🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(evals): add code-based eval (#13685)
Tobias Wochingercf24ee840af9
diff --git a/.env.dev.example b/.env.dev.exampleindex 4dcd0e7b08..b2d12ef0db 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -71,6 +71,9 @@ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION="DEV"# Langfuse experimental featuresLANGFUSE_ENABLE_EXPERIMENTAL_FEATURES="false"+# Code-based evals (if set to "true", code evaluator templates will be shown in the UI)+NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED="false"+# Salt for API key hashingSALT="salt"@@ -139,6 +142,18 @@ NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT="false"# LANGFUSE_EVAL_EXECUTION_WORKER_CONCURRENCY=5# LANGFUSE_LLM_AS_JUDGE_EXECUTION_WORKER_CONCURRENCY=5+# Code-based eval dispatchers. Local dev defaults to the insecure in-process dispatcher.+# To explicitly use the local dispatcher, set:+# LANGFUSE_CODE_EVAL_DISPATCHER=insecure-local+# To test the AWS Lambda dispatcher against Floci, set:+# LANGFUSE_CODE_EVAL_DISPATCHER=aws-lambda+# LANGFUSE_CODE_EVAL_AWS_LAMBDA_ENDPOINT=http://localhost:4566+# Override Lambda function names if your deployment uses non-default names:+# LANGFUSE_CODE_EVAL_AWS_LAMBDA_NODE_FUNCTION_NAME=code-based-eval-executor-node+# LANGFUSE_CODE_EVAL_AWS_LAMBDA_PYTHON_FUNCTION_NAME=code-based-eval-executor-python+# Override the local dispatcher execution timeout (default: 2000ms):+# LANGFUSE_CODE_EVAL_LOCAL_TIMEOUT_MS=2000+# Slack credentials for developmentSLACK_CLIENT_ID=your_slack_client_idSLACK_CLIENT_SECRET=your_slack_client_secretdiff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex 8290adcf69..202978e46c 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -514,6 +514,9 @@ jobs:run: |docker compose -f docker-compose.dev${{ matrix.deploy-mode }}.yml up -d --wait --wait-timeout 180docker compose ps+ env:+ # Only start the extra floci container for default worker tests to avoid overhead elsewhere.+ COMPOSE_PROFILES: ${{ matrix.deploy-mode == '' && 'worker-tests' || '' }}- name: Ensure no unhealthy statusrun: |if docker compose ps | grep "(unhealthy)"; then@@ -542,7 +545,8 @@ jobs:run: pnpm --filter=worker... run build- name: run testsrun: pnpm --filter=worker run test:exclude-llm-connections-+ env:+ LANGFUSE_CODE_EVAL_AWS_LAMBDA_ENDPOINT: ${{ matrix.deploy-mode == '' && 'http://localhost:4566' || '' }}test-worker-llm-connections:timeout-minutes: 20runs-on: blacksmith-4vcpu-ubuntu-2404diff --git a/.gitignore b/.gitignoreindex 134f7a8634..b1c96d31aa 100644--- a/.gitignore+++ b/.gitignore@@ -55,6 +55,10 @@ yarn-error.log*# typescript*.tsbuildinfo+# python+__pycache__/+*.py[cod]+/generated# openapi spec that is copied during builddiff --git a/.semgrepignore b/.semgrepignorenew file mode 100644index 0000000000..9587277b8a--- /dev/null+++ b/.semgrepignore@@ -0,0 +1,6 @@+# Code-eval runners are Lambda handler test fixtures (Node + Python). They+# intentionally execute user-supplied evaluator source via `exec` / dynamic+# `import` and talk to a locally-provisioned Floci endpoint from+# `urllib.request.urlopen`. Both are by design and inherent to the runner+# contract — scanning them produces noise, not signal.+scripts/code-eval-runners/diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 65e1f937be..02b3178d65 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -49,6 +49,27 @@ services:networks:- default+ floci:+ profiles:+ - worker-tests+ image: docker.io/floci/floci:1.5.17-compat+ user: "0"+ container_name: ${FLOCI_CONTAINER_NAME:-langfuse-floci}+ environment:+ FLOCI_HOSTNAME: floci+ FLOCI_INIT_HOOKS_TIMEOUT_SECONDS: 120+ ports:+ - ${HOST_IP:-127.0.0.1}:${FLOCI_PORT:-4566}:4566+ volumes:+ # Floci Lambda starts real Docker containers for function invocations.+ # See: https://floci.io/floci/services/lambda/+ - /var/run/docker.sock:/var/run/docker.sock+ # The init hook packages these local runner sources into Lambda ZIPs on startup.+ - ./scripts/code-eval-runners:/opt/code-eval-runners:ro+ - ./scripts/code-eval-runners/bootstrap-floci.py:/etc/floci/init/ready.d/01-bootstrap-code-eval-runners.py:ro+ networks:+ - default+redis:image: docker.io/redis:7.2.4container_name: ${REDIS_CONTAINER_NAME:-langfuse-redis}diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex a448ece17a..128745ec93 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -87,6 +87,7 @@"dependencies": {"@anthropic-ai/tokenizer": "^0.0.4","@aws-sdk/client-cloudwatch": "^3.1013.0",+ "@aws-sdk/client-lambda": "^3.1046.0","@aws-sdk/client-s3": "^3.1013.0","@aws-sdk/client-sesv2": "^3.1013.0","@aws-sdk/lib-storage": "^3.1013.0",diff --git a/packages/shared/prisma/migrations/20260518090000_add_code_eval_template_fields/migration.sql b/packages/shared/prisma/migrations/20260518090000_add_code_eval_template_fields/migration.sqlnew file mode 100644index 0000000000..0a886a3888--- /dev/null+++ b/packages/shared/prisma/migrations/20260518090000_add_code_eval_template_fields/migration.sql@@ -0,0 +1,15 @@+-- CreateEnum+CREATE TYPE "EvalTemplateType" AS ENUM ('LLM_AS_JUDGE', 'CODE');++-- CreateEnum+CREATE TYPE "EvalTemplateSourceCodeLanguage" AS ENUM ('PYTHON', 'TYPESCRIPT');++-- AlterTable+ALTER TABLE "eval_templates"+ADD COLUMN "type" "EvalTemplateType" NOT NULL DEFAULT 'LLM_AS_JUDGE',+ADD COLUMN "source_code" VARCHAR(262144),+ADD COLUMN "source_code_language" "EvalTemplateSourceCodeLanguage";++ALTER TABLE "eval_templates"+ALTER COLUMN "prompt" DROP NOT NULL,+ALTER COLUMN "output_schema" DROP NOT NULL;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 7de7c0c7c9..eb650b21b9 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -923,23 +923,36 @@ model EvalTemplate {name Stringversion Int- prompt String+ prompt String?+ type EvalTemplateType @default(LLM_AS_JUDGE)partner String? // e.g. "ragas", describes the partner that created the template- model String?- provider String?- modelParams Json? @map("model_params")- vars String[] @default([])- outputDefinition Json @map("output_schema")- JobConfiguration JobConfiguration[]- JobExecution JobExecution[]+ model String?+ provider String?+ modelParams Json? @map("model_params")+ vars String[] @default([])+ outputDefinition Json? @map("output_schema")+ sourceCode String? @map("source_code") @db.VarChar(262144)+ sourceCodeLanguage EvalTemplateSourceCodeLanguage? @map("source_code_language")+ JobConfiguration JobConfiguration[]+ JobExecution JobExecution[]@@unique([projectId, name, version])@@index([projectId, id])@@map("eval_templates")}+enum EvalTemplateType {+ LLM_AS_JUDGE+ CODE+}++enum EvalTemplateSourceCodeLanguage {+ PYTHON+ TYPESCRIPT+}+// We currently assume in evaluator execution-count queries that _all_ job_executions are for EVAL job_configs.// If we ever extend this, we need to adjust the filter condition there. ref.: getEvaluatorExecutionStatusCounts.enum JobType {diff --git a/packages/shared/scripts/seeder/seed-postgres.ts b/packages/shared/scripts/seeder/seed-postgres.tsindex 30cab5f7ed..116f0a1a8e 100644--- a/packages/shared/scripts/seeder/seed-postgres.ts+++ b/packages/shared/scripts/seeder/seed-postgres.ts@@ -4,6 +4,8 @@ import { hash } from "bcryptjs";import { v4 } from "uuid";import { encrypt } from "../../src/encryption";import {+ EvalTemplateSourceCodeLanguage,+ EvalTemplateType,type JobConfiguration,JobExecutionStatus,PrismaClient,@@ -297,6 +299,8 @@ async function main() {// add eval objectsfor (const evalTemplate of SEED_EVALUATOR_TEMPLATES) {+ const evalTemplateType = evalTemplate.type as EvalTemplateType;+await prisma.evalTemplate.upsert({where: {projectId_name_version: {@@ -310,12 +314,18 @@ async function main() {projectId: project1.id,name: evalTemplate.name,version: evalTemplate.version,- prompt: evalTemplate.prompt,- model: evalTemplate.model,+ type: evalTemplateType,+ prompt: evalTemplate.prompt ?? null,+ model: evalTemplate.model ?? null,vars: evalTemplate.vars,- provider: evalTemplate.provider,- outputDefinition: evalTemplate.outputDefinition,- modelParams: evalTemplate.modelParams,+ provider: evalTemplate.provider ?? null,+ outputDefinition: evalTemplate.outputDefinition ?? undefined,+ modelParams: evalTemplate.modelParams ?? undefined,+ sourceCode: evalTemplate.sourceCode ?? null,+ sourceCodeLanguage:+ (evalTemplate.sourceCodeLanguage as+ | EvalTemplateSourceCodeLanguage+ | undefined) ?? null,},update: {},});diff --git a/packages/shared/scripts/seeder/utils/postgres-seed-constants.ts b/packages/shared/scripts/seeder/utils/postgres-seed-constants.tsindex 161ec5b432..d11bcd8ba1 100644--- a/packages/shared/scripts/seeder/utils/postgres-seed-constants.ts+++ b/packages/shared/scripts/seeder/utils/postgres-seed-constants.ts@@ -687,6 +687,7 @@ export const SEED_EVALUATOR_TEMPLATES = [id: "toxicity-template",name: "toxicity-template",version: 1,+ type: "LLM_AS_JUDGE",prompt:"Please evaluate the toxicity of the following text {{input}} {{output}}",model: "gpt-3.5-turbo",@@ -701,6 +702,50 @@ export const SEED_EVALUATOR_TEMPLATES = [outputTokenLimit: 100,topP: 0.9,},+ sourceCode: null,+ sourceCodeLanguage: null,+ },+ {+ id: "typescript-code-eval-template",+ name: "typescript-code-eval-template",+ version: 1,+ type: "CODE",+ prompt: null,+ model: null,+ vars: [+ "input",+ "output",+ "metadata",+ "experimentItemExpectedOutput",+ "experimentItemMetadata",+ ],+ provider: null,+ outputDefinition: null,+ modelParams: null,+ sourceCodeLanguage: "TYPESCRIPT",+ sourceCode: `function evaluate(ctx: {+ observation: {+ input: unknown;+ output: unknown;+ metadata: unknown;+ };+}) {+ const hasOutput = ctx.observation.output !== null && ctx.observation.output !== undefined;++ return {+ scores: [+ {+ name: "has-output",+ value: hasOutput ? 1 : 0,+ dataType: "BOOLEAN",+ comment: hasOutput+ ? "Observation has an output."+ : "Observation is missing an output.",+ },+ ],+ };+}+`,},];diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex 1389053646..d34965c60f 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -152,6 +152,25 @@ const EnvSchema = z.object({.number().positive().default(1),+ LANGFUSE_CODE_EVAL_EXECUTION_QUEUE_SHARD_COUNT: z.coerce+ .number()+ .positive()+ .default(1),+ LANGFUSE_CODE_EVAL_DISPATCHER: z+ .enum(["insecure-local", "aws-lambda"])+ .optional(),+ LANGFUSE_CODE_EVAL_AWS_LAMBDA_ENDPOINT: z.string().optional(),+ LANGFUSE_CODE_EVAL_AWS_LAMBDA_NODE_FUNCTION_NAME: z+ .string()+ .default("code-based-eval-executor-node"),+ LANGFUSE_CODE_EVAL_AWS_LAMBDA_PYTHON_FUNCTION_NAME: z+ .string()+ .default("code-based-eval-executor-python"),+ LANGFUSE_CODE_EVAL_LOCAL_TIMEOUT_MS: z.coerce+ .number()+ .int()+ .positive()+ .default(2_000),LANGFUSE_TRACE_UPSERT_QUEUE_SHARD_COUNT: z.coerce.number().positive()diff --git a/packages/shared/src/features/evals/types.ts b/packages/shared/src/features/evals/types.tsindex 4c2bc32028..6690cc24c3 100644--- a/packages/shared/src/features/evals/types.ts+++ b/packages/shared/src/features/evals/types.ts@@ -1,5 +1,30 @@+import {+ EvalTemplateSourceCodeLanguage,+ EvalTemplateType,+ type EvalTemplate,+} from "@prisma/client";import z from "zod";+export type EvalTemplateLlmAsAJudge = EvalTemplate & {+ type: typeof EvalTemplateType.LLM_AS_JUDGE;+ prompt: string;+ outputDefinition: NonNullable<EvalTemplate["outputDefinition"]>;+ sourceCode: null;+ sourceCodeLanguage: null;+};++export type EvalTemplateCodeBased = EvalTemplate & {+ type: typeof EvalTemplateType.CODE;+ prompt: null;+ outputDefinition: null;+ sourceCode: string;+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage;+};++export type EvalTemplateWithType =+ | EvalTemplateLlmAsAJudge+ | EvalTemplateCodeBased;+export const EvalTargetObject = {TRACE: "trace",DATASET: "dataset",diff --git a/packages/shared/src/features/evals/utilities.ts b/packages/shared/src/features/evals/utilities.tsindex 2e9c88897c..65d012b9ee 100644--- a/packages/shared/src/features/evals/utilities.ts+++ b/packages/shared/src/features/evals/utilities.ts@@ -78,7 +78,7 @@ export function extractValueFromObject(selectedColumnId: string,jsonSelector?: string,parseJson?: (selectedColumn: unknown, jsonSelector: string) => unknown,-): { value: string; error: Error | null } {+): { value: unknown; error: Error | null } {const selectedColumn = obj[selectedColumnId];const jsonParser = parseJson || parseJsonDefault;@@ -107,8 +107,26 @@ export function extractValueFromObject(jsonSelectedColumn = selectedColumn;}- return {- value: parseUnknownToString(jsonSelectedColumn),- error,- };+ return { value: jsonSelectedColumn, error };+}++/**+ * Backwards-compatible extraction for UI prompt previews and LLM prompt+ * rendering. `extractValueFromObject` preserves typed values for code eval;+ * this wrapper keeps the previous string-only behavior for prompt surfaces.+ */+export function extractValueFromObjectAsString(+ obj: Record<string, unknown>,+ selectedColumnId: string,+ jsonSelector?: string,+ parseJson?: (selectedColumn: unknown, jsonSelector: string) => unknown,+): { value: string; error: Error | null } {+ const { value, error } = extractValueFromObject(+ obj,+ selectedColumnId,+ jsonSelector,+ parseJson,+ );++ return { value: parseUnknownToString(value), error };}diff --git a/packages/shared/src/server/evals/awsLambdaCodeEvalDispatcher.ts b/packages/shared/src/server/evals/awsLambdaCodeEvalDispatcher.tsnew file mode 100644index 0000000000..a14caa527a--- /dev/null+++ b/packages/shared/src/server/evals/awsLambdaCodeEvalDispatcher.ts@@ -0,0 +1,393 @@+import {+ InvokeCommand,+ LambdaClient,+ type InvokeCommandInput,+} from "@aws-sdk/client-lambda";+import { z } from "zod";+import { logger } from "../logger";+import {+ assertDispatchInputWithinLimits,+ assertDispatchResultWithinByteLimit,+ CodeEvalDispatcherError,+ CodeEvalDispatcherErrorCode,+ CodeEvalDispatcherErrorCodes,+ parseDispatchResult,+ type CodeEvalDispatcher,+ type CodeEvalRuntimeLanguage,+ type DispatchInput,+ type DispatchResult,+} from "./codeEvalDispatcherTypes";++export const DEFAULT_LAMBDA_FUNCTION_BY_LANGUAGE = {+ PYTHON: "code-based-eval-executor-python",+ TYPESCRIPT: "code-based-eval-executor-node",+} satisfies Record<CodeEvalRuntimeLanguage, string>;++// Synchronous Lambda invokes hold the HTTP request open through cold starts and user code execution.+const LAMBDA_INVOKE_REQUEST_TIMEOUT_MS = 10_000;++type CodeEvalDispatcherErrorClassification = {+ code: CodeEvalDispatcherErrorCode;+ retryable?: boolean;+};++// Defensive: today our runners only emit non-retryable user-code codes, so+// this is only consulted if a future runner surfaces one of them via the+// user-code-error envelope.+const RETRYABLE_ERROR_CODES = new Set<CodeEvalDispatcherErrorCode>([+ CodeEvalDispatcherErrorCodes.TIMEOUT,+ CodeEvalDispatcherErrorCodes.LAMBDA_CONCURRENCY_LIMIT,+ CodeEvalDispatcherErrorCodes.LAMBDA_INVOCATION_ERROR,+]);++// Skipped from warn-level logging so routine user failures don't drown out+// infrastructure issues in Datadog.+const USER_ERROR_CODES = new Set<CodeEvalDispatcherErrorCode>([+ CodeEvalDispatcherErrorCodes.INVALID_RESULT,+ CodeEvalDispatcherErrorCodes.INVALID_SOURCE,+ CodeEvalDispatcherErrorCodes.PAYLOAD_TOO_LARGE,+ CodeEvalDispatcherErrorCodes.RESULT_TOO_LARGE,+ CodeEvalDispatcherErrorCodes.SOURCE_TOO_LARGE,+ CodeEvalDispatcherErrorCodes.USER_CODE_ERROR,+]);++const AWS_ERROR_CLASSIFICATION_BY_NAME: Record<+ string,+ CodeEvalDispatcherErrorClassification+> = {+ TooManyRequestsException: {+ code: CodeEvalDispatcherErrorCodes.LAMBDA_CONCURRENCY_LIMIT,+ retryable: true,+ },+ AccessDeniedException: {+ code: CodeEvalDispatcherErrorCodes.LAMBDA_CONFIGURATION_ERROR,+ },+ InvalidParameterValueException: {+ code: CodeEvalDispatcherErrorCodes.LAMBDA_CONFIGURATION_ERROR,+ },+ // Unified with the local pre-check so "payload too large" failures share+ // a single code regardless of which layer caught them.+ RequestTooLargeException: {+ code: CodeEvalDispatcherErrorCodes.PAYLOAD_TOO_LARGE,+ },+ ResourceNotFoundException: {+ code: CodeEvalDispatcherErrorCodes.LAMBDA_CONFIGURATION_ERROR,+ },+ ResourceConflictException: {+ code: CodeEvalDispatcherErrorCodes.LAMBDA_INVOCATION_ERROR,+ retryable: true,+ },+ ServiceException: {+ code: CodeEvalDispatcherErrorCodes.LAMBDA_INVOCATION_ERROR,+ retryable: true,+ },+};++const AWS_ERROR_CLASSIFICATION_BY_CODE: Record<+ string,+ CodeEvalDispatcherErrorClassification+> = {+ ECONNRESET: {+ code: CodeEvalDispatcherErrorCodes.LAMBDA_INVOCATION_ERROR,+ retryable: true,+ },+ ETIMEDOUT: {+ code: CodeEvalDispatcherErrorCodes.LAMBDA_INVOCATION_ERROR,+ retryable: true,+ },+};++// `.strict()` ensures a runner that returns a valid dispatch result alongside+// an `error` field (e.g. `{ scores: [...], error: { code, message } }`) cannot+// match here — defense in depth for the user-code envelope.+const UserCodeErrorFieldsSchema = z+ .object({+ code: CodeEvalDispatcherErrorCode,+ message: z.string(),+ })+ .strict();++const UserCodeErrorSchema = z.union([+ z+ .object({ error: UserCodeErrorFieldsSchema })+ .strict()+ .transform(({ error }) => error),+ UserCodeErrorFieldsSchema,+]);++type UserCodeError = z.infer<typeof UserCodeErrorSchema>;++// Process-singleton client so the AWS SDK's Keep-Alive connection pool is+// reused across all dispatcher instances. In practice the process sees one+// endpoint for its lifetime (real AWS or the Floci dev endpoint); the+// endpoint-mismatch guard exists so a future caller that passes a different+// endpoint without injecting a client doesn't silently get a stale one.+let sharedLambdaClient: LambdaClient | undefined;+let sharedLambdaClientEndpoint: string | undefined;++function getSharedLambdaClient(endpoint?: string): LambdaClient {+ if (sharedLambdaClient && sharedLambdaClientEndpoint === endpoint) {+ return sharedLambdaClient;+ }+ sharedLambdaClient = new LambdaClient({+ ...(endpoint ? { endpoint } : {}),+ requestHandler: {+ requestTimeout: LAMBDA_INVOKE_REQUEST_TIMEOUT_MS,+ throwOnRequestTimeout: true,+ },+ });+ sharedLambdaClientEndpoint = endpoint;+ return sharedLambdaClient;+}++export class AwsLambdaCodeEvalDispatcher implements CodeEvalDispatcher {+ public readonly name = "aws-lambda";+ private readonly lambdaClient: LambdaClient;+ private readonly functionNameByLanguage: Record<+ CodeEvalRuntimeLanguage,+ string+ >;++ constructor(params?: {+ lambdaClient?: LambdaClient;+ endpoint?: string;+ functionNameByLanguage?: Partial<Record<CodeEvalRuntimeLanguage, string>>;+ }) {+ this.lambdaClient =+ params?.lambdaClient ?? getSharedLambdaClient(params?.endpoint);+ this.functionNameByLanguage = {+ ...DEFAULT_LAMBDA_FUNCTION_BY_LANGUAGE,+ ...params?.functionNameByLanguage,+ };+ }++ async dispatch(input: DispatchInput): Promise<DispatchResult> {+ const serializedPayload = assertDispatchInputWithinLimits(input);+ const functionName = this.functionNameByLanguage[input.runtime.language];++ try {+ const commandInput: InvokeCommandInput = {+ FunctionName: functionName,+ InvocationType: "RequestResponse",+ Payload: Buffer.from(serializedPayload),+ TenantId: `${input.scope.organizationId}:${input.scope.projectId}`,+ };++ const response = await this.lambdaClient.send(+ new InvokeCommand(commandInput),+ );++ // Lambda function errors come back as HTTP 200 with `FunctionError`+ // set; the SDK does NOT throw for these. SDK service exceptions+ // (throttling, auth, etc.) hit the outer catch instead.+ // https://docs.aws.amazon.com/lambda/latest/dg/invocation-errors.html+ if (response.FunctionError) {+ throw classifyLambdaFunctionError({+ functionName,+ functionError: response.FunctionError,+ payload: response.Payload,+ });+ }++ if (!response.Payload) {+ throw new CodeEvalDispatcherError(+ `Code eval Lambda ${functionName} returned an empty response`,+ {+ code: CodeEvalDispatcherErrorCodes.LAMBDA_INVOCATION_ERROR,+ retryable: true,+ },+ );+ }++ return parseLambdaResponsePayload({+ functionName,+ payload: response.Payload,+ });+ } catch (error) {+ if (error instanceof CodeEvalDispatcherError) {+ logDispatcherError({ functionName, error });+ throw error;+ }++ const awsError = classifyAwsLambdaError(error);+ const dispatcherError = new CodeEvalDispatcherError(+ `Failed to invoke code eval Lambda ${functionName}: ${error instanceof Error ? error.message : String(error)}`,+ { ...awsError, cause: error },+ );+ logDispatcherError({ functionName, error: dispatcherError });+ throw dispatcherError;+ }+ }+}++// Warn on non-user errors only, so infrastructure issues surface in Datadog+// without drowning the channel in routine user-template failures.+function logDispatcherError(params: {+ functionName: string;+ error: CodeEvalDispatcherError;+}): void {+ if (USER_ERROR_CODES.has(params.error.code)) return;++ logger.warn(+ `Code eval Lambda ${params.functionName} dispatcher failed: ${params.error.message}`,+ {+ code: params.error.code,+ retryable: params.error.retryable,+ },+ );+}++function classifyLambdaFunctionError(params: {+ functionName: string;+ functionError: string;+ payload: Uint8Array | undefined;+}): CodeEvalDispatcherError {+ const errorPayload = parseLambdaErrorPayload(params.payload);++ // Our runners emit `{ error: { code, message } }` on user-code failures.+ const userCodeError = parseUserCodeError(errorPayload);+ if (userCodeError) {+ return createCodeEvalDispatcherErrorFromUserCodeError(userCodeError);+ }++ // AWS-runtime error envelope: `{ errorMessage, errorType, stackTrace? }`.+ const record = isRecord(errorPayload) ? errorPayload : null;+ const errorType =+ typeof record?.errorType === "string" ? record.errorType : null;+ const errorMessage =+ typeof record?.errorMessage === "string" ? record.errorMessage : null;+ const composedMessage =+ errorType && errorMessage+ ? `${errorType}: ${errorMessage}`+ : (errorMessage ?? errorType ?? "");++ if (+ errorType === "Function.TimedOut" ||+ errorType === "Sandbox.Timedout" ||+ (errorMessage && isTimeoutErrorMessage(errorMessage))+ ) {+ return new CodeEvalDispatcherError(+ composedMessage || "Lambda task timed out",+ { code: CodeEvalDispatcherErrorCodes.TIMEOUT, retryable: true },+ );+ }++ // Abnormal runtime exit (OOM kill, segfault, process.exit, SIGKILL).+ // Retrying never recovers from these.+ if (errorType === "Runtime.ExitError") {+ return new CodeEvalDispatcherError(+ composedMessage || "Lambda runtime exited abnormally",+ {+ code: CodeEvalDispatcherErrorCodes.LAMBDA_CONFIGURATION_ERROR,+ retryable: false,+ },+ );+ }++ // The managed runtime caught a user-code exception and populated+ // errorType + errorMessage with the language-specific class and message.+ if (params.functionError === "Handled") {+ return new CodeEvalDispatcherError(+ composedMessage || "Evaluator code threw an uncaught exception",+ { code: CodeEvalDispatcherErrorCodes.USER_CODE_ERROR, retryable: false },+ );+ }++ // Unknown failure — default retryable so a flake doesn't burn the job.+ return new CodeEvalDispatcherError(+ composedMessage ||+ `Code eval Lambda ${params.functionName} failed with ${params.functionError}`,+ {+ code: CodeEvalDispatcherErrorCodes.LAMBDA_INVOCATION_ERROR,+ retryable: true,+ },+ );+}++function createCodeEvalDispatcherErrorFromUserCodeError(+ userCodeError: UserCodeError,+): CodeEvalDispatcherError {+ return new CodeEvalDispatcherError(userCodeError.message, {+ code: userCodeError.code,+ retryable: RETRYABLE_ERROR_CODES.has(userCodeError.code),+ });+}++function classifyAwsLambdaError(+ error: unknown,+): CodeEvalDispatcherErrorClassification {+ if (!(error instanceof Error)) {+ return {+ code: CodeEvalDispatcherErrorCodes.LAMBDA_INVOCATION_ERROR,+ retryable: true,+ };+ }++ const errorCode = (error as { code?: unknown }).code;++ return (+ AWS_ERROR_CLASSIFICATION_BY_NAME[error.name] ??+ (typeof errorCode === "string"+ ? AWS_ERROR_CLASSIFICATION_BY_CODE[errorCode]+ : undefined) ?? {+ code: CodeEvalDispatcherErrorCodes.LAMBDA_INVOCATION_ERROR,+ retryable: true,+ }+ );+}++function parseLambdaResponsePayload(params: {+ functionName: string;+ payload: Uint8Array;+}): DispatchResult {+ assertDispatchResultWithinByteLimit(params.payload.byteLength);++ const responseBody = Buffer.from(params.payload).toString("utf8");++ let parsed: unknown;+ try {+ parsed = JSON.parse(responseBody) as unknown;+ } catch (error) {+ throw new CodeEvalDispatcherError(+ `Code eval Lambda ${params.functionName} returned invalid JSON`,+ { code: CodeEvalDispatcherErrorCodes.INVALID_RESULT, cause: error },+ );+ }++ // Try the success shape first so a runner can't smuggle an `error`+ // envelope alongside valid scores to force a retry or mask the outcome.+ try {+ return parseDispatchResult(parsed);+ } catch (dispatchError) {+ const userCodeError = parseUserCodeError(parsed);+ if (userCodeError) {+ throw createCodeEvalDispatcherErrorFromUserCodeError(userCodeError);+ }+ throw dispatchError;+ }+}++function parseUserCodeError(payload: unknown): UserCodeError | null {+ return UserCodeErrorSchema.safeParse(payload).data ?? null;+}++function parseLambdaErrorPayload(payload: Uint8Array | undefined): unknown {+ if (!payload) return null;++ try {+ return JSON.parse(Buffer.from(payload).toString("utf8")) as unknown;+ } catch {+ return null;+ }+}++function isTimeoutErrorMessage(message: string): boolean {+ const normalized = message.toLowerCase();+ return (+ normalized.includes("task timed out") || normalized.includes("timeout")+ );+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/packages/shared/src/server/evals/codeEvalDispatcherTypes.ts b/packages/shared/src/server/evals/codeEvalDispatcherTypes.tsnew file mode 100644index 0000000000..3f0f2d3ffe--- /dev/null+++ b/packages/shared/src/server/evals/codeEvalDispatcherTypes.ts@@ -0,0 +1,213 @@+import { z } from "zod";+import { ScoreDataTypeEnum, TEXT_SCORE_MAX_LENGTH } from "../../domain/scores";++export const CODE_EVAL_SOURCE_MAX_BYTES = 256 * 1024;+export const CODE_EVAL_DISPATCH_PAYLOAD_MAX_BYTES = 5.5 * 1024 * 1024;+export const CODE_EVAL_DISPATCH_RESULT_MAX_BYTES = 256 * 1024;+// TODO: Replace with a dedicated code-based evaluator limits docs page.+export const CODE_EVAL_DOCS_URL =+ "https://langfuse.com/docs/evaluation/overview";++export function withCodeEvalDocs(message: string): string {+ const trimmedMessage = message.trim();+ const punctuatedMessage = /[.!?]$/.test(trimmedMessage)+ ? trimmedMessage+ : `${trimmedMessage}.`;++ return `${punctuatedMessage} See ${CODE_EVAL_DOCS_URL} for details.`;+}++export const CodeEvalRuntimeLanguage = z.enum(["PYTHON", "TYPESCRIPT"]);+export type CodeEvalRuntimeLanguage = z.infer<typeof CodeEvalRuntimeLanguage>;++export type CodeEvalScope = {+ organizationId: string;+ projectId: string;+ evaluatorId: string;+};++export type CodeEvalPayload = {+ observation: {+ input: unknown;+ output: unknown;+ metadata: unknown;+ };+ experiment?: {+ itemExpectedOutput: unknown;+ itemMetadata: unknown;+ };+};++export type DispatchInput = {+ scope: CodeEvalScope;+ runtime: { language: CodeEvalRuntimeLanguage };+ execution: {+ jobExecutionId: string;+ };+ code: {+ source: string;+ };+ payload: CodeEvalPayload;+};++const codeEvalScoreBase = {+ name: z.string().min(1),+ comment: z.string().nullish(),+ configId: z.string().nullish(),+ metadata: z.record(z.string(), z.unknown()).optional(),+};++const CodeEvalScoreSchema = z.union([+ z.object({+ ...codeEvalScoreBase,+ value: z.number(),+ dataType: z.literal(ScoreDataTypeEnum.NUMERIC),+ }),+ z.object({+ ...codeEvalScoreBase,+ value: z.string(),+ dataType: z.literal(ScoreDataTypeEnum.CATEGORICAL),+ }),+ z.object({+ ...codeEvalScoreBase,+ // BOOLEAN explicitly signals intent, so accept the values users most+ // commonly return — native booleans, 0/1, and string forms ("true"/+ // "false"/"1"/"0", case-insensitive) — and normalize to the 0/1 wire+ // encoding the score ingestion expects.+ value: z+ .union([z.literal(0), z.literal(1), z.boolean(), z.string()])+ .transform((v, ctx): 0 | 1 => {+ if (v === 0 || v === 1) return v;+ if (typeof v === "boolean") return v ? 1 : 0;++ const normalized = v.trim().toLowerCase();+ if (normalized === "true" || normalized === "1") return 1;+ if (normalized === "false" || normalized === "0") return 0;++ ctx.addIssue({+ code: "custom",+ message: `Invalid boolean value: ${JSON.stringify(v)}`,+ });+ return z.NEVER;+ }),+ dataType: z.literal(ScoreDataTypeEnum.BOOLEAN),+ }),+ z.object({+ ...codeEvalScoreBase,+ // Mirror the public ingestion `ScoreBody` cap on TEXT score length so that+ // an oversized TEXT value fails fast as a non-retryable `INVALID_RESULT`+ // at the dispatcher, instead of being silently dropped later by the+ // ingestion consumer after the `JobExecution` is already marked+ // COMPLETED.+ value: z.string().min(1).max(TEXT_SCORE_MAX_LENGTH),+ dataType: z.literal(ScoreDataTypeEnum.TEXT),+ }),+ z.object({+ ...codeEvalScoreBase,+ value: z.union([z.string(), z.number()]),+ dataType: z.undefined().optional(),+ }),+]);++const CodeEvalDispatchResultSchema = z.object({+ scores: z.array(CodeEvalScoreSchema).min(1),+});++export type CodeEvalScore = z.infer<typeof CodeEvalScoreSchema>;+export type CodeEvalScoreWithName = CodeEvalScore;+export type DispatchResult = z.infer<typeof CodeEvalDispatchResultSchema>;++export interface CodeEvalDispatcher {+ name: string;+ dispatch(input: DispatchInput): Promise<DispatchResult>;+}++export const CodeEvalDispatcherErrorCode = z.enum([+ "INVALID_RESULT",+ "INVALID_SOURCE",+ "PAYLOAD_TOO_LARGE",+ "RESULT_TOO_LARGE",+ "SOURCE_TOO_LARGE",+ "TIMEOUT",+ "UNSUPPORTED_RUNTIME",+ "USER_CODE_ERROR",+ "LAMBDA_CONCURRENCY_LIMIT",+ "LAMBDA_CONFIGURATION_ERROR",+ "LAMBDA_INVOCATION_ERROR",+]);+export type CodeEvalDispatcherErrorCode = z.infer<+ typeof CodeEvalDispatcherErrorCode+>;+export const CodeEvalDispatcherErrorCodes = CodeEvalDispatcherErrorCode.enum;++export class CodeEvalDispatcherError extends Error {+ public readonly code: CodeEvalDispatcherErrorCode;+ public readonly retryable: boolean;++ constructor(+ message: string,+ options: {+ code: CodeEvalDispatcherErrorCode;+ retryable?: boolean;+ cause?: unknown;+ },+ ) {+ super(message, { cause: options.cause });+ this.name = "CodeEvalDispatcherError";+ this.code = options.code;+ this.retryable = options.retryable ?? false;+ }+}++export type CodeEvalDispatcherName = "insecure-local" | "aws-lambda";++export function assertDispatchInputWithinLimits(input: DispatchInput): string {+ const sourceBytes = Buffer.byteLength(input.code.source, "utf8");+ if (sourceBytes > CODE_EVAL_SOURCE_MAX_BYTES) {+ throw new CodeEvalDispatcherError(+ `Code eval source exceeds the ${CODE_EVAL_SOURCE_MAX_BYTES} byte limit`,+ { code: CodeEvalDispatcherErrorCodes.SOURCE_TOO_LARGE },+ );+ }++ const serializedInput = JSON.stringify(input);+ const payloadBytes = Buffer.byteLength(serializedInput, "utf8");+ if (payloadBytes > CODE_EVAL_DISPATCH_PAYLOAD_MAX_BYTES) {+ throw new CodeEvalDispatcherError(+ `Code eval dispatch payload exceeds the ${CODE_EVAL_DISPATCH_PAYLOAD_MAX_BYTES} byte limit`,+ { code: CodeEvalDispatcherErrorCodes.PAYLOAD_TOO_LARGE },+ );+ }++ return serializedInput;+}++/**+ * Guard against malicious or runaway evaluator output that would blow up+ * downstream score ingestion and ClickHouse writes. Each dispatcher is+ * expected to call this with the byte size at its cheapest representation:+ * Lambda has the raw response bytes (`response.Payload.byteLength`) so the+ * check is free; the local dispatcher must serialize the in-memory result+ * because there is no wire payload.+ */+export function assertDispatchResultWithinByteLimit(byteSize: number): void {+ if (byteSize > CODE_EVAL_DISPATCH_RESULT_MAX_BYTES) {+ throw new CodeEvalDispatcherError(+ `Code eval result exceeds the ${CODE_EVAL_DISPATCH_RESULT_MAX_BYTES} byte limit`,+ { code: CodeEvalDispatcherErrorCodes.RESULT_TOO_LARGE },+ );+ }+}++export function parseDispatchResult(result: unknown): DispatchResult {+ const parsed = CodeEvalDispatchResultSchema.safeParse(result);++ if (!parsed.success) {+ throw new CodeEvalDispatcherError(+ `Invalid code eval result: ${parsed.error.message}`,+ { code: CodeEvalDispatcherErrorCodes.INVALID_RESULT },+ );+ }++ return parsed.data;+}diff --git a/packages/shared/src/server/evals/codeEvalDispatchers.ts b/packages/shared/src/server/evals/codeEvalDispatchers.tsnew file mode 100644index 0000000000..644f0762cd--- /dev/null+++ b/packages/shared/src/server/evals/codeEvalDispatchers.ts@@ -0,0 +1,43 @@+import { env } from "../../env";+import { logger } from "../logger";+import { AwsLambdaCodeEvalDispatcher } from "./awsLambdaCodeEvalDispatcher";+import { LocalCodeEvalDispatcher } from "./localCodeEvalDispatcher";+import type { CodeEvalDispatcher } from "./codeEvalDispatcherTypes";++export * from "./awsLambdaCodeEvalDispatcher";+export * from "./codeEvalDispatcherTypes";+export * from "./localCodeEvalDispatcher";++let hasLoggedInsecureLocalWarning = false;++export function resolveConfiguredCodeEvalDispatcher(): CodeEvalDispatcher | null {+ const dispatcherName =+ env.LANGFUSE_CODE_EVAL_DISPATCHER ??+ (env.NODE_ENV === "development" || env.NODE_ENV === "test"+ ? "insecure-local"+ : undefined);++ if (!dispatcherName) return null;++ if (dispatcherName === "insecure-local") {+ if (!hasLoggedInsecureLocalWarning) {+ logger.warn(+ "Using the `insecure-local` code-eval dispatcher. Code evals will execute user-provided code in the worker process. Only use this with trusted code, local development, or tests.",+ );+ hasLoggedInsecureLocalWarning = true;+ }+ return new LocalCodeEvalDispatcher();+ }++ if (dispatcherName === "aws-lambda") {+ return new AwsLambdaCodeEvalDispatcher({+ endpoint: env.LANGFUSE_CODE_EVAL_AWS_LAMBDA_ENDPOINT,+ functionNameByLanguage: {+ PYTHON: env.LANGFUSE_CODE_EVAL_AWS_LAMBDA_PYTHON_FUNCTION_NAME,+ TYPESCRIPT: env.LANGFUSE_CODE_EVAL_AWS_LAMBDA_NODE_FUNCTION_NAME,+ },+ });+ }++ return null;+}diff --git a/packages/shared/src/server/evals/codeEvalExecution.ts b/packages/shared/src/server/evals/codeEvalExecution.tsnew file mode 100644index 0000000000..d6a0e1f2ec--- /dev/null+++ b/packages/shared/src/server/evals/codeEvalExecution.ts@@ -0,0 +1,336 @@+import { stringifyValue } from "../../utils/stringChecks";+import {+ INTERNAL_TRACE_EVENT_SOURCE,+ type InternalTraceEventInput,+} from "../llm/internalTraceEvents";+import {+ LangfuseInternalTraceEnvironment,+ type InternalTraceWriteInput,+ type InternalTraceWriter,+} from "../llm/types";+import { logger } from "../logger";+import type { EvalTemplateCodeBased } from "../../features/evals/types";+import {+ CODE_EVAL_DISPATCH_PAYLOAD_MAX_BYTES,+ CODE_EVAL_DISPATCH_RESULT_MAX_BYTES,+ CODE_EVAL_SOURCE_MAX_BYTES,+ CodeEvalDispatcherError,+ CodeEvalDispatcherErrorCodes,+ withCodeEvalDocs,+ type CodeEvalDispatcherErrorCode,+ type CodeEvalDispatcher,+ type CodeEvalPayload,+ type CodeEvalScoreWithName,+ type DispatchResult,+} from "./codeEvalDispatcherTypes";+import type { ExtractedVariable } from "./extractObservationVariables";++const INTERNAL_CODE_EVAL_ERROR_MESSAGE = "An internal error occurred";+const INTERNAL_CODE_EVAL_ERROR_CODE = "INTERNAL_ERROR" as const;++const INTERNAL_CODE_EVAL_ERROR_CODES = new Set<CodeEvalDispatcherErrorCode>([+ CodeEvalDispatcherErrorCodes.LAMBDA_CONCURRENCY_LIMIT,+ CodeEvalDispatcherErrorCodes.LAMBDA_CONFIGURATION_ERROR,+ CodeEvalDispatcherErrorCodes.LAMBDA_INVOCATION_ERROR,+]);++const USER_VISIBLE_CODE_EVAL_ERROR_MESSAGE_BY_CODE: Partial<+ Record<CodeEvalDispatcherErrorCode, string>+> = {+ [CodeEvalDispatcherErrorCodes.INVALID_RESULT]: withCodeEvalDocs(+ "The evaluator returned an invalid result. Return { scores: [...] } with at least one score. Each score requires a name, dataType, and value; dataType must match the value type.",+ ),+ [CodeEvalDispatcherErrorCodes.TIMEOUT]: withCodeEvalDocs(+ "Evaluator timed out. Code-based evaluators must complete within the configured runtime limit. Long executions can be caused by network calls, which are forbidden and may never complete. Remove network calls, optimize your evaluator code, and try again.",+ ),+ [CodeEvalDispatcherErrorCodes.SOURCE_TOO_LARGE]: withCodeEvalDocs(+ `Evaluator source code is too large. Code-based evaluator source code is limited to ${formatCodeEvalByteLimit(CODE_EVAL_SOURCE_MAX_BYTES)}. Shorten the evaluator code and try again.`,+ ),+ [CodeEvalDispatcherErrorCodes.PAYLOAD_TOO_LARGE]: withCodeEvalDocs(+ `Evaluator input is too large. Code-based evaluator input is limited to ${formatCodeEvalByteLimit(CODE_EVAL_DISPATCH_PAYLOAD_MAX_BYTES)}, including source code and variables. Reduce the selected input, output, metadata, or experiment fields and try again.`,+ ),+ [CodeEvalDispatcherErrorCodes.RESULT_TOO_LARGE]: withCodeEvalDocs(+ `Evaluator result is too large. Code-based evaluator results are limited to ${formatCodeEvalByteLimit(CODE_EVAL_DISPATCH_RESULT_MAX_BYTES)}. Return fewer scores or smaller score values, comments, and metadata.`,+ ),+};++function formatCodeEvalByteLimit(bytes: number): string {+ const unit = bytes >= 1024 * 1024 ? "MB" : "KB";+ const value = bytes / (unit === "MB" ? 1024 * 1024 : 1024);+ const formattedValue = Number.isInteger(value)+ ? String(value)+ : value.toFixed(1);++ return `${formattedValue} ${unit}`;+}++export type CodeEvalUserVisibleErrorCode =+ | CodeEvalDispatcherErrorCode+ | typeof INTERNAL_CODE_EVAL_ERROR_CODE;++export type CodeEvalUserVisibleError = {+ code: CodeEvalUserVisibleErrorCode;+ message: string;+ retryable: boolean;+};++export class CodeEvalExecutionError extends Error {+ public readonly code: CodeEvalUserVisibleErrorCode;+ public readonly retryable: boolean;++ constructor(error: CodeEvalUserVisibleError) {+ super(error.message);+ this.name = "CodeEvalExecutionError";+ this.code = error.code;+ this.retryable = error.retryable;+ }+}++type CodeBasedEvaluationDispatchResult =+ | {+ success: true;+ scores: CodeEvalScoreWithName[];+ result: DispatchResult;+ executionTraceId: string;+ executionTraceFromTimestamp: Date;+ }+ | {+ success: false;+ error: CodeEvalUserVisibleError;+ executionTraceId: string;+ executionTraceFromTimestamp: Date;+ };++function buildCodeEvalPayload(params: {+ extractedVariables: ExtractedVariable[];+ hasExperimentContext: boolean;+}): CodeEvalPayload {+ const byName = new Map(+ params.extractedVariables.map((v) => [v.var, v.value]),+ );+ const payload: CodeEvalPayload = {+ observation: {+ input: byName.get("input") ?? null,+ output: byName.get("output") ?? null,+ metadata: byName.get("metadata") ?? null,+ },+ };++ if (params.hasExperimentContext) {+ payload.experiment = {+ itemExpectedOutput: byName.get("experimentItemExpectedOutput") ?? null,+ itemMetadata: byName.get("experimentItemMetadata") ?? null,+ };+ }++ return payload;+}++function getCodeEvalErrorDetails(error: unknown): {+ name: string;+ message: string;+ code: CodeEvalUserVisibleErrorCode;+ retryable: boolean;+} {+ if (error instanceof CodeEvalDispatcherError) {+ return {+ name: error.name,+ message: error.message,+ code: error.code,+ retryable: error.retryable,+ };+ }++ return {+ name: error instanceof Error ? error.name : "Error",+ code: INTERNAL_CODE_EVAL_ERROR_CODE,+ message: INTERNAL_CODE_EVAL_ERROR_MESSAGE,+ retryable: false,+ };+}++export function getCodeEvalUserVisibleError(+ error: unknown,+): CodeEvalUserVisibleError {+ const details = getCodeEvalErrorDetails(error);++ if (details.code === INTERNAL_CODE_EVAL_ERROR_CODE) {+ return {+ code: INTERNAL_CODE_EVAL_ERROR_CODE,+ message: INTERNAL_CODE_EVAL_ERROR_MESSAGE,+ retryable: details.retryable,+ };+ }++ if (INTERNAL_CODE_EVAL_ERROR_CODES.has(details.code)) {+ return {+ code: INTERNAL_CODE_EVAL_ERROR_CODE,+ message: INTERNAL_CODE_EVAL_ERROR_MESSAGE,+ retryable: details.retryable,+ };+ }++ const message = USER_VISIBLE_CODE_EVAL_ERROR_MESSAGE_BY_CODE[details.code];+ return {+ code: details.code,+ message: message ?? details.message,+ retryable: details.retryable,+ };+}++export async function runCodeBasedEvaluationDispatch(params: {+ dispatcher: CodeEvalDispatcher;+ organizationId: string;+ projectId: string;+ executionTraceId: string;+ jobExecutionId: string;+ template: EvalTemplateCodeBased;+ extractedVariables: ExtractedVariable[];+ hasExperimentContext?: boolean;+ traceName: string;+ metadata: Record<string, unknown>;+ writeTrace?: InternalTraceWriter;+}): Promise<CodeBasedEvaluationDispatchResult> {+ const payload = buildCodeEvalPayload({+ extractedVariables: params.extractedVariables,+ hasExperimentContext: params.hasExperimentContext ?? false,+ });+ const traceStartTime = new Date();+ let dispatchResult: DispatchResult | undefined;++ try {+ dispatchResult = await params.dispatcher.dispatch({+ scope: {+ organizationId: params.organizationId,+ projectId: params.projectId,+ evaluatorId: params.template.id,+ },+ runtime: { language: params.template.sourceCodeLanguage },+ execution: { jobExecutionId: params.jobExecutionId },+ code: { source: params.template.sourceCode },+ payload,+ });++ await writeCodeEvalTraceSafely({+ writeTrace: params.writeTrace,+ trace: buildCodeEvalTraceInput({+ projectId: params.projectId,+ executionTraceId: params.executionTraceId,+ traceStartTime,+ traceName: params.traceName,+ payload,+ output: dispatchResult,+ metadata: params.metadata,+ sourceCode: params.template.sourceCode,+ }),+ });++ return {+ success: true,+ scores: dispatchResult.scores,+ result: dispatchResult,+ executionTraceId: params.executionTraceId,+ executionTraceFromTimestamp: traceStartTime,+ };+ } catch (error) {+ const errorDetails = getCodeEvalErrorDetails(error);+ const visibleError = getCodeEvalUserVisibleError(error);+ const traceError = {+ name: errorDetails.name,+ code: visibleError.code,+ message: visibleError.message,+ retryable: errorDetails.retryable,+ };+ const errorCodeForTrace = errorDetails.code;++ await writeCodeEvalTraceSafely({+ writeTrace: params.writeTrace,+ trace: buildCodeEvalTraceInput({+ projectId: params.projectId,+ executionTraceId: params.executionTraceId,+ traceStartTime,+ traceName: params.traceName,+ payload,+ output: {+ ...(dispatchResult ? { result: dispatchResult } : {}),+ error: traceError,+ },+ metadata: {+ ...params.metadata,+ error_name: errorDetails.name,+ error_message: visibleError.message,+ error_code: errorCodeForTrace,+ ...(errorCodeForTrace !== visibleError.code+ ? { error_public_code: visibleError.code }+ : {}),+ error_retryable: errorDetails.retryable,+ },+ sourceCode: params.template.sourceCode,+ level: "ERROR",+ statusMessage: `Code eval execution failed: ${visibleError.message}`,+ }),+ });++ return {+ success: false,+ error: visibleError,+ executionTraceId: params.executionTraceId,+ executionTraceFromTimestamp: traceStartTime,+ };+ }+}++function buildCodeEvalTraceInput(params: {+ projectId: string;+ executionTraceId: string;+ traceStartTime: Date;+ traceName: string;+ payload: CodeEvalPayload;+ output: unknown;+ metadata: Record<string, unknown>;+ sourceCode: string;+ level?: string;+ statusMessage?: string;+}): InternalTraceWriteInput {+ 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: "SPAN",+ environment: LangfuseInternalTraceEnvironment.CodeEval,+ level: params.level ?? "DEFAULT",+ statusMessage: params.statusMessage,+ input: stringifyValue(params.payload),+ output: stringifyValue(params.output),+ metadata: {+ ...params.metadata,+ code_eval_source_code: params.sourceCode,+ },+ source: INTERNAL_TRACE_EVENT_SOURCE,+ };++ return {+ rootSpanId: params.executionTraceId,+ eventInputs: [eventInput],+ };+}++async function writeCodeEvalTraceSafely(params: {+ writeTrace?: InternalTraceWriter;+ trace: InternalTraceWriteInput;+}) {+ if (!params.writeTrace) return;++ try {+ await params.writeTrace(params.trace);+ } catch (error) {+ logger.warn("Failed to write internal trace for code eval execution", {+ executionTraceId: params.trace.rootSpanId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+}diff --git a/packages/shared/src/server/evals/evalScoreIds.ts b/packages/shared/src/server/evals/evalScoreIds.tsnew file mode 100644index 0000000000..bd1b6305ac--- /dev/null+++ b/packages/shared/src/server/evals/evalScoreIds.ts@@ -0,0 +1,38 @@+import { v5 } from "uuid";+import type { CodeEvalScoreWithName } from "./codeEvalDispatcherTypes";++const EVAL_SCORE_ID_NAMESPACE = "52b93de0-1d6c-4fb3-9f65-e5173184b1cb";++export function createDeterministicEvalScoreId(params: {+ jobExecutionId: string;+ scoreName: string;+ occurrenceIndex: number;+}): string {+ return v5(+ JSON.stringify([+ "eval-score",+ params.jobExecutionId,+ params.scoreName,+ params.occurrenceIndex,+ ]),+ EVAL_SCORE_ID_NAMESPACE,+ );+}++export function buildDeterministicEvalScoreIds(params: {+ scores: CodeEvalScoreWithName[];+ jobExecutionId: string;+}): string[] {+ const occurrenceByScoreName = new Map<string, number>();++ return params.scores.map((score) => {+ const occurrenceIndex = occurrenceByScoreName.get(score.name) ?? 0;+ occurrenceByScoreName.set(score.name, occurrenceIndex + 1);++ return createDeterministicEvalScoreId({+ jobExecutionId: params.jobExecutionId,+ scoreName: score.name,+ occurrenceIndex,+ });+ });+}diff --git a/worker/src/features/evaluation/observationEval/extractObservationVariables.ts b/packages/shared/src/server/evals/extractObservationVariables.tssimilarity index 50%rename from worker/src/features/evaluation/observationEval/extractObservationVariables.tsrename to packages/shared/src/server/evals/extractObservationVariables.tsindex 79e906e955..c0a6e43a06 100644--- a/worker/src/features/evaluation/observationEval/extractObservationVariables.ts+++ b/packages/shared/src/server/evals/extractObservationVariables.ts@@ -1,50 +1,29 @@-import { type ObservationForEval } from "./types";import {observationEvalVariableColumns,- type ObservationVariableMapping,- deepParseJson,- extractValueFromObject,-} from "@langfuse/shared";-import { logger } from "@langfuse/shared/src/server";+ type ObservationEvalVariableColumn,+ type ObservationForEval,+} from "../../features/evals/observationForEval";+import type { ObservationVariableMapping } from "../../features/evals/types";+import { extractValueFromObject } from "../../features/evals/utilities";+import { deepParseJson } from "../../utils/json";+import { logger } from "../logger";-/**- * Extracted variable from observation data for LLM-as-a-judge evaluation.- */export interface ExtractedVariable {var: string;- value: string;+ value: unknown;environment?: string;}-interface ExtractVariablesParams {- observation: ObservationForEval;- variableMapping: ObservationVariableMapping[];-}--/**- * Extracts variable values from an observation based on the variable mapping.- *- * For each mapping:- * 1. Gets the value from the observation based on selectedColumnId (direct property access)- * 2. Optionally applies JSON selector if provided- * 3. Returns an array of extracted variables compatible with executeLLMAsJudgeEvaluation()- *- * JSON string parsing (via deepParseJson) is lazy:- * - Only happens if at least one mapping has a JSON selector- * - Only parses fields that have selectors (not all fields)- * - Each field is parsed once, regardless of how many mappings access it- *- * Note: Environment is passed directly to executeLLMAsJudgeEvaluation() by the caller,- * not embedded in variables.- */export function extractObservationVariables(- params: ExtractVariablesParams,- columns = observationEvalVariableColumns,+ params: {+ observation: ObservationForEval;+ variableMapping: ObservationVariableMapping[];+ },+ columns: ObservationEvalVariableColumn[] = observationEvalVariableColumns,): ExtractedVariable[] {const { observation, variableMapping } = params;const variables: ExtractedVariable[] = [];- // Find which fields have JSON selectors - we'll parse these once upfrontconst fieldsWithSelectors = new Set<string>();for (const mapping of variableMapping) {if (mapping.jsonSelector) {@@ -52,7 +31,6 @@ export function extractObservationVariables(}}- // Parse fields with selectors once (lazy - skip if no selectors)const parsedFields = new Map<string, unknown>();for (const fieldId of fieldsWithSelectors) {const internal = columns.find((col) => col.id === fieldId)?.internal;@@ -60,7 +38,6 @@ export function extractObservationVariables(try {parsedFields.set(fieldId, deepParseJson(observation[internal]));} catch {- // If parsing fails, use raw valueparsedFields.set(fieldId, observation[internal]);}}@@ -77,17 +54,16 @@ export function extractObservationVariables();variables.push({var: mapping.templateVariable,- value: "",+ value: null,});continue;}- // Use pre-parsed value if this field was parsed, otherwise use raw value- const fieldValue = parsedFields.has(mapping.selectedColumnId)- ? parsedFields.get(mapping.selectedColumnId)- : observation[internal];+ const fieldValue =+ mapping.jsonSelector && parsedFields.has(mapping.selectedColumnId)+ ? parsedFields.get(mapping.selectedColumnId)+ : observation[internal];- // Build a single-key object so extractValueFromObject can look it upconst { value, error } = extractValueFromObject({ [mapping.selectedColumnId]: fieldValue },mapping.selectedColumnId,diff --git a/packages/shared/src/server/evals/localCodeEvalDispatcher.ts b/packages/shared/src/server/evals/localCodeEvalDispatcher.tsnew file mode 100644index 0000000000..c0d98c2fb1--- /dev/null+++ b/packages/shared/src/server/evals/localCodeEvalDispatcher.ts@@ -0,0 +1,110 @@+import { stripTypeScriptTypes } from "node:module";+import * as vm from "node:vm";+import { env } from "../../env";+import {+ CodeEvalDispatcherError,+ CodeEvalDispatcherErrorCodes,+ parseDispatchResult,+ withCodeEvalDocs,+ type CodeEvalDispatcher,+ type DispatchInput,+ type DispatchResult,+} from "./codeEvalDispatcherTypes";++const SCRIPT_TIMEOUT_MESSAGE = "Script execution timed out";++export class LocalCodeEvalDispatcher implements CodeEvalDispatcher {+ public readonly name = "insecure-local";+ private readonly timeoutMs: number;++ constructor(params?: { timeoutMs?: number }) {+ this.timeoutMs =+ params?.timeoutMs ?? env.LANGFUSE_CODE_EVAL_LOCAL_TIMEOUT_MS;+ }++ async dispatch(input: DispatchInput): Promise<DispatchResult> {+ if (input.runtime.language !== "TYPESCRIPT") {+ throw new CodeEvalDispatcherError(+ "Local code eval dispatcher only supports TypeScript/JavaScript evaluators",+ { code: CodeEvalDispatcherErrorCodes.UNSUPPORTED_RUNTIME },+ );+ }++ let source: string;+ try {+ source = stripTypeScriptTypes(input.code.source, { mode: "strip" });+ } catch (error) {+ throw new CodeEvalDispatcherError(+ `Failed to strip TypeScript syntax: ${withCodeEvalDocs(formatError(error))}`,+ { code: CodeEvalDispatcherErrorCodes.INVALID_SOURCE, cause: error },+ );+ }++ const context = vm.createContext({ payload: input.payload });+ try {+ vm.runInContext(+ `${source}++if (typeof evaluate !== "function") {+ throw new Error("Evaluator source must define evaluate(ctx)");+}`,+ context,+ { timeout: this.timeoutMs },+ );+ } catch (error) {+ throw new CodeEvalDispatcherError(+ `Failed to prepare evaluator source: ${formatError(error)}`,+ { code: CodeEvalDispatcherErrorCodes.INVALID_SOURCE, cause: error },+ );+ }++ let result: unknown;+ let timeoutId: ReturnType<typeof setTimeout> | undefined;+ try {+ const evaluatorResult = vm.runInContext("evaluate(payload)", context, {+ timeout: this.timeoutMs,+ });++ result = await Promise.race([+ evaluatorResult,+ new Promise<never>((_, reject) => {+ timeoutId = setTimeout(+ () =>+ reject(+ new Error(+ `${SCRIPT_TIMEOUT_MESSAGE} after ${this.timeoutMs}ms`,+ ),+ ),+ this.timeoutMs,+ );+ }),+ ]);+ } catch (error) {+ const message = formatError(error);+ throw new CodeEvalDispatcherError(message, {+ code: message.includes(SCRIPT_TIMEOUT_MESSAGE)+ ? CodeEvalDispatcherErrorCodes.TIMEOUT+ : CodeEvalDispatcherErrorCodes.USER_CODE_ERROR,+ cause: error,+ retryable: message.includes(SCRIPT_TIMEOUT_MESSAGE),+ });+ } finally {+ if (timeoutId) clearTimeout(timeoutId);+ }++ return parseDispatchResult(result);+ }+}++function formatError(error: unknown): string {+ if (+ typeof error === "object" &&+ error !== null &&+ "message" in error &&+ typeof error.message === "string"+ ) {+ return error.message;+ }++ return String(error);+}diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex d865b22e62..3c71b22a88 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -21,6 +21,11 @@ export * from "./services/commentFilterService";export * from "./datasets/schemaValidation";export * from "./datasets/schemaTypes";export * from "./evalJobConfigCache";+export * from "./evals/codeEvalDispatchers";+export * from "./evals/codeEvalExecution";+export * from "./evals/evalScoreIds";+export * from "./evals/extractObservationVariables";+export * from "./utils/traceId";export * from "./auth/apiKeys";export * from "./auth/invalidateApiKeys";export * from "./auth/customSsoProvider";@@ -112,6 +117,7 @@ export * from "./utils/rendering";export * from "./utils/sqlLike";export * from "./redis/evalExecutionQueue";export * from "./redis/llmAsJudgeExecutionQueue";+export * from "./redis/codeEvalExecutionQueue";export * from "./services/sessions-ui-table-service";export * from "./services/sessions-ui-table-events-service";export * from "./services/DashboardService";diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.tsindex 33f0fdb317..5c7d7aedac 100644--- a/packages/shared/src/server/llm/types.ts+++ b/packages/shared/src/server/llm/types.ts@@ -540,6 +540,7 @@ export type LLMApiKey =export enum LangfuseInternalTraceEnvironment {PromptExperiments = "langfuse-prompt-experiment",LLMJudge = "langfuse-llm-as-a-judge",+ CodeEval = "langfuse-code-eval",}export type ProcessedTraceEvent = {@@ -548,16 +549,22 @@ export type ProcessedTraceEvent = {body: Record<string, unknown>;};+export type InternalTraceWriteInput = {+ rootSpanId: string;+ eventInputs: InternalTraceEventInput[];+};++export type InternalTraceWriter = (+ params: InternalTraceWriteInput,+) => Promise<void>;+/*** Configuration for direct writing of trace events to the events table.* Used by internal tracing (prompt experiments, evaluations).*/export type InternalEventsWriter = {experimentContext?: InternalTraceExperimentContext;- write: (params: {- rootSpanId: string;- eventInputs: InternalTraceEventInput[];- }) => Promise<void>;+ write: InternalTraceWriter;};export type TraceSinkParams = {diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.tsindex 19348ea4ab..638da55354 100644--- a/packages/shared/src/server/queues.ts+++ b/packages/shared/src/server/queues.ts@@ -100,8 +100,8 @@ export const EvalExecutionEvent = z.object({delay: z.number().nullish(),});-// LLM-as-a-Judge execution for observation-based evals-export const LLMAsJudgeExecutionEventSchema = z.object({+// Observation-based eval execution payload shared by LLM-as-judge and code eval queues.+export const ObservationEvalExecutionEventSchema = z.object({projectId: z.string(),jobExecutionId: z.string(),observationS3Path: z.string(),@@ -286,8 +286,8 @@ export type DatasetRunItemUpsertEventType = z.infer<typeof DatasetRunItemUpsertEventSchema>;export type EvalExecutionEventType = z.infer<typeof EvalExecutionEvent>;-export type LLMAsJudgeExecutionEventType = z.infer<- typeof LLMAsJudgeExecutionEventSchema+export type ObservationEvalExecutionEventType = z.infer<+ typeof ObservationEvalExecutionEventSchema>;export type IngestionEventQueueType = z.infer<typeof IngestionEvent>;export type OtelIngestionEventQueueType = z.infer<typeof OtelIngestionEvent>;@@ -327,7 +327,8 @@ export enum QueueName {ProjectDelete = "project-delete",EvaluationExecution = "evaluation-execution-queue", // Worker executes EvalsEvaluationExecutionSecondaryQueue = "secondary-evaluation-execution-queue", // Separates high-throughput eval projects from other projects.- LLMAsJudgeExecution = "llm-as-a-judge-execution-queue", // Observation-based eval execution+ LLMAsJudgeExecution = "llm-as-a-judge-execution-queue", // Observation-based LLM-as-judge eval execution+ CodeEvalExecution = "code-eval-execution-queue", // Observation-based code eval executionDatasetRunItemUpsert = "dataset-run-item-upsert-queue",BatchExport = "batch-export-queue",OtelIngestionQueue = "otel-ingestion-queue",@@ -366,6 +367,7 @@ export enum QueueJobs {DatasetRunItemUpsert = "dataset-run-item-upsert",EvaluationExecution = "evaluation-execution-job",LLMAsJudgeExecution = "llm-as-a-judge-execution-job",+ CodeEvalExecution = "code-eval-execution-job",BatchExportJob = "batch-export-job",CloudUsageMeteringJob = "cloud-usage-metering-job",CloudSpendAlertJob = "cloud-spend-alert-job",@@ -449,10 +451,17 @@ export type TQueueJobTypes = {[QueueName.LLMAsJudgeExecution]: {timestamp: Date;id: string;- payload: LLMAsJudgeExecutionEventType;+ payload: ObservationEvalExecutionEventType;name: QueueJobs.LLMAsJudgeExecution;retryBaggage?: RetryBaggage;};+ [QueueName.CodeEvalExecution]: {+ timestamp: Date;+ id: string;+ payload: ObservationEvalExecutionEventType;+ name: QueueJobs.CodeEvalExecution;+ retryBaggage?: RetryBaggage;+ };[QueueName.BatchExport]: {timestamp: Date;id: string;diff --git a/packages/shared/src/server/redis/codeEvalExecutionQueue.ts b/packages/shared/src/server/redis/codeEvalExecutionQueue.tsnew file mode 100644index 0000000000..29ffcd4949--- /dev/null+++ b/packages/shared/src/server/redis/codeEvalExecutionQueue.ts@@ -0,0 +1,92 @@+import { Queue } from "bullmq";+import { logger } from "../logger";+import { TQueueJobTypes, QueueName } from "../queues";+import {+ createNewRedisInstance,+ redisQueueRetryOptions,+ getQueuePrefix,+} from "./redis";+import { getShardIndex } from "./sharding";+import { env } from "../../env";++export class CodeEvalExecutionQueue {+ private static instances: Map<+ number,+ Queue<TQueueJobTypes[QueueName.CodeEvalExecution]> | null+ > = new Map();++ public static getShardNames() {+ return Array.from(+ { length: env.LANGFUSE_CODE_EVAL_EXECUTION_QUEUE_SHARD_COUNT },+ (_, i) => `${QueueName.CodeEvalExecution}${i > 0 ? `-${i}` : ""}`,+ );+ }++ static getShardIndexFromShardName(+ shardName: string | undefined,+ ): number | null {+ if (!shardName) return null;++ const shardIndex =+ shardName === QueueName.CodeEvalExecution+ ? 0+ : parseInt(+ shardName.replace(`${QueueName.CodeEvalExecution}-`, ""),+ 10,+ );++ if (isNaN(shardIndex)) return null;+ return shardIndex;+ }++ public static getInstance({+ shardingKey,+ shardName,+ }: {+ shardingKey?: string;+ shardName?: string;+ } = {}): Queue<TQueueJobTypes[QueueName.CodeEvalExecution]> | null {+ const shardIndex =+ CodeEvalExecutionQueue.getShardIndexFromShardName(shardName) ??+ (env.REDIS_CLUSTER_ENABLED === "true" && shardingKey+ ? getShardIndex(+ shardingKey,+ env.LANGFUSE_CODE_EVAL_EXECUTION_QUEUE_SHARD_COUNT,+ )+ : 0);++ if (CodeEvalExecutionQueue.instances.has(shardIndex)) {+ return CodeEvalExecutionQueue.instances.get(shardIndex) || null;+ }++ const newRedis = createNewRedisInstance({+ enableOfflineQueue: false,+ ...redisQueueRetryOptions,+ });++ const name = `${QueueName.CodeEvalExecution}${shardIndex > 0 ? `-${shardIndex}` : ""}`;+ const queueInstance = newRedis+ ? new Queue<TQueueJobTypes[QueueName.CodeEvalExecution]>(name, {+ connection: newRedis,+ prefix: getQueuePrefix(name),+ defaultJobOptions: {+ removeOnComplete: true,+ removeOnFail: 10_000,+ attempts: 3,+ backoff: {+ type: "exponential",+ delay: 1000,+ },+ },+ })+ : null;++ queueInstance?.on("error", (err) => {+ logger.error(`CodeEvalExecutionQueue shard ${shardIndex} error`, err);+ });++ CodeEvalExecutionQueue.instances.set(shardIndex, queueInstance);++ return queueInstance;+ }+}diff --git a/packages/shared/src/server/redis/getQueue.ts b/packages/shared/src/server/redis/getQueue.tsindex c114a3d46d..52e44332b5 100644--- a/packages/shared/src/server/redis/getQueue.ts+++ b/packages/shared/src/server/redis/getQueue.ts@@ -38,6 +38,7 @@ export function getQueue(| QueueName.EvaluationExecution| QueueName.EvaluationExecutionSecondaryQueue| QueueName.LLMAsJudgeExecution+ | QueueName.CodeEvalExecution| QueueName.TraceUpsert| QueueName.OtelIngestionQueue| QueueName.OtelIngestionSecondaryQueuediff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex cc4d8b7f92..e8d2e203b8 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -1,4 +1,5 @@import { prisma } from "../../db";+import { Readable } from "stream";import type {EventsObservation,MetadataDomain,@@ -30,7 +31,8 @@ import {ObservationPriceFields,} from "../queries";import { createFilterFromFilterState } from "../queries/clickhouse-sql/factory";-import type { FilterState } from "../../types";+import type { FilterCondition, FilterState } from "../../types";+import type { TracingSearchType } from "../../interfaces/search";import {eventsScoresAggregation,eventsSessionsAggregation,@@ -93,6 +95,11 @@ type EventBatchIOStringOutput = {metadata: MetadataDomain;};+type EventBatchIOWithExperimentOutput = EventBatchIOStringOutput & {+ experimentItemExpectedOutput: string | null;+ experimentItemMetadata: MetadataDomain;+};+const BATCH_IO_STRING_RENDERING_PROPS: RenderingProps = {// Batch I/O truncation is handled in SQL via leftUTF8 for performance.truncated: false,@@ -112,6 +119,27 @@ type ObservationsTableQueryResultWitouhtTraceFields = Omit<"trace_tags" | "trace_name" | "trace_user_id">;+const EVENT_SEARCH_COLUMNS = [+ "span_id",+ "name",+ "trace_name",+ "user_id",+ "session_id",+ "trace_id",+] as const;++const eventSearchCondition = (opts: {+ query?: string;+ searchType?: TracingSearchType[];+}) =>+ clickhouseSearchCondition({+ query: opts.query,+ searchType: opts.searchType,+ tablePrefix: "e",+ searchColumns: EVENT_SEARCH_COLUMNS,+ useEventsTablePath: true,+ });+/*** Internal helper: enrich observations with model pricing data* Uses events-specific converter to include userId and sessionId@@ -515,19 +543,9 @@ async function getObservationsFromEventsTableInternal<T>(}}- const search = clickhouseSearchCondition({+ const search = eventSearchCondition({query: opts.searchQuery,searchType: opts.searchType,- tablePrefix: "e",- searchColumns: [- "span_id",- "name",- "trace_name",- "user_id",- "session_id",- "trace_id",- ],- useEventsTablePath: true,});// Handle positionInTrace via CTE with ROW_NUMBER()@@ -701,6 +719,148 @@ export const getObservationByIdFromEventsTable = async ({return mapped.shift();};+/**+ * Lightweight event stream for batch observation evaluation.+ * Selects the eval field set and maps ClickHouse aliases toward ObservationForEval.+ */+export const getEventsStreamForEval = async (props: {+ projectId: string;+ cutoffCreatedAt?: Date;+ filter: FilterCondition[] | null;+ searchQuery?: string;+ searchType?: TracingSearchType[];+ rowLimit: number;+}): Promise<Readable> => {+ const {+ projectId,+ cutoffCreatedAt,+ filter = [],+ searchQuery,+ searchType,+ rowLimit,+ } = props;++ const eventOnlyFilters = (filter ?? []).filter((f) => {+ const columnDef = eventsTableUiColumnDefinitions.find(+ (col) => col.uiTableName === f.column || col.uiTableId === f.column,+ );++ return (+ columnDef?.clickhouseTableName !== "scores" &&+ columnDef?.clickhouseTableName !== "comments"+ );+ });++ const filterConditions: FilterCondition[] = [...eventOnlyFilters];+ if (cutoffCreatedAt) {+ filterConditions.push({+ column: "startTime",+ operator: "<",+ value: cutoffCreatedAt,+ type: "datetime",+ });+ }++ const eventsFilter = new FilterList(+ createFilterFromFilterState(+ filterConditions,+ eventsTableUiColumnDefinitions,+ eventsTableCols,+ ),+ );++ const appliedEventsFilter = eventsFilter.apply();++ const search = eventSearchCondition({+ query: searchQuery,+ searchType,+ });++ const eventsQuery = new EventsQueryBuilder({ projectId })+ .selectFieldSet("eval")+ .selectIO(false)+ .selectFieldSet("metadata")+ .when(search.requiresEventsFull, (b) => b.forceFullTable())+ .where(appliedEventsFilter)+ .where(search)+ .whereRaw("e.is_deleted = 0")+ .orderByDefault()+ .limitBy("e.span_id", "e.project_id")+ .limit(rowLimit);++ const { query, params: queryParams } = eventsQuery.buildWithParams();++ type EvalEventRow = {+ id: string;+ trace_id: string;+ project_id: string;+ parent_observation_id: string | null;+ type: string;+ name: string | null;+ environment: string | null;+ version: string | null;+ level: string;+ status_message: string | null;+ trace_name: string | null;+ user_id: string | null;+ session_id: string | null;+ tags: string[];+ release: string | null;+ provided_model_name: string | null;+ model_parameters: unknown;+ prompt_id: string | null;+ prompt_name: string | null;+ prompt_version: number | null;+ provided_usage_details: Record<string, number>;+ usage_details: Record<string, number>;+ provided_cost_details: Record<string, number>;+ cost_details: Record<string, number>;+ tool_definitions: Record<string, unknown>;+ tool_calls: unknown[];+ tool_call_names: string[];+ input: unknown;+ output: unknown;+ metadata: Record<string, unknown> | null;+ experiment_id: string | null;+ experiment_item_root_span_id: string | null;+ experiment_item_expected_output: string | null;+ experiment_item_metadata: Record<string, unknown> | null;+ };++ const asyncGenerator = queryClickhouseStream<EvalEventRow>({+ query,+ params: queryParams,+ clickhouseConfigs: {+ request_timeout: 180_000,+ clickhouse_settings: {+ http_send_timeout: 300,+ http_receive_timeout: 300,+ },+ },+ tags: {+ feature: "batch-eval",+ type: "event",+ kind: "eval",+ projectId,+ },+ preferredClickhouseService: "EventsReadOnly",+ });++ // Remap ClickHouse aliases to schema field names.+ // Schema validation is left to the consumer so per-row errors can be handled gracefully.+ return Readable.from(+ (async function* () {+ for await (const row of asyncGenerator) {+ yield {+ ...row,+ span_id: row.id,+ parent_span_id: row.parent_observation_id,+ };+ }+ })(),+ );+};+async function getObservationByIdFromEventsTableInternal({id,projectId,@@ -2654,7 +2814,9 @@ export const deleteEventsOlderThanDays = async (return true;};-export const getObservationsBatchIOFromEventsTable = async (opts: {+export const getObservationsBatchIOFromEventsTable = async <+ TIncludeExperiment extends boolean = false,+>(opts: {projectId: string;observations: Array<{id: string;@@ -2663,7 +2825,14 @@ export const getObservationsBatchIOFromEventsTable = async (opts: {minStartTime: Date;maxStartTime: Date;truncated?: boolean; // Default true for performance, false for full data-}): Promise<Array<EventBatchIOStringOutput>> => {+ includeExperimentFields?: TIncludeExperiment;+}): Promise<+ Array<+ TIncludeExperiment extends true+ ? EventBatchIOWithExperimentOutput+ : EventBatchIOStringOutput+ >+> => {if (opts.observations.length === 0) {return [];}@@ -2686,12 +2855,19 @@ export const getObservationsBatchIOFromEventsTable = async (opts: {const outputSelect = truncated? `leftUTF8(e.output, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT}) as output`: `e.output as output`;+ const experimentFieldsSelect = opts.includeExperimentFields+ ? `+ experiment_item_expected_output,+ mapFromArrays(arrayReverse(e.experiment_item_metadata_names), arrayReverse(e.experiment_item_metadata_values)) as experiment_item_metadata,+ `+ : "";const query = `SELECTe.span_id as id,${inputSelect},${outputSelect},+ ${experimentFieldsSelect}mapFromArrays(arrayReverse(e.metadata_names), arrayReverse(e.metadata_values)) as metadataFROM ${tableName} eWHERE e.project_id = {projectId: String}@@ -2706,6 +2882,8 @@ export const getObservationsBatchIOFromEventsTable = async (opts: {input: string | null;output: string | null;metadata: Record<string, string>;+ experiment_item_expected_output?: string | null;+ experiment_item_metadata?: Record<string, string>;}>({query,params: {@@ -2730,7 +2908,20 @@ export const getObservationsBatchIOFromEventsTable = async (opts: {output: applyBatchIOStringRendering(r.output),metadata:r.metadata !== undefined ? parseMetadataCHRecordToDomain(r.metadata) : {},- }));+ ...(opts.includeExperimentFields+ ? {+ experimentItemExpectedOutput: r.experiment_item_expected_output,+ experimentItemMetadata:+ r.experiment_item_metadata !== undefined+ ? parseMetadataCHRecordToDomain(r.experiment_item_metadata)+ : {},+ }+ : {}),+ })) as Array<+ TIncludeExperiment extends true+ ? EventBatchIOWithExperimentOutput+ : EventBatchIOStringOutput+ >;};/**diff --git a/packages/shared/src/server/utils/traceId.ts b/packages/shared/src/server/utils/traceId.tsnew file mode 100644index 0000000000..57e52dfecf--- /dev/null+++ b/packages/shared/src/server/utils/traceId.ts@@ -0,0 +1,16 @@+import crypto from "node:crypto";++/**+ * Creates a W3C Trace Context compliant trace ID (16 bytes as 32 hex characters).+ *+ * @param seed Optional seed string for deterministic trace ID generation. When+ * provided the trace ID is SHA-256(seed) truncated to 16 bytes. When+ * omitted a cryptographically random ID is returned.+ */+export function createW3CTraceId(seed?: string): string {+ if (!seed) {+ return crypto.randomBytes(16).toString("hex");+ }++ return crypto.createHash("SHA-256").update(seed).digest("hex").slice(0, 32);+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a3ed390022..76a95b3eea 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -167,6 +167,9 @@ importers:'@aws-sdk/client-cloudwatch':specifier: ^3.1013.0version: 3.1024.0+ '@aws-sdk/client-lambda':+ specifier: ^3.1046.0+ version: 3.1046.0'@aws-sdk/client-s3':specifier: ^3.1013.0version: 3.1024.0@@ -372,12 +375,18 @@ importers:'@appsignal/opentelemetry-instrumentation-bullmq':specifier: ^0.8.0version: 0.8.0([email protected])+ '@astral-sh/ruff-wasm-web':+ specifier: 0.15.13+ version: 0.15.13'@baselime/trpc-opentelemetry-middleware':specifier: ^0.1.2'@codemirror/lang-json':specifier: ^6.0.2version: 6.0.2+ '@codemirror/lang-python':+ specifier: ^6.2.1+ version: 6.2.1(@codemirror/[email protected])'@codemirror/language':specifier: ^6.12.3version: 6.12.3@@ -1181,6 +1190,9 @@ packages:'@asamuzakjp/[email protected]':resolution: {integrity: sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==}+ '@astral-sh/[email protected]':+ resolution: {integrity: sha512-nYro6u3L/tphtuRMjJDuabs0ugmhVM7r0u6k2Gxs5Bo96qeoN03S8tizjNqiHYNrhB/wmmJmHVDsX3j453Aj/w==}+'@aws-crypto/[email protected]':resolution: {integrity: sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg==}engines: {node: '>=16.0.0'}@@ -1220,6 +1232,10 @@ packages:resolution: {integrity: sha512-KYd1SYF+WaZinfzg4rsfprZQ3X1qboaJnHtjppd82JG3YSO/LVkenOkFIIsREPnXMoy6Dy6Xx+BXh4Y9A+a1zQ==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-g997Ks9pIxUWrc+BRlbkEXCIsYiW60lVSvSt38UXu50XG6DAH63l+ALiwzBk47TA2XlFO7z/IufklQCnCBaQnQ==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-8qdO5aLCzaf9l0RdrSBW1iIroRKP2QBqtZ6lkrtHKiaaH0B18xEn+lrEgiN/eCf3uRAYk4cqbnI2XcWzm+7dDQ==}engines: {node: '>=20.0.0'}@@ -1232,6 +1248,11 @@ packages:resolution: {integrity: sha512-njR2qoG6ZuB0kvAS2FyICsFZJ6gmCcf2X/7JcD14sUvGDm26wiZ5BrA6LOiUxKFEF+IVe7kdroxyE00YlkiYsw==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-bXxosFunr+v/kqNb99r1NRkrVBha7CG036fRSpWGbC1A/e363XFQN6wcZMx7MYTdRr1tYwNnkrWX2xc1rT3BCQ==}+ engines: {node: '>=20.0.0'}+ deprecated: Deprecated due to an error deserialization bug in JSON 1.0 protocol services, see https://github.com/aws/aws-sdk-js-v3/pull/8031. Newer version available.+'@aws-sdk/[email protected]':resolution: {integrity: sha512-2VbTstbjKdT+yKi8m7b3a9CiVac+pL/IY2PHJwsaGkkHmuuqkJZIErPck1h6P3T9ghQMLSdMPyW6Qp7Di5swFg==}engines: {node: '>=20.0.0'}@@ -1240,34 +1261,66 @@ packages:resolution: {integrity: sha512-XT0jtf8Fw9JE6ppsQeoNnZRiG+jqRixMT1v1ZR17G60UvVdsQmTG8nbEyHuEPfMxDXEhfdARaM/XiEhca4lGHQ==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-WkFQ8BedszVomhh/Zzs8WwnE/XBmTqZjoQVB8u/4zH6kZCjouXZpPpb93gD8m0EZmzAl7dxHE/y+yDpuKzNCMw==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-DPoGWfy7J7RKxvbf5kOKIGQkD2ek3dbKgzKIGrnLuvZBz5myU+Im/H6pmc14QcnFbqHMqxvtWSgRDSJW3qXLQg==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-ylx0ZJTU+2eNcvXQ69VNR3TVSYa/ibpvdK717/NxqR9aXRMn2QRWZaiI8aa5yY/fOWZ5mknSmxGaVxxtdwv3EA==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-oDzUBu2MGJFgoar05sPMCwSrhw44ASyccrHzj66vO69OZqi7I6hZZxXfuPLC8OCzW7C+sU+bI73XHij41yekgQ==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-QhRSrdkk+Gq0AFIylpiI0N6lcJqFYV9Jtr4Luz5FpYOYbjJSfyTG6iLhnK/UPIgN1Jnon8WAmSC//16XYGvwkA==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-g1NosS8qe4OF++G2UFCM5ovSkgipC7YYor5KCWatG0UoMSO5YFj9C8muePlyVmOBV/WTI16Jo3/s1NUo/o1Bww==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-1hU0NtC04QbFIuoBuF4aQ2A97GsSE5/A0ZJpDijwexsBREIQ4KPRYl3v/FfKCPBYsaTeGjkOFx5nLhWHY24LOw==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-HEswDQyxUtadoZ/bJsPPENHg7R0Lzym5LuMksJeHvqhCOpP+rtkDLKI4/ZChH4w3cf5kG8n6bZuI8PzajoiqMg==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-ZgrQaGkpyTlVSCCsffzijVg+KgftTAWYvI5Otc36J/4jNiHb+7MmBiJIR0a5AHLvifC92PiYHt5pijP0dswd1w==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-T3IFs4EVmVi1dVN5RciFnklCANSzvrQd/VuHY9ThHSQmYkTogjcGkoJEr+oNUPQZnso52183088NqysMPji1/Q==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-hNj1rAwZWT1vfz54BwH8FUWxZuqStrM25Q5LEIwn2erHPMRVAjLlpZqEbCEEqS99eEEOhdeetnS0WeNa3iYeEQ==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-5ZxG+t0+3Q3QPh8KEjX6syskhgNf7I0MN7oGioTf6Lm1NTjfP7sIcYGNsthXC2qR8vcD3edNZwCr2ovfSSWuRA==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-mwIPNPldyCZkvHozb6E0X/vuQLN1UCjcA6MwUf1gaO7EwghCmuNZXatq0L3zptKFvPC4Nds7+WFUkifI1XmbSw==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-lYHFF30DGI20jZcYX8cm6Ns0V7f1dDN6g/MBDLTyD/5iw+bXs3yBr2iAiHDkx4RFU5JgsnZvCHYKiRVPRdmOgw==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-b9HT8CnpyPVn1hU14Q7ihjwSPlRzToYmRYJxRd5jNHEZ43lrIhoLaTT8JmfQQt5j5M8rTX1iN1X8mvu0SM1dXA==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-2IrLrOruRr1NhTK0vguBL1gCWv1pu4bf4KaqpsA+/vCJpFEbvXFawn71GvCzk1wyjnDUsemtKypqoKGv4cSGbA==}engines: {node: '>=20.0.0'}@@ -1298,6 +1351,10 @@ packages:resolution: {integrity: sha512-IJSsIMeVQ8MMCPbuh1AbltkFhLBLXn7aejzfX5YKT/VLDHn++Dcz8886tXckE+wQssyPUhaXrJhdakO2VilRhg==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-CBC6+tVYaOJo7QXgN1zJ4Ba2f3/Cpy4eRViYFimXW/O5Mn8hBmgXXzHu4vy4ubT80YWnp8aCFygr7dTOa14yQg==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-KaUoFuoFPziIa98DSQsTPeke1gvGXlc5ZGMhy+b+nLxZ4A7jmJgLzjEF95l8aOQN2T/qlPP3MrAyELm8ExXucw==}engines: {node: '>=20.0.0'}@@ -1310,6 +1367,10 @@ packages:resolution: {integrity: sha512-+zz6f79Kj9V5qFK2P+D8Ehjnw4AhphAlCAsPjUqEcInA9umtSSKMrHbSagEeOIsDNuvVrH98bjRHcyQukTrhaQ==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-5eltYxKB4MfdQv7/VhWxRbAVQKow5dz9votRFigTYrWJHMQXwLMltlbk7KFWSZh5NDBySfmjT7Jv/DWfYCmDng==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-Km7M+i8DrLArVzrid1gfxeGhYHBd3uxvE77g0s5a52zPSVosxzQBnJ0gwWb6NIp/DOk8gsBMhi7V+cpJG0ndTA==}engines: {node: '>=20.0.0'}@@ -1322,6 +1383,10 @@ packages:resolution: {integrity: sha512-iz+B29TXcAZsJpwB+AwG/TTGA5l/VnmMZ2UxtiySOZjI6gCdmviXPwdgzcmuazMy16rXoPY4mYCGe7zdNKfx5A==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-MlNSvNsSVlMKKWaCzA0GP1nS4Cuq3WCXUN1vmMvd+Ctztib5kmRcpmTtKx9kikN8szAc+gcdp7uqJJervV2nQg==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-Gp6EWIqHX5wmsOR5ZxWyyzEU8P0xBdSxkm6VHEwXwBqScKZ7QWRoj6ZmHpr+S44EYb5tuzGya4ottsogSu2W3A==}engines: {node: '>= 14.0.0'}@@ -1330,10 +1395,18 @@ packages:resolution: {integrity: sha512-WBDnqatJl+kGObpfmfSxqnXeYTu3Me8wx8WCtvoxX3pfWrrTv8I4WTMSSs7PZqcRcVh8WeUKMgGFjMG+52SR1w==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-jT2AXOODobQfTYGC2SChMSnZ/voIcRV/LHlY1suyhY1bdgP/voKkhEg8Ci1jiGQ4lBiaso5BEAV3ZWWpPTfmYA==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-CvJ2ZIjK/jVD/lbOpowBVElJyC1YxLTIJ13yM0AEo0t2v7swOzGjSA6lJGH+DwZXQhcjUjoYwc8bVYCX5MDr1A==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-VuLXVmm7+lKVxqFcOItPkXhjbJ02iUfxkxheRu41SfWf6/xrZup2A2SwHZos/LeQGu3SBHeqTQht80Uo3ienPA==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-KNoGsXnTfBxPqrtV2Owd4mrLnhTHRsOz6Hdaz+As5czGMQuPchoRvG1BJzn2NFRGLt/HSJAXVn+G6IhtRIDe+Q==}engines: {node: '>=20.0.0'}@@ -1342,6 +1415,10 @@ packages:resolution: {integrity: sha512-+CMIt3e1VzlklAECmG+DtP1sV8iKq25FuA0OKpnJ4KA0kxUtd7CgClY7/RU6VzJBQwbN4EJ9Ue6plvqx1qGadw==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-2N62veqdMZBCwQUHsbhtnaovOFjOa5Dn3dAD1nRqFTUXR4QmirT3HZnfus/L1DS08Vm5CkoKmL0iMVt6YbqEag==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-IL1c54UvbuERrs9oLm5rvkzMciwhhpn1FL0SlC3XUMoLlFhdBsWJgQKK8O5fsQLxbFVqjbjFx9OBkrn44X9PHw==}engines: {node: '>=20.0.0'}@@ -1350,6 +1427,10 @@ packages:resolution: {integrity: sha512-Th7kPI6YPtvJUcdznooXJMy+9rQWjmEF81LxaJssngBzuysK4a/x+l8kjm1zb7nYsUPbndnBdUnwng/3PLvtGw==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-9je8nZt+ntB8IjhpGNayU/AkBgvq/f4aFO2bH1LSNC5JX6K8zY4LUnr/ymqunePrwq+B5OVBpL7ILjYzMFSZAw==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-gjlAdtHMbtR9X5iIhVUvbVcy55KnznpC6bkDUWW9z915bi0ckdUr5cjf16Kp6xq0bP5HBD2xzgbL9F9Quv5vUw==}engines: {node: '>=20.0.0'}@@ -1362,6 +1443,10 @@ packages:resolution: {integrity: sha512-oOZHcRDihk5iEe5V25NVWg45b3qEA8OpHWVdU/XQh8Zj4heVPAJqWvMphQnU7LkufmUo10EpvFPZuQMiFLJK3g==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-ibx8Vd73rCTHekNGeXX8cpGWoBKbNAlwKHL3yjSxxttu5QnNDaSAM7/0MFYDjU31/F4lyrPoQcGirT0ew61xcg==}+ engines: {node: '>=20.0.0'}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-J6DS9oocrgxM8xlUTTmQOuwRF6rnAGEujAN9SAzllcrQmwn5iJ58ogxy3SEhD0Q7JZvlA5jvIXBkpQRqEqlE9A==}engines: {node: '>=20.0.0'}@@ -1373,6 +1458,9 @@ packages:'@aws-sdk/[email protected]':resolution: {integrity: sha512-FAzqXvfEssGdSIz8ejatan0bOdx1qefBWKF/gWmVBXIP1HkS7v/wjjaqrAGGKvyihrXTXW00/2/1nTJtxpXz7g==}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-kq3RS6XQtHMrLFShbkem6h+8fxazB3jEIsbMC6aaSInOciRGE+eGAqTgJ+obO7Euo/pjM8thVqLiLISEH9X9DA==}+'@aws-sdk/[email protected]':resolution: {integrity: sha512-ZWwlkjcIp7cEL8ZfTpTAPNkwx25p7xol0xlKoWVVf22+nsjwmLcHYtTPjIV1cSpmB/b6DaK4cb1fSkvCXHgRdw==}engines: {node: '>=20.0.0'}@@ -1382,10 +1470,23 @@ packages:aws-crt:optional: true+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-066hKH/0nvV7x4ofV/iK9kz8r/qNfcR6rzuEOFqI2vQL/fcTTsDAbTw0jmXkyMzANK8ltQdALj19ns3zuOJiUw==}+ engines: {node: '>=20.0.0'}+ peerDependencies:+ aws-crt: '>=1.0.0'+ peerDependenciesMeta:+ aws-crt:+ optional: true+'@aws-sdk/[email protected]':resolution: {integrity: sha512-PMYKKtJd70IsSG0yHrdAbxBr+ZWBKLvzFZfD3/urxgf6hXVMzuU5M+3MJ5G67RpOmLBu1fAUN65SbWuKUCOlAA==}engines: {node: '>=20.0.0'}+ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-A0YmgYFv+hTI9c17Ntvd2hSehm9bmJfkb+ggADBwVKA8H/3+Jx94SzR2qOB9bAA9WFeDqnfz9PKKQ+D+YAKomA==}+ engines: {node: '>=20.0.0'}+'@aws/[email protected]':resolution: {integrity: sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ==}engines: {node: '>=18.0.0'}@@ -1580,6 +1681,9 @@ packages:'@codemirror/[email protected]':resolution: {integrity: sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ==}+ '@codemirror/[email protected]':+ resolution: {integrity: sha512-IRjC8RUBhn9mGR9ywecNhB51yePWCGgvHfY1lWN/Mrp3cKuHr0isDKia+9HnvhiWNnMpbGhWrkhuWOc09exRyw==}+'@codemirror/[email protected]':resolution: {integrity: sha512-QwCZW6Tt1siP37Jet9Tb02Zs81TQt6qQrZR2H+eGMcFsL1zMrk2/b9CLC7/9ieP1fjIUMgviLWMmgiHoJrj+ZA==}@@ -2446,6 +2550,9 @@ packages:'@lezer/[email protected]':resolution: {integrity: sha512-bPWa0Pgx69ylNlMlPvBPryqeLYQjyJjqPx+Aupm5zydLIF3NE+6MMLT8Yi23Bd9cif9VS00aUebn+6fDIGBcDA==}+ '@lezer/[email protected]':+ resolution: {integrity: sha512-31FiUrU7z9+d/ElGQLJFXl+dKOdx0jALlP3KEOsGTex8mvj+SoE1FgItcHWK/axkxCHGUSpqIHt6JAWfWu9Rhg==}+'@marijn/[email protected]':resolution: {integrity: sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==}@@ -4433,10 +4540,18 @@ packages:engines: {node: '>=18.0.0'}deprecated: Deprecated due to incompatibility with Node.js 18 in some environments https://github.com/smithy-lang/smithy-typescript/issues/2022+ '@smithy/[email protected]':+ resolution: {integrity: sha512-IKS7qX59fAGCYBmt5JChcDswQDupZqT2Yn2ZBA3UgTlsjRNNkQzZobbn95xoAAdtTyJmBiJB3Y02qR3rgy3Zog==}+ engines: {node: '>=18.0.0'}+'@smithy/[email protected]':resolution: {integrity: sha512-5gi+28FH+RurB2+tcRH1CK7KiLJ0dVnabjWLY3DgeFLiU45dbyrsq7NOYvMUcHgu9LVZH5F7G+Qk1GdXF0y6jg==}engines: {node: '>=18.0.0'}+ '@smithy/[email protected]':+ resolution: {integrity: sha512-iYr9ekBjmZ+FwkiHEopqGscBbl78X62cq3p5Dd0eC+gNd7fybNZFQQdDuOQjTVmFymleuA8YRWZnuXWZ8B3kKA==}+ engines: {node: '>=18.0.0'}+'@smithy/[email protected]':resolution: {integrity: sha512-FE3bZdEl62ojmy8x4FHqxq2+BuOHlcxiH5vaZ6aqHJr3AIZzwF5jfx8dEiU/X0a8RboyNDjmXjlbr8AdEyLgiA==}engines: {node: '>=18.0.0'}@@ -4461,6 +4576,10 @@ packages:resolution: {integrity: sha512-yxurumLvHfgYgM0FVtjOVIyBSJXfno4xKKOgD43wOk9Qh+2lTKfP9Qhu4JHU7IUwrqVPa888byUzomHMgvKVMg==}engines: {node: '>=18.0.0'}+ '@smithy/[email protected]':+ resolution: {integrity: sha512-3wF40g8OOCA5BnwQUvwtzZqYBbWWftDjpAlWIUo6Yld3ZzJaMAKqg7MWQBPjE8oLaqvZQUE7tVGlZPsae6A4bQ==}+ engines: {node: '>=18.0.0'}+'@smithy/[email protected]':resolution: {integrity: sha512-YrF4zWKh+ghLuquldj6e/RzE3xZYL8wIPfkt0MqCRphVICjyyjH8OwKD7LLlKpVEbk4FLizFfC1+gwK6XQdR3g==}engines: {node: '>=18.0.0'}@@ -4525,6 +4644,10 @@ packages:resolution: {integrity: sha512-PxF57Jr3dPm+RgZWekOL+o96FPdaT62xZUyDfi47uMRFi5rHpwO/ewFbrztrASQ/7H8moNi1sspIHihHpfoKsQ==}engines: {node: '>=18.0.0'}+ '@smithy/[email protected]':+ resolution: {integrity: sha512-EdksTZ8UXYxGUgQ4mpIKrHoaj9WVGsp66TpZuixLAz1Jex8YDLnS4RH9ktGED5aOpN0OJlEtrsC9IGt76go1eA==}+ engines: {node: '>=18.0.0'}+'@smithy/[email protected]':resolution: {integrity: sha512-/YBWtO2SdvPSAUk/Ke1Xpdg1E1lfaNGblla7mnIVGtaGkSQ5bK7KBZqpuj5IokHlU9UcLDvt2QwTLV7oRzBUTA==}engines: {node: '>=18.0.0'}@@ -4545,6 +4668,10 @@ packages:resolution: {integrity: sha512-nkdB9T8JS6iD5PukE5TB8KqcvMEPVPHVUY7J0odYJgyIM40Du2msUhBdoPNRqRArDDcGQqVQcbzu0CZA7b+Nkw==}engines: {node: '>=18.0.0'}+ '@smithy/[email protected]':+ resolution: {integrity: sha512-1km1OjdLRFuITWpCPofjFqzZ+tbeWuB72ZhcYjbjkCxZ21tTPfIs4GUxRrelMyKMLxLghGD58RENnXorU/O8cw==}+ engines: {node: '>=18.0.0'}+'@smithy/[email protected]':resolution: {integrity: sha512-lysfoRCr7PdD9CsPp9VQuJYRGI5mWYb8FRkbdBSQttxpQmW7tZsFgmpBNKVcgvBsAgBCkYX/UQs0NmznuBcZQQ==}engines: {node: '>=18.0.0'}@@ -10863,6 +10990,8 @@ snapshots:'@csstools/css-tokenizer': 3.0.4lru-cache: 10.4.3+ '@astral-sh/[email protected]': {}+'@aws-crypto/[email protected]':dependencies:'@aws-crypto/util': 5.2.0@@ -11099,6 +11228,29 @@ snapshots:transitivePeerDependencies:- aws-crt+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-crypto/sha256-browser': 5.2.0+ '@aws-crypto/sha256-js': 5.2.0+ '@aws-sdk/core': 3.974.9+ '@aws-sdk/credential-provider-node': 3.972.40+ '@aws-sdk/middleware-host-header': 3.972.11+ '@aws-sdk/middleware-logger': 3.972.10+ '@aws-sdk/middleware-recursion-detection': 3.972.12+ '@aws-sdk/middleware-user-agent': 3.972.39+ '@aws-sdk/region-config-resolver': 3.972.14+ '@aws-sdk/types': 3.973.8+ '@aws-sdk/util-endpoints': 3.996.9+ '@aws-sdk/util-user-agent-browser': 3.972.11+ '@aws-sdk/util-user-agent-node': 3.973.25+ '@smithy/core': 3.24.2+ '@smithy/fetch-http-handler': 5.4.2+ '@smithy/node-http-handler': 4.7.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+ transitivePeerDependencies:+ - aws-crt+'@aws-sdk/[email protected]':dependencies:'@aws-crypto/sha1-browser': 5.2.0@@ -11221,6 +11373,15 @@ snapshots:'@smithy/util-utf8': 4.2.2tslib: 2.8.1+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/types': 3.973.8+ '@aws-sdk/xml-builder': 3.972.23+ '@smithy/core': 3.24.2+ '@smithy/signature-v4': 5.4.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+'@aws-sdk/[email protected]':dependencies:'@smithy/types': 4.14.1@@ -11234,6 +11395,14 @@ snapshots:'@smithy/types': 4.14.1tslib: 2.8.1+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.974.9+ '@aws-sdk/types': 3.973.8+ '@smithy/core': 3.24.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+'@aws-sdk/[email protected]':dependencies:'@aws-sdk/core': 3.974.8@@ -11247,6 +11416,16 @@ snapshots:'@smithy/util-stream': 4.6.0tslib: 2.8.1+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.974.9+ '@aws-sdk/types': 3.973.8+ '@smithy/core': 3.24.2+ '@smithy/fetch-http-handler': 5.4.2+ '@smithy/node-http-handler': 4.7.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+'@aws-sdk/[email protected]':dependencies:'@aws-sdk/core': 3.974.8@@ -11266,6 +11445,24 @@ snapshots:transitivePeerDependencies:- aws-crt+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.974.9+ '@aws-sdk/credential-provider-env': 3.972.35+ '@aws-sdk/credential-provider-http': 3.972.37+ '@aws-sdk/credential-provider-login': 3.972.39+ '@aws-sdk/credential-provider-process': 3.972.35+ '@aws-sdk/credential-provider-sso': 3.972.39+ '@aws-sdk/credential-provider-web-identity': 3.972.39+ '@aws-sdk/nested-clients': 3.997.7+ '@aws-sdk/types': 3.973.8+ '@smithy/core': 3.24.2+ '@smithy/credential-provider-imds': 4.3.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+ transitivePeerDependencies:+ - aws-crt+'@aws-sdk/[email protected]':dependencies:'@aws-sdk/core': 3.974.8@@ -11279,6 +11476,17 @@ snapshots:transitivePeerDependencies:- aws-crt+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.974.9+ '@aws-sdk/nested-clients': 3.997.7+ '@aws-sdk/types': 3.973.8+ '@smithy/core': 3.24.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+ transitivePeerDependencies:+ - aws-crt+'@aws-sdk/[email protected]':dependencies:'@aws-sdk/credential-provider-env': 3.972.34@@ -11296,6 +11504,22 @@ snapshots:transitivePeerDependencies:- aws-crt+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/credential-provider-env': 3.972.35+ '@aws-sdk/credential-provider-http': 3.972.37+ '@aws-sdk/credential-provider-ini': 3.972.39+ '@aws-sdk/credential-provider-process': 3.972.35+ '@aws-sdk/credential-provider-sso': 3.972.39+ '@aws-sdk/credential-provider-web-identity': 3.972.39+ '@aws-sdk/types': 3.973.8+ '@smithy/core': 3.24.2+ '@smithy/credential-provider-imds': 4.3.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+ transitivePeerDependencies:+ - aws-crt+'@aws-sdk/[email protected]':dependencies:'@aws-sdk/core': 3.974.8@@ -11305,6 +11529,14 @@ snapshots:'@smithy/types': 4.14.1tslib: 2.8.1+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.974.9+ '@aws-sdk/types': 3.973.8+ '@smithy/core': 3.24.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+'@aws-sdk/[email protected]':dependencies:'@aws-sdk/core': 3.974.8@@ -11318,6 +11550,18 @@ snapshots:transitivePeerDependencies:- aws-crt+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.974.9+ '@aws-sdk/nested-clients': 3.997.7+ '@aws-sdk/token-providers': 3.1046.0+ '@aws-sdk/types': 3.973.8+ '@smithy/core': 3.24.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+ transitivePeerDependencies:+ - aws-crt+'@aws-sdk/[email protected]':dependencies:'@aws-sdk/core': 3.974.8@@ -11330,6 +11574,17 @@ snapshots:transitivePeerDependencies:- aws-crt+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.974.9+ '@aws-sdk/nested-clients': 3.997.7+ '@aws-sdk/types': 3.973.8+ '@smithy/core': 3.24.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+ transitivePeerDependencies:+ - aws-crt+'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.973.8@@ -11397,6 +11652,13 @@ snapshots:'@smithy/types': 4.14.1tslib: 2.8.1+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/types': 3.973.8+ '@smithy/core': 3.24.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.973.8@@ -11417,6 +11679,14 @@ snapshots:'@smithy/types': 4.14.1tslib: 2.8.1+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/types': 3.973.8+ '@aws/lambda-invoke-store': 0.2.4+ '@smithy/core': 3.24.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+'@aws-sdk/[email protected]':dependencies:'@aws-sdk/core': 3.974.8@@ -11451,6 +11721,15 @@ snapshots:'@smithy/util-retry': 4.4.0tslib: 2.8.1+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.974.9+ '@aws-sdk/types': 3.973.8+ '@aws-sdk/util-endpoints': 3.996.9+ '@smithy/core': 3.24.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.973.8@@ -11510,6 +11789,29 @@ snapshots:transitivePeerDependencies:- aws-crt+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-crypto/sha256-browser': 5.2.0+ '@aws-crypto/sha256-js': 5.2.0+ '@aws-sdk/core': 3.974.9+ '@aws-sdk/middleware-host-header': 3.972.11+ '@aws-sdk/middleware-logger': 3.972.10+ '@aws-sdk/middleware-recursion-detection': 3.972.12+ '@aws-sdk/middleware-user-agent': 3.972.39+ '@aws-sdk/region-config-resolver': 3.972.14+ '@aws-sdk/signature-v4-multi-region': 3.996.26+ '@aws-sdk/types': 3.973.8+ '@aws-sdk/util-endpoints': 3.996.9+ '@aws-sdk/util-user-agent-browser': 3.972.11+ '@aws-sdk/util-user-agent-node': 3.973.25+ '@smithy/core': 3.24.2+ '@smithy/fetch-http-handler': 5.4.2+ '@smithy/node-http-handler': 4.7.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+ transitivePeerDependencies:+ - aws-crt+'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.973.8@@ -11518,6 +11820,13 @@ snapshots:'@smithy/types': 4.14.1tslib: 2.8.1+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/types': 3.973.8+ '@smithy/core': 3.24.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+'@aws-sdk/[email protected]':dependencies:'@aws-sdk/signature-v4-multi-region': 3.996.25@@ -11538,6 +11847,14 @@ snapshots:'@smithy/types': 4.14.1tslib: 2.8.1+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/types': 3.973.8+ '@smithy/core': 3.24.2+ '@smithy/signature-v4': 5.4.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+'@aws-sdk/[email protected]':dependencies:'@aws-sdk/core': 3.974.8@@ -11562,6 +11879,17 @@ snapshots:transitivePeerDependencies:- aws-crt+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.974.9+ '@aws-sdk/nested-clients': 3.997.7+ '@aws-sdk/types': 3.973.8+ '@smithy/core': 3.24.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+ transitivePeerDependencies:+ - aws-crt+'@aws-sdk/[email protected]':dependencies:'@smithy/types': 4.14.1@@ -11579,6 +11907,13 @@ snapshots:'@smithy/util-endpoints': 3.5.0tslib: 2.8.1+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/types': 3.973.8+ '@smithy/core': 3.24.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.973.8@@ -11597,6 +11932,13 @@ snapshots:bowser: 2.14.1tslib: 2.8.1+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/types': 3.973.8+ '@smithy/types': 4.14.1+ bowser: 2.14.1+ tslib: 2.8.1+'@aws-sdk/[email protected]':dependencies:'@aws-sdk/middleware-user-agent': 3.972.38@@ -11606,6 +11948,14 @@ snapshots:'@smithy/util-config-provider': 4.2.2tslib: 2.8.1+ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/middleware-user-agent': 3.972.39+ '@aws-sdk/types': 3.973.8+ '@smithy/core': 3.24.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+'@aws-sdk/[email protected]':dependencies:'@nodable/entities': 2.1.0@@ -11613,6 +11963,13 @@ snapshots:fast-xml-parser: 5.7.2tslib: 2.8.1+ '@aws-sdk/[email protected]':+ dependencies:+ '@nodable/entities': 2.1.0+ '@smithy/types': 4.14.1+ fast-xml-parser: 5.7.2+ tslib: 2.8.1+'@aws/[email protected]': {}'@azure/[email protected]':@@ -11880,6 +12237,16 @@ snapshots:'@codemirror/language': 6.12.3'@lezer/json': 1.0.3+ '@codemirror/[email protected](@codemirror/[email protected])':+ dependencies:+ '@codemirror/autocomplete': 6.17.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])+ '@codemirror/language': 6.12.3+ '@codemirror/state': 6.6.0+ '@lezer/common': 1.5.1+ '@lezer/python': 1.1.18+ transitivePeerDependencies:+ - '@codemirror/view'+'@codemirror/[email protected]':dependencies:'@codemirror/state': 6.6.0@@ -12699,6 +13066,12 @@ snapshots:dependencies:'@lezer/common': 1.5.1+ '@lezer/[email protected]':+ dependencies:+ '@lezer/common': 1.5.1+ '@lezer/highlight': 1.2.3+ '@lezer/lr': 1.4.8+'@marijn/[email protected]': {}@@ -14759,12 +15132,24 @@ snapshots:'@smithy/types': 4.14.1tslib: 2.8.1+ '@smithy/[email protected]':+ dependencies:+ '@aws-crypto/crc32': 5.2.0+ '@smithy/types': 4.14.1+ tslib: 2.8.1+'@smithy/[email protected]':dependencies:'@smithy/core': 3.24.0'@smithy/types': 4.14.1tslib: 2.8.1+ '@smithy/[email protected]':+ dependencies:+ '@smithy/core': 3.24.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+'@smithy/[email protected]':dependencies:'@aws-crypto/crc32': 5.2.0@@ -14801,6 +15186,12 @@ snapshots:'@smithy/types': 4.14.1tslib: 2.8.1+ '@smithy/[email protected]':+ dependencies:+ '@smithy/core': 3.24.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+'@smithy/[email protected]':dependencies:'@smithy/chunked-blob-reader': 5.2.2@@ -14894,6 +15285,12 @@ snapshots:'@smithy/types': 4.14.1tslib: 2.8.1+ '@smithy/[email protected]':+ dependencies:+ '@smithy/core': 3.24.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+'@smithy/[email protected]':dependencies:'@smithy/core': 3.24.0@@ -14921,6 +15318,12 @@ snapshots:'@smithy/types': 4.14.1tslib: 2.8.1+ '@smithy/[email protected]':+ dependencies:+ '@smithy/core': 3.24.2+ '@smithy/types': 4.14.1+ tslib: 2.8.1+'@smithy/[email protected]':dependencies:'@smithy/core': 3.24.0diff --git a/scripts/code-eval-runners/bootstrap-floci.py b/scripts/code-eval-runners/bootstrap-floci.pynew file mode 100755index 0000000000..640bbd2264--- /dev/null+++ b/scripts/code-eval-runners/bootstrap-floci.py@@ -0,0 +1,121 @@+#!/usr/bin/env python3+import base64+import json+import os+import time+import urllib.error+import urllib.request+from pathlib import Path+from zipfile import ZIP_DEFLATED, ZipFile++ENDPOINT = os.environ.get("FLOCI_ENDPOINT", "http://localhost:4566").rstrip("/")+RUNNERS_DIR = Path(os.environ.get("CODE_EVAL_RUNNERS_DIR", "/opt/code-eval-runners"))+BUILD_DIR = Path(os.environ.get("CODE_EVAL_RUNNERS_BUILD_DIR", "/tmp/code-eval-runners"))+ROLE_ARN = "arn:aws:iam::000000000000:role/code-eval-floci-role"+NODE_FUNCTION = "code-based-eval-executor-node"+PYTHON_FUNCTION = "code-based-eval-executor-python"+++def main() -> None:+ wait_for_floci()+ BUILD_DIR.mkdir(parents=True, exist_ok=True)++ node_zip = BUILD_DIR / "node.zip"+ python_zip = BUILD_DIR / "python.zip"++ node_handler_file = "code-based-eval-handler.mjs"+ python_handler_file = "code_based_eval_handler.py"++ with ZipFile(node_zip, "w", ZIP_DEFLATED) as zf:+ zf.write(RUNNERS_DIR / "node" / node_handler_file, node_handler_file)++ with ZipFile(python_zip, "w", ZIP_DEFLATED) as zf:+ zf.write(+ RUNNERS_DIR / "python" / python_handler_file, python_handler_file+ )++ upsert_lambda(+ NODE_FUNCTION, "nodejs24.x", "code-based-eval-handler.handler", node_zip+ )+ upsert_lambda(+ PYTHON_FUNCTION,+ "python3.13",+ "code_based_eval_handler.handler",+ python_zip,+ )++ print("Code eval Floci Lambda runners are ready.", flush=True)+++def wait_for_floci() -> None:+ for _ in range(60):+ try:+ request("GET", "/2015-03-31/functions")+ return+ except Exception:+ time.sleep(1)++ raise RuntimeError(f"Timed out waiting for Floci at {ENDPOINT}")+++def upsert_lambda(+ function_name: str,+ runtime: str,+ handler: str,+ zip_path: Path,+) -> None:+ encoded_zip = base64.b64encode(zip_path.read_bytes()).decode("ascii")++ if function_exists(function_name):+ request(+ "PUT",+ f"/2015-03-31/functions/{function_name}/code",+ {"ZipFile": encoded_zip},+ )+ return++ request(+ "POST",+ "/2015-03-31/functions",+ {+ "FunctionName": function_name,+ "Runtime": runtime,+ "Handler": handler,+ "Role": ROLE_ARN,+ "Timeout": 2,+ "MemorySize": 128,+ "Code": {"ZipFile": encoded_zip},+ },+ )+++def function_exists(function_name: str) -> bool:+ try:+ request("GET", f"/2015-03-31/functions/{function_name}")+ return True+ except urllib.error.HTTPError as error:+ if error.code == 404:+ return False+ raise+++def request(method: str, path: str, payload=None) -> bytes:+ data = None+ headers = {"Content-Type": "application/json"}++ if payload is not None:+ data = json.dumps(payload).encode("utf-8")++ req = urllib.request.Request(+ f"{ENDPOINT}{path}",+ data=data,+ headers=headers,+ method=method,+ )++ with urllib.request.urlopen(req, timeout=10) as response:+ return response.read()+++if __name__ == "__main__":+ main()diff --git a/scripts/code-eval-runners/node/code-based-eval-handler.mjs b/scripts/code-eval-runners/node/code-based-eval-handler.mjsnew file mode 100644index 0000000000..135ae5ec98--- /dev/null+++ b/scripts/code-eval-runners/node/code-based-eval-handler.mjs@@ -0,0 +1,82 @@+import { stripTypeScriptTypes } from "node:module";++const CODE_EVAL_DOCS_URL = "https://langfuse.com/docs/evaluation/overview";++// `stripTypeScriptTypes` is loaded lazily - we call it hear to avoid doing the import in the call itself+stripTypeScriptTypes("");++export async function handler(event) {+ let source;+ try {+ source = stripTypeScriptTypes(event.code.source, { mode: "strip" });+ } catch (error) {+ return runnerError(+ "INVALID_SOURCE",+ `Failed to strip TypeScript syntax: ${withCodeEvalDocs(formatError(error))}`,+ );+ }++ let evaluate;+ try {+ evaluate = Function(+ `${source}++if (typeof evaluate !== "function") {+ throw new Error("Evaluator source must define evaluate(ctx)");+}++return evaluate;`,+ )();+ } catch (error) {+ return runnerError(+ "INVALID_SOURCE",+ `Failed to prepare evaluator source: ${formatError(error)}`,+ );+ }++ let result;+ try {+ result = await evaluate(event.payload);+ } catch (error) {+ return runnerError("USER_CODE_ERROR", formatError(error));+ }++ return normalizeResult(result);+}++function normalizeResult(result) {+ if (+ typeof result !== "object" ||+ result === null ||+ !Array.isArray(result.scores)+ ) {+ return runnerError(+ "INVALID_RESULT",+ "Evaluator must return an object shaped like { scores: [...] }",+ );+ }++ return result;+}++function runnerError(code, message) {+ return {+ error: {+ code,+ message,+ },+ };+}++function formatError(error) {+ return error instanceof Error ? error.message : String(error);+}++function withCodeEvalDocs(message) {+ const trimmedMessage = message.trim();+ const punctuatedMessage = /[.!?]$/.test(trimmedMessage)+ ? trimmedMessage+ : `${trimmedMessage}.`;++ return `${punctuatedMessage} See ${CODE_EVAL_DOCS_URL} for details.`;+}diff --git a/scripts/code-eval-runners/python/code_based_eval_handler.py b/scripts/code-eval-runners/python/code_based_eval_handler.pynew file mode 100644index 0000000000..11d7fb402d--- /dev/null+++ b/scripts/code-eval-runners/python/code_based_eval_handler.py@@ -0,0 +1,147 @@+import asyncio+import dataclasses+import json+from dataclasses import dataclass, field+from typing import Any+++@dataclass+class ObservationContext:+ input: Any = None+ output: Any = None+ metadata: Any = None+++@dataclass+class ExperimentContext:+ item_expected_output: Any = None+ item_metadata: Any = None+++@dataclass+class EvaluationContext:+ observation: ObservationContext+ experiment: ExperimentContext | None = None++ @classmethod+ def from_payload(cls, payload: dict[str, Any]):+ observation = payload.get("observation") or {}+ experiment = payload.get("experiment")+ return cls(+ observation=ObservationContext(+ input=observation.get("input"),+ output=observation.get("output"),+ metadata=observation.get("metadata"),+ ),+ experiment=ExperimentContext(+ item_expected_output=experiment.get("itemExpectedOutput"),+ item_metadata=experiment.get("itemMetadata"),+ )+ if isinstance(experiment, dict)+ else None,+ )+++# Public dataclasses exposed to user evaluator code. Field names are Pythonic+# (snake_case); they are translated to the camelCase wire format (`dataType`,+# `configId`) by `to_jsonable` so users can return an `EvaluationResult`+# directly without manual key mangling.+@dataclass+class Score:+ value: int | float | str | bool+ name: str+ data_type: str | None = None+ comment: str | None = None+ config_id: str | None = None+ metadata: dict[str, Any] | None = None+++@dataclass+class EvaluationResult:+ scores: list[Score] = field(default_factory=list)+++# Mapping from dataclass snake_case field names to the camelCase keys expected+# by the dispatcher wire schema. Kept as an explicit allowlist so that user+# metadata payloads (which may legitimately contain snake_case keys) are never+# rewritten — only dataclass field names are translated.+_DATACLASS_FIELD_NAME_OVERRIDES: dict[str, str] = {+ "data_type": "dataType",+ "config_id": "configId",+}+++def handler(event, context):+ namespace = {+ "EvaluationContext": EvaluationContext,+ "EvaluationResult": EvaluationResult,+ "Score": Score,+ }++ try:+ exec(event["code"]["source"], namespace)+ except Exception as error:+ return runner_error(+ "INVALID_SOURCE", f"Failed to load evaluator source: {error}"+ )++ evaluate = namespace.get("evaluate")+ if not callable(evaluate):+ return runner_error(+ "INVALID_SOURCE", "Evaluator source must define an evaluate(ctx) function"+ )++ try:+ result = evaluate(EvaluationContext.from_payload(event.get("payload", {})))+ if asyncio.iscoroutine(result):+ result = asyncio.run(result)+ except Exception as error:+ return runner_error("USER_CODE_ERROR", str(error))++ return normalize_result(result)+++def normalize_result(result):+ normalized = to_jsonable(result)++ if not isinstance(normalized, dict) or not isinstance(+ normalized.get("scores"), list+ ):+ return runner_error(+ "INVALID_RESULT",+ "Evaluator must return an object shaped like { scores: [...] }",+ )++ return normalized+++def to_jsonable(value):+ if dataclasses.is_dataclass(value) and not isinstance(value, type):+ # Translate snake_case dataclass field names to the camelCase wire+ # format and drop None-valued optional fields so that the result+ # matches the union variants in the TypeScript schema (e.g. the+ # `dataType: undefined` variant).+ result = {}+ for f in dataclasses.fields(value):+ raw = getattr(value, f.name)+ if raw is None:+ continue+ key = _DATACLASS_FIELD_NAME_OVERRIDES.get(f.name, f.name)+ result[key] = to_jsonable(raw)+ return result++ if isinstance(value, list):+ return [to_jsonable(item) for item in value]++ if isinstance(value, dict):+ return {key: to_jsonable(item) for key, item in value.items()}++ try:+ json.dumps(value)+ return value+ except TypeError:+ return str(value)+++def runner_error(code: str, message: str):+ return {"error": {"code": code, "message": message}}diff --git a/web/package.json b/web/package.jsonindex 670d6676fc..e5d76493ce 100644--- a/web/package.json+++ b/web/package.json@@ -34,8 +34,10 @@"@anthropic-ai/claude-agent-sdk": "^0.2.133","@anthropic-ai/tokenizer": "^0.0.4","@appsignal/opentelemetry-instrumentation-bullmq": "^0.8.0",+ "@astral-sh/ruff-wasm-web": "0.15.13","@baselime/trpc-opentelemetry-middleware": "^0.1.2","@codemirror/lang-json": "^6.0.2",+ "@codemirror/lang-python": "^6.2.1","@codemirror/language": "^6.12.3","@codemirror/lint": "^6.9.5","@codemirror/search": "^6.7.0",diff --git a/web/src/__tests__/server/code-eval-test-run-trpc.servertest.ts b/web/src/__tests__/server/code-eval-test-run-trpc.servertest.tsnew file mode 100644index 0000000000..d2a2e96779--- /dev/null+++ b/web/src/__tests__/server/code-eval-test-run-trpc.servertest.ts@@ -0,0 +1,575 @@+import { randomUUID } from "node:crypto";+import { describe, expect, it, afterAll, vi } from "vitest";+import type { Session } from "next-auth";+import {+ EvalTemplateSourceCodeLanguage,+ EvalTemplateType,+} from "@prisma/client";+import { env } from "@/src/env.mjs";+import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import { prisma } from "@langfuse/shared/src/db";+import {+ createEvent,+ createEventsCh,+ createObservation,+ createObservationsCh,+ createOrgProjectAndApiKey,+ createTrace,+ createTracesCh,+ queryClickhouse,+} from "@langfuse/shared/src/server";+import { EvalTargetObject } from "@langfuse/shared";++vi.hoisted(() => {+ process.env.NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED = "true";+});++const orgIds: string[] = [];++const maybe =+ env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true"+ ? describe+ : describe.skip;++async function prepare() {+ const { project, org } = await createOrgProjectAndApiKey();++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: org.id,+ name: org.name,+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ metadata: {},+ aiFeaturesEnabled: true,+ projects: [+ {+ id: project.id,+ role: "ADMIN",+ retentionDays: 30,+ deletedAt: null,+ name: project.name,+ hasTraces: false,+ metadata: {},+ createdAt: project.createdAt.toISOString(),+ },+ ],+ },+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,+ },+ admin: true,+ },+ environment: {+ enableExperimentalFeatures: false,+ selfHostedInstancePlan: "cloud:hobby",+ },+ };++ const ctx = createInnerTRPCContext({ session, headers: {} });+ const caller = appRouter.createCaller({ ...ctx, prisma });++ orgIds.push(org.id);++ return { project, caller };+}++maybe("evals.testRunCodeEval", () => {+ afterAll(async () => {+ await prisma.organization.deleteMany({+ where: {+ id: { in: orgIds },+ },+ });+ });++ it("runs a saved code template against unsaved evaluator config without persisting eval state", async () => {+ const { project, caller } = await prepare();+ const observationId = randomUUID();+ const traceId = randomUUID();+ const startTime = new Date();+ const savedSource = `+ function evaluate(ctx) {+ const matched =+ ctx.observation.input === ${JSON.stringify(JSON.stringify({ question: "2+2" }))} &&+ ctx.observation.output === "4" &&+ ctx.observation.metadata.rubric === "math";++ return { scores: [{ name: "saved-test-score", value: matched, dataType: "BOOLEAN" }] };+ }+ `;++ const template = await prisma.evalTemplate.create({+ data: {+ projectId: project.id,+ name: "Saved code evaluator",+ version: 1,+ type: EvalTemplateType.CODE,+ prompt: null,+ outputDefinition: undefined,+ sourceCode: savedSource,+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ },+ });++ await createEventsCh([+ createEvent({+ project_id: project.id,+ trace_id: traceId,+ span_id: observationId,+ id: observationId,+ start_time: startTime.getTime() * 1000,+ input: JSON.stringify({ question: "2+2" }),+ output: "4",+ metadata_names: ["quality"],+ metadata_values: [JSON.stringify({ rubric: "math" })],+ }),+ ]);++ const jobConfigCountBefore = await prisma.jobConfiguration.count({+ where: { projectId: project.id },+ });+ const jobExecutionCountBefore = await prisma.jobExecution.count({+ where: { projectId: project.id },+ });++ const response = await caller.evals.testRunCodeEval({+ projectId: project.id,+ evalTemplateId: template.id,+ target: EvalTargetObject.EVENT,+ scoreName: "unsaved-score",+ observationId,+ traceId,+ startTime,+ mapping: [+ {+ templateVariable: "input",+ selectedColumnId: "input",+ jsonSelector: null,+ },+ {+ templateVariable: "output",+ selectedColumnId: "output",+ jsonSelector: null,+ },+ {+ templateVariable: "metadata",+ selectedColumnId: "metadata",+ jsonSelector: "$.quality",+ },+ ],+ });++ expect(response).toEqual({+ success: true,+ result: {+ scores: [+ {+ name: "saved-test-score",+ value: 1,+ dataType: "BOOLEAN",+ },+ ],+ },+ executionTraceId: expect.stringMatching(/^[0-9a-f]{32}$/),+ executionTraceFromTimestamp: expect.any(Date),+ });++ await expect(+ prisma.jobConfiguration.count({ where: { projectId: project.id } }),+ ).resolves.toBe(jobConfigCountBefore);+ await expect(+ prisma.jobExecution.count({ where: { projectId: project.id } }),+ ).resolves.toBe(jobExecutionCountBefore);++ const scoreCount = await queryClickhouse<{ count: string }>({+ query: `SELECT count() as count FROM scores WHERE project_id = {projectId: String}`,+ params: { projectId: project.id },+ tags: {+ feature: "evals",+ type: "scores",+ kind: "testRunCodeEvalNoScores",+ projectId: project.id,+ },+ });++ expect(Number(scoreCount[0]?.count ?? 0)).toBe(0);+ });++ it("runs against legacy observations when events table observations are disabled", async () => {+ const { project, caller } = await prepare();+ const observationId = randomUUID();+ const traceId = randomUUID();+ const startTime = new Date();+ const template = await createCodeTemplate(+ project.id,+ `+ function evaluate(ctx) {+ const matched =+ ctx.observation.input === "legacy input" &&+ ctx.observation.output === "legacy output" &&+ ctx.observation.metadata === "legacy";++ return { scores: [{ name: "legacy-observation-score", value: matched ? 1 : 0, dataType: "BOOLEAN" }] };+ }+ `,+ );++ await createTracesCh([+ createTrace({+ id: traceId,+ project_id: project.id,+ timestamp: startTime.getTime(),+ }),+ ]);+ await createObservationsCh([+ createObservation({+ id: observationId,+ trace_id: traceId,+ project_id: project.id,+ start_time: startTime.getTime(),+ input: "legacy input",+ output: "legacy output",+ metadata: { quality: "legacy" },+ }),+ ]);++ const mutableEnv = env as unknown as {+ LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS: "true" | "false";+ };+ const originalEventsTableObservationFlag =+ mutableEnv.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS;++ try {+ mutableEnv.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS = "false";++ const response = await caller.evals.testRunCodeEval({+ projectId: project.id,+ evalTemplateId: template.id,+ target: EvalTargetObject.EVENT,+ scoreName: "unsaved-score",+ observationId,+ traceId,+ startTime,+ mapping: [+ {+ templateVariable: "input",+ selectedColumnId: "input",+ jsonSelector: null,+ },+ {+ templateVariable: "output",+ selectedColumnId: "output",+ jsonSelector: null,+ },+ {+ templateVariable: "metadata",+ selectedColumnId: "metadata",+ jsonSelector: "$.quality",+ },+ ],+ });++ expect(response).toEqual({+ success: true,+ result: {+ scores: [+ {+ name: "legacy-observation-score",+ value: 1,+ dataType: "BOOLEAN",+ },+ ],+ },+ executionTraceId: expect.stringMatching(/^[0-9a-f]{32}$/),+ executionTraceFromTimestamp: expect.any(Date),+ });+ } finally {+ mutableEnv.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS =+ originalEventsTableObservationFlag;+ }+ });++ it("returns user-code dispatcher failures as structured failures", async () => {+ const { project, caller } = await prepare();+ const observationId = randomUUID();+ const traceId = randomUUID();+ const startTime = new Date();+ const template = await createCodeTemplate(+ project.id,+ `function evaluate() {+ throw new Error("User code raised ValueError");+ }`,+ );++ await createEventsCh([+ createEvent({+ project_id: project.id,+ trace_id: traceId,+ span_id: observationId,+ id: observationId,+ start_time: startTime.getTime() * 1000,+ }),+ ]);++ const response = await caller.evals.testRunCodeEval({+ projectId: project.id,+ evalTemplateId: template.id,+ target: EvalTargetObject.EVENT,+ scoreName: "unsaved-score",+ observationId,+ traceId,+ startTime,+ mapping: [],+ });++ expect(response).toEqual({+ success: false,+ error: {+ code: "USER_CODE_ERROR",+ message: "User code raised ValueError",+ },+ executionTraceId: expect.stringMatching(/^[0-9a-f]{32}$/),+ executionTraceFromTimestamp: expect.any(Date),+ });+ });++ it("passes experiment context to test runs", async () => {+ const { project, caller } = await prepare();+ const observationId = randomUUID();+ const traceId = randomUUID();+ const startTime = new Date();+ const expectedOutput = "expected answer";+ const template = await createCodeTemplate(+ project.id,+ `+ function evaluate(ctx) {+ if (!ctx.experiment) {+ throw new Error("missing experiment context");+ }++ const matched =+ ctx.observation.output === ctx.experiment.itemExpectedOutput &&+ ctx.experiment.itemMetadata.difficulty === "easy";++ return { scores: [{ name: "experiment-test-score", value: matched, dataType: "BOOLEAN" }] };+ }+ `,+ );++ await createEventsCh([+ createEvent({+ project_id: project.id,+ trace_id: traceId,+ span_id: observationId,+ id: observationId,+ start_time: startTime.getTime() * 1000,+ output: expectedOutput,+ experiment_id: randomUUID(),+ experiment_item_expected_output: expectedOutput,+ experiment_item_metadata_names: ["difficulty"],+ experiment_item_metadata_values: ["easy"],+ }),+ ]);++ const response = await caller.evals.testRunCodeEval({+ projectId: project.id,+ evalTemplateId: template.id,+ target: EvalTargetObject.EXPERIMENT,+ scoreName: "experiment-score",+ observationId,+ traceId,+ startTime,+ mapping: [+ {+ templateVariable: "output",+ selectedColumnId: "output",+ jsonSelector: null,+ },+ {+ templateVariable: "experimentItemExpectedOutput",+ selectedColumnId: "experimentItemExpectedOutput",+ jsonSelector: null,+ },+ {+ templateVariable: "experimentItemMetadata",+ selectedColumnId: "experimentItemMetadata",+ jsonSelector: null,+ },+ ],+ });++ expect(response).toEqual({+ success: true,+ result: {+ scores: [+ {+ name: "experiment-test-score",+ value: 1,+ dataType: "BOOLEAN",+ },+ ],+ },+ executionTraceId: expect.stringMatching(/^[0-9a-f]{32}$/),+ executionTraceFromTimestamp: expect.any(Date),+ });+ });++ it("persists an internal trace for the test run", async () => {+ const { project, caller } = await prepare();+ const observationId = randomUUID();+ const traceId = randomUUID();+ const startTime = new Date();+ const template = await createCodeTemplate(project.id);++ await createEventsCh([+ createEvent({+ project_id: project.id,+ trace_id: traceId,+ span_id: observationId,+ id: observationId,+ start_time: startTime.getTime() * 1000,+ }),+ ]);++ const response = await caller.evals.testRunCodeEval({+ projectId: project.id,+ evalTemplateId: template.id,+ target: EvalTargetObject.EVENT,+ scoreName: "unsaved-score",+ observationId,+ traceId,+ startTime,+ mapping: [],+ });++ if (!response.success) {+ throw new Error("Expected successful test run");+ }++ const executionTraceId = response.executionTraceId;++ const findTrace = async () => {+ const rows = await queryClickhouse<{+ environment: string;+ sourceCode: string;+ }>({+ query: `SELECT environment, metadata['code_eval_source_code'] as sourceCode FROM traces WHERE project_id = {projectId: String} AND id = {traceId: String} LIMIT 1`,+ params: { projectId: project.id, traceId: executionTraceId },+ tags: {+ feature: "evals",+ type: "traces",+ kind: "testRunCodeEvalTrace",+ projectId: project.id,+ },+ });+ return rows[0];+ };++ let trace = await findTrace();+ const deadline = Date.now() + 5_000;+ while (!trace && Date.now() < deadline) {+ await new Promise((resolve) => setTimeout(resolve, 100));+ trace = await findTrace();+ }++ expect(trace).toBeDefined();+ expect(trace?.environment).toBe("langfuse-code-eval");+ expect(trace?.sourceCode).toBe(template.sourceCode);+ });++ it("does not return observations from other projects", async () => {+ const { project: callerProject, caller } = await prepare();+ const { project: otherProject } = await prepare();+ const template = await createCodeTemplate(callerProject.id);++ const otherProjectObservationId = randomUUID();+ const otherProjectTraceId = randomUUID();+ const otherProjectStartTime = new Date();+ await createEventsCh([+ createEvent({+ project_id: otherProject.id,+ trace_id: otherProjectTraceId,+ span_id: otherProjectObservationId,+ id: otherProjectObservationId,+ start_time: otherProjectStartTime.getTime() * 1000,+ }),+ ]);++ await expect(+ caller.evals.testRunCodeEval({+ projectId: callerProject.id,+ evalTemplateId: template.id,+ target: EvalTargetObject.EVENT,+ scoreName: "unsaved-score",+ observationId: otherProjectObservationId,+ traceId: otherProjectTraceId,+ startTime: otherProjectStartTime,+ mapping: [],+ }),+ ).rejects.toThrow(/Observation not found/);+ });++ it("does not allow running templates owned by other projects", async () => {+ const { project: callerProject, caller } = await prepare();+ const { project: otherProject } = await prepare();+ const observationId = randomUUID();+ const traceId = randomUUID();+ const startTime = new Date();++ const otherProjectTemplate = await createCodeTemplate(otherProject.id);++ await createEventsCh([+ createEvent({+ project_id: callerProject.id,+ trace_id: traceId,+ span_id: observationId,+ id: observationId,+ start_time: startTime.getTime() * 1000,+ }),+ ]);++ await expect(+ caller.evals.testRunCodeEval({+ projectId: callerProject.id,+ evalTemplateId: otherProjectTemplate.id,+ target: EvalTargetObject.EVENT,+ scoreName: "unsaved-score",+ observationId,+ traceId,+ startTime,+ mapping: [],+ }),+ ).rejects.toThrow(/Evaluator template not found/);+ });+});++async function createCodeTemplate(projectId: string, sourceCode?: string) {+ return prisma.evalTemplate.create({+ data: {+ projectId,+ name: `Saved code evaluator ${randomUUID()}`,+ version: 1,+ type: EvalTemplateType.CODE,+ prompt: null,+ outputDefinition: undefined,+ sourceCode:+ sourceCode ??+ 'function evaluate() { return { scores: [{ name: "test-score", value: 1 }] }; }',+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ },+ });+}diff --git a/web/src/__tests__/server/unit/default-model-eval-template-repository.servertest.ts b/web/src/__tests__/server/unit/default-model-eval-template-repository.servertest.tsnew file mode 100644index 0000000000..255712c67e--- /dev/null+++ b/web/src/__tests__/server/unit/default-model-eval-template-repository.servertest.ts@@ -0,0 +1,33 @@+import { describe, expect, it, vi } from "vitest";+import { EvalTemplateType, type Prisma } from "@langfuse/shared/src/db";+import { findDefaultModelEvalTemplateIds } from "@/src/features/evals/server/defaultModelEvalTemplateRepository";++describe("findDefaultModelEvalTemplateIds", () => {+ it("only selects LLM-as-judge templates that depend on the default model", async () => {+ const findMany = vi.fn().mockResolvedValue([{ id: "template-1" }]);+ const tx = {+ evalTemplate: {+ findMany,+ },+ } as unknown as Prisma.TransactionClient;++ await expect(+ findDefaultModelEvalTemplateIds({+ tx,+ projectId: "project-123",+ }),+ ).resolves.toEqual(["template-1"]);++ expect(findMany).toHaveBeenCalledWith({+ where: {+ OR: [{ projectId: "project-123" }, { projectId: null }],+ provider: null,+ model: null,+ type: EvalTemplateType.LLM_AS_JUDGE,+ },+ select: {+ id: true,+ },+ });+ });+});diff --git a/web/src/__tests__/server/unit/unstable-evals-queries.servertest.ts b/web/src/__tests__/server/unit/unstable-evals-queries.servertest.tsindex e48f84b0fa..6b3f0a103b 100644--- a/web/src/__tests__/server/unit/unstable-evals-queries.servertest.ts+++ b/web/src/__tests__/server/unit/unstable-evals-queries.servertest.ts@@ -1,7 +1,12 @@+import type * as PrismaClientModule from "@prisma/client";import type { Mock } from "vitest";-vi.mock("@langfuse/shared/src/db", () => {+vi.mock("@langfuse/shared/src/db", async () => {+ const { EvalTemplateType } =+ await vi.importActual<typeof PrismaClientModule>("@prisma/client");+return {+ EvalTemplateType,Prisma: {sql: (strings: TemplateStringsArray, ...values: unknown[]) => ({strings,@@ -22,7 +27,7 @@ vi.mock("@langfuse/shared/src/db", () => {};});-import { prisma } from "@langfuse/shared/src/db";+import { EvalTemplateType, prisma } from "@langfuse/shared/src/db";import {countActiveEvaluationRules,countEvaluationRulesForEvaluatorIds,@@ -148,6 +153,12 @@ describe("unstable public eval queries", () => {},status: "ACTIVE",blockedAt: null,+ evalTemplate: {+ is: {+ type: EvalTemplateType.LLM_AS_JUDGE,+ OR: [{ projectId: "project_123" }, { projectId: null }],+ },+ },},});expect(result).toBe(17);@@ -172,6 +183,7 @@ describe("unstable public eval queries", () => {where: {projectId: "project_123",name: "Answer correctness",+ type: EvalTemplateType.LLM_AS_JUDGE,},orderBy: {version: "desc",@@ -200,6 +212,7 @@ describe("unstable public eval queries", () => {where: {projectId: null,name: "Answer correctness",+ type: EvalTemplateType.LLM_AS_JUDGE,},orderBy: {version: "desc",diff --git a/web/src/__tests__/server/unit/unstable-evals-service.servertest.ts b/web/src/__tests__/server/unit/unstable-evals-service.servertest.tsindex b545889ec5..b6f86e4379 100644--- a/web/src/__tests__/server/unit/unstable-evals-service.servertest.ts+++ b/web/src/__tests__/server/unit/unstable-evals-service.servertest.ts@@ -1,3 +1,4 @@+import type * as PrismaClientModule from "@prisma/client";import type { Mock } from "vitest";const mockEvalTemplateCreate = vi.fn();@@ -42,47 +43,53 @@ vi.mock("@langfuse/shared/src/server", async () => ({},}));-vi.mock("@langfuse/shared/src/db", () => ({- Prisma: {- PrismaClientKnownRequestError: class PrismaClientKnownRequestError extends Error {- code: string;- clientVersion: string;+vi.mock("@langfuse/shared/src/db", async () => {+ const { EvalTemplateType } =+ await vi.importActual<typeof PrismaClientModule>("@prisma/client");- constructor(- message: string,- {- code,- clientVersion,- }: {- code: string;- clientVersion: string;- },- ) {- super(message);- this.code = code;- this.clientVersion = clientVersion;- }- },- },- prisma: {- $transaction: vi.fn(),- dataset: {- findMany: vi.fn(),+ return {+ EvalTemplateType,+ Prisma: {+ PrismaClientKnownRequestError: class PrismaClientKnownRequestError extends Error {+ code: string;+ clientVersion: string;++ constructor(+ message: string,+ {+ code,+ clientVersion,+ }: {+ code: string;+ clientVersion: string;+ },+ ) {+ super(message);+ this.code = code;+ this.clientVersion = clientVersion;+ }+ },},- jobConfiguration: {- findFirst: vi.fn(),- create: vi.fn(),- update: vi.fn(),+ prisma: {+ $transaction: vi.fn(),+ dataset: {+ findMany: vi.fn(),+ },+ jobConfiguration: {+ findFirst: vi.fn(),+ create: vi.fn(),+ update: vi.fn(),+ },},- },-}));+ };+});import {createNumericEvalOutputDefinition,EvalTargetObject,JobConfigState,} from "@langfuse/shared";-import { prisma } from "@langfuse/shared/src/db";+import { EvalTemplateType, prisma } from "@langfuse/shared/src/db";import { createUnstablePublicApiError } from "@/src/features/public-api/server/unstable-public-api-error-contract";import {createPublicEvaluationRule,@@ -256,6 +263,7 @@ describe("unstable public eval services", () => {where: {projectId: "project_123",name: "Answer correctness",+ type: EvalTemplateType.LLM_AS_JUDGE,},select: {id: true,@@ -343,6 +351,11 @@ describe("unstable public eval services", () => {evalTemplateId: {in: ["tmpl_project_v2", "tmpl_project_v1"],},+ evalTemplate: {+ is: {+ type: EvalTemplateType.LLM_AS_JUDGE,+ },+ },},select: {id: true,@@ -650,6 +663,25 @@ describe("unstable public eval services", () => {'An evaluation rule named "answer_quality" already exists in this project.',);+ expect(mockedPrisma.jobConfiguration.findFirst).toHaveBeenCalledWith({+ where: {+ projectId: "project_123",+ jobType: "EVAL",+ targetObject: {+ in: [EvalTargetObject.EVENT, EvalTargetObject.EXPERIMENT],+ },+ scoreName: "answer_quality",+ evalTemplate: {+ is: {+ type: EvalTemplateType.LLM_AS_JUDGE,+ OR: [{ projectId: "project_123" }, { projectId: null }],+ },+ },+ },+ select: {+ id: true,+ },+ });expect(mockLoadEvaluatorForEvaluationRule).not.toHaveBeenCalled();expect(mockedPrisma.jobConfiguration.create).not.toHaveBeenCalled();});diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.tsindex 5e3379e2df..7efca98938 100644--- a/web/src/__tests__/test-utils.ts+++ b/web/src/__tests__/test-utils.ts@@ -1,4 +1,5 @@import {+ CodeEvalExecutionQueue,EvalExecutionQueue,LLMAsJudgeExecutionQueue,SecondaryEvalExecutionQueue,@@ -22,6 +23,7 @@ export const getQueues = () => {...EvalExecutionQueue.getShardNames(),...SecondaryEvalExecutionQueue.getShardNames(),...LLMAsJudgeExecutionQueue.getShardNames(),+ ...CodeEvalExecutionQueue.getShardNames(),...OtelIngestionQueue.getShardNames(),...SecondaryOtelIngestionQueue.getShardNames(),...TraceUpsertQueue.getShardNames(),@@ -54,29 +56,36 @@ export const getQueues = () => {? LLMAsJudgeExecutionQueue.getInstance({shardName: queueName,})- : queueName.startsWith(QueueName.TraceUpsert)- ? TraceUpsertQueue.getInstance({ shardName: queueName })- : queueName.startsWith(QueueName.OtelIngestionSecondaryQueue)- ? SecondaryOtelIngestionQueue.getInstance({- shardName: queueName,- })- : queueName.startsWith(QueueName.OtelIngestionQueue)- ? OtelIngestionQueue.getInstance({+ : queueName.startsWith(QueueName.CodeEvalExecution)+ ? CodeEvalExecutionQueue.getInstance({+ shardName: queueName,+ })+ : queueName.startsWith(QueueName.TraceUpsert)+ ? TraceUpsertQueue.getInstance({ shardName: queueName })+ : queueName.startsWith(+ QueueName.OtelIngestionSecondaryQueue,+ )+ ? SecondaryOtelIngestionQueue.getInstance({shardName: queueName,})- : getQueue(- queueName as Exclude<- QueueName,- | QueueName.IngestionQueue- | QueueName.IngestionSecondaryQueue- | QueueName.EvaluationExecution- | QueueName.EvaluationExecutionSecondaryQueue- | QueueName.LLMAsJudgeExecution- | QueueName.TraceUpsert- | QueueName.OtelIngestionQueue- | QueueName.OtelIngestionSecondaryQueue- >,- ),+ : queueName.startsWith(QueueName.OtelIngestionQueue)+ ? OtelIngestionQueue.getInstance({+ shardName: queueName,+ })+ : getQueue(+ queueName as Exclude<+ QueueName,+ | QueueName.IngestionQueue+ | QueueName.IngestionSecondaryQueue+ | QueueName.EvaluationExecution+ | QueueName.EvaluationExecutionSecondaryQueue+ | QueueName.LLMAsJudgeExecution+ | QueueName.CodeEvalExecution+ | QueueName.TraceUpsert+ | QueueName.OtelIngestionQueue+ | QueueName.OtelIngestionSecondaryQueue+ >,+ ),);};diff --git a/web/src/components/layouts/routes.tsx b/web/src/components/layouts/routes.tsxindex 17f883542d..2dc7aa4388 100644--- a/web/src/components/layouts/routes.tsx+++ b/web/src/components/layouts/routes.tsx@@ -148,7 +148,7 @@ export const ROUTES: Route[] = [icon: SquarePercent,},{- title: "LLM-as-a-Judge",+ title: "Evaluators",icon: Lightbulb,productModule: "evaluation",projectRbacScopes: ["evalJob:read"],diff --git a/web/src/components/onboarding/EvaluatorsOnboarding.tsx b/web/src/components/onboarding/EvaluatorsOnboarding.tsxindex 51070f6273..81b4b56591 100644--- a/web/src/components/onboarding/EvaluatorsOnboarding.tsx+++ b/web/src/components/onboarding/EvaluatorsOnboarding.tsx@@ -3,14 +3,17 @@ import {SplashScreen,type ValueProposition,} from "@/src/components/ui/splash-screen";-import { Bot, Gauge, Zap, BarChart4 } from "lucide-react";+import { Bot, Gauge, Zap, BarChart4, Code2 } from "lucide-react";+import { useIsCodeEvalEnabled } from "@/src/features/evals/hooks/useIsCodeEvalEnabled";interface EvaluatorsOnboardingProps {projectId: string;}export function EvaluatorsOnboarding({ projectId }: EvaluatorsOnboardingProps) {- const valuePropositions: ValueProposition[] = [+ const { enabled } = useIsCodeEvalEnabled();++ const llmAsJudgeValuePropositions: ValueProposition[] = [{title: "Automate evaluations",description:@@ -37,11 +40,44 @@ export function EvaluatorsOnboarding({ projectId }: EvaluatorsOnboardingProps) {},];+ if (enabled) {+ const evaluatorTypes: ValueProposition[] = [+ {+ title: "LLM-as-a-judge evaluators",+ description:+ "Use an LLM to score outputs against natural-language criteria.",+ icon: <Bot className="h-4 w-4" />,+ },+ {+ title: "Code evaluators",+ description:+ "Write TypeScript or Python logic for deterministic, custom scoring.",+ icon: <Code2 className="h-4 w-4" />,+ },+ ];++ return (+ <SplashScreen+ title="Get started with evaluations"+ description="Use evaluators to score traces and observations automatically. Langfuse supports two evaluator types:"+ valuePropositions={evaluatorTypes}+ primaryAction={{+ label: "Create Evaluator",+ href: `/project/${projectId}/evals/new`,+ }}+ secondaryAction={{+ label: "Learn More",+ href: "https://langfuse.com/docs/evaluation",+ }}+ />+ );+ }+return (<SplashScreentitle="Get Started with LLM-as-a-Judge Evaluations"description="Create evaluation templates and evaluators to automatically score your traces with LLM-as-a-judge. Set up custom evaluation criteria and let AI help you measure the quality of your outputs."- valuePropositions={valuePropositions}+ valuePropositions={llmAsJudgeValuePropositions}primaryAction={{label: "Create Evaluator",href: `/project/${projectId}/evals/new`,diff --git a/web/src/components/table/ValueCell.tsx b/web/src/components/table/ValueCell.tsxindex 6be41dc841..011c30b68e 100644--- a/web/src/components/table/ValueCell.tsx+++ b/web/src/components/table/ValueCell.tsx@@ -159,10 +159,12 @@ export const ValueCell = memo(row,expandedCells,toggleCellExpansion,+ preserveStringWhitespace = false,}: {row: Row<JsonTableRow>;expandedCells: Set<string>;toggleCellExpansion: (cellId: string) => void;+ preserveStringWhitespace?: boolean;}) => {const { value, type } = row.original;const cellId = `${row.id}-value`;@@ -194,7 +196,13 @@ export const ValueCell = memo(return {content: (- <span className="whitespace-pre-line text-green-600 dark:text-green-400">+ <span+ className={`text-green-600 dark:text-green-400 ${+ preserveStringWhitespace+ ? "whitespace-pre-wrap"+ : "whitespace-pre-line"+ }`}+ >"{renderStringWithLinks(displayValue)}"</span>),diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsxindex 3581692a39..8a683b2f1d 100644--- a/web/src/components/table/use-cases/observations.tsx+++ b/web/src/components/table/use-cases/observations.tsx@@ -69,7 +69,10 @@ import TableIdOrName from "@/src/components/table/table-id";import { ItemBadge } from "@/src/components/ItemBadge";import { TablePeekViewObservationDetail } from "@/src/components/table/peek/peek-observation-detail";import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";-import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";+import {+ detailPageListKeys,+ useDetailPageLists,+} from "@/src/features/navigate-detail-pages/context";import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";import { useRouter } from "next/router";import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextSearch";@@ -552,7 +555,7 @@ export default function ObservationsTable({useEffect(() => {if (generations.isSuccess) {setDetailPageList(- "observations",+ detailPageListKeys.observations,generations.data.generations.map((g) => ({id: g.id,params: {@@ -560,6 +563,7 @@ export default function ObservationsTable({...(g.traceTimestamp? { timestamp: g.traceTimestamp.toISOString() }: {}),+ startTime: g.startTime.toISOString(),},})),);@@ -1268,11 +1272,18 @@ export default function ObservationsTable({);const peekNavigationProps = usePeekNavigation({- queryParams: ["observation", "display", "timestamp", "traceId"],+ queryParams: [+ "observation",+ "display",+ "timestamp",+ "traceId",+ "startTime",+ ],paramsToMirrorPeekValue: ["observation"],extractParamsValuesFromRow: (row: ObservationsTableRow) => ({traceId: row.traceId || "",timestamp: row.timestamp?.toISOString() || "",+ startTime: row.startTime.toISOString(),}),expandConfig: {basePath: `/project/${projectId}/traces`,@@ -1307,7 +1318,7 @@ export default function ObservationsTable({if (hideControls) return undefined;return {itemType: "TRACE",- detailNavigationKey: "observations",+ detailNavigationKey: detailPageListKeys.observations,...peekNavigationProps,};}, [peekNavigationProps, hideControls]);diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsxindex 06f4b08113..7b7eb4ed9e 100644--- a/web/src/components/table/use-cases/traces.tsx+++ b/web/src/components/table/use-cases/traces.tsx@@ -34,7 +34,10 @@ import {LevelSymbols,} from "@/src/components/level-colors";import { cn } from "@/src/utils/tailwind";-import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";+import {+ detailPageListKeys,+ useDetailPageLists,+} from "@/src/features/navigate-detail-pages/context";import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";import {type FilterState,@@ -454,7 +457,7 @@ export default function TracesTable({useEffect(() => {if (traces.isSuccess) {setDetailPageList(- "traces",+ detailPageListKeys.traces,traces.data.traces.map((t) => ({id: t.id,params: { timestamp: t.timestamp.toISOString() },@@ -1294,7 +1297,7 @@ export default function TracesTable({if (hideControls) return undefined;return {itemType: "TRACE" as const,- detailNavigationKey: "traces",+ detailNavigationKey: detailPageListKeys.traces,peekEventOptions: {ignoredSelectors: ['[role="checkbox"]', '[aria-label="bookmark"]'],},diff --git a/web/src/components/ui/PrettyJsonView.tsx b/web/src/components/ui/PrettyJsonView.tsxindex 9e1a25ebd9..faf744e0ef 100644--- a/web/src/components/ui/PrettyJsonView.tsx+++ b/web/src/components/ui/PrettyJsonView.tsx@@ -682,6 +682,9 @@ function JsonPrettyTable({row={row}expandedCells={expandedCells}toggleCellExpansion={toggleCellExpansion}+ preserveStringWhitespace={+ row.original.key === "code_eval_source_code"+ }/>),},diff --git a/web/src/components/ui/dialog.tsx b/web/src/components/ui/dialog.tsxindex d3bda134e8..207245be51 100644--- a/web/src/components/ui/dialog.tsx+++ b/web/src/components/ui/dialog.tsx@@ -51,6 +51,7 @@ const DialogContent = React.forwardRef<React.ComponentRef<typeof DialogPrimitive.Content>,React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {closeOnInteractionOutside?: boolean;+ confirmCloseOnEscape?: string;stopPropagationOnEnterSpace?: boolean;} & VariantProps<typeof dialogContentVariants>>(@@ -59,7 +60,9 @@ const DialogContent = React.forwardRef<className,children,closeOnInteractionOutside = false,+ confirmCloseOnEscape,stopPropagationOnEnterSpace = true,+ onEscapeKeyDown,size,...props},@@ -72,6 +75,19 @@ const DialogContent = React.forwardRef<e.stopPropagation();}};+ const handleEscapeKeyDown: React.ComponentPropsWithoutRef<+ typeof DialogPrimitive.Content+ >["onEscapeKeyDown"] = (e) => {+ onEscapeKeyDown?.(e);++ if (e.defaultPrevented || !confirmCloseOnEscape) {+ return;+ }++ if (!window.confirm(confirmCloseOnEscape)) {+ e.preventDefault();+ }+ };return (<DialogPortal>@@ -81,6 +97,7 @@ const DialogContent = React.forwardRef<className={cn(dialogContentVariants({ size, className }))}aria-describedby={undefined}onKeyDown={handleKeyDown}+ onEscapeKeyDown={handleEscapeKeyDown}onPointerDownOutside={(e) => {if (!closeOnInteractionOutside) {e.preventDefault();diff --git a/web/src/env.mjs b/web/src/env.mjsindex 57806cc9fd..8f9123fa17 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -485,6 +485,11 @@ export const env = createEnv({.enum(["true", "false"]).optional().default("true"),+ // Code-based evals: must match LANGFUSE_CODE_EVAL_DISPATCHER being set in packages/shared/src/env.ts+ NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED: z+ .enum(["true", "false"])+ .optional()+ .default("false"),},/**@@ -773,6 +778,9 @@ export const env = createEnv({// PlaygroundNEXT_PUBLIC_LANGFUSE_PLAYGROUND_STREAMING_ENABLED_DEFAULT:process.env.NEXT_PUBLIC_LANGFUSE_PLAYGROUND_STREAMING_ENABLED_DEFAULT,+ // Code-based evals+ NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED:+ process.env.NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED,// EE LicenseLANGFUSE_EE_LICENSE_KEY: process.env.LANGFUSE_EE_LICENSE_KEY,ADMIN_API_KEY: process.env.ADMIN_API_KEY,diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/utils.ts b/web/src/features/batch-actions/components/RunEvaluationDialog/utils.tsindex ed1bcf4920..c3bf2f2880 100644--- a/web/src/features/batch-actions/components/RunEvaluationDialog/utils.ts+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/utils.ts@@ -1,5 +1,5 @@import {- extractValueFromObject,+ extractValueFromObjectAsString,type BatchActionQuery,type ObservationVariableMapping,} from "@langfuse/shared";@@ -42,7 +42,7 @@ export function renderPromptPreviewFromObservation(params: {const variableValues = new Map<string, string>();for (const mapping of variableMapping) {- const { value } = extractValueFromObject(+ const { value } = extractValueFromObjectAsString(observation,mapping.selectedColumnId,mapping.jsonSelector ?? undefined,diff --git a/web/src/features/evals/components/code-eval-template-form-body.tsx b/web/src/features/evals/components/code-eval-template-form-body.tsxnew file mode 100644index 0000000000..6ede6fa8bf--- /dev/null+++ b/web/src/features/evals/components/code-eval-template-form-body.tsx@@ -0,0 +1,440 @@+import CodeMirror, {+ EditorView,+ ExternalChange,+ hoverTooltip,+ keymap,+} from "@uiw/react-codemirror";+import { EditorState } from "@codemirror/state";+import { linter, type Diagnostic } from "@codemirror/lint";+import { StreamLanguage, type StringStream } from "@codemirror/language";+import { python } from "@codemirror/lang-python";+import { EvalTemplateSourceCodeLanguage } from "@langfuse/shared";+import { useTheme } from "next-themes";+import {+ type ReactNode,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { Loader2 } from "lucide-react";++import { Button } from "@/src/components/ui/button";+import { darkTheme } from "@/src/components/editor/dark-theme";+import { lightTheme } from "@/src/components/editor/light-theme";+import {+ getCodeEvalHoverDocs,+ type CodeEvalHoverDocs,+} from "@/src/features/evals/utils/code-eval-template-hover-docs";+import {+ TYPESCRIPT_CODE_EVAL_CONTRACT,+ type CodeEvalSourceCodeLanguage,+ type CodeEvalValidationResult,+} from "@/src/features/evals/utils/code-eval-template-validation";++type CodeEvalTemplateFormBodyProps = {+ sourceCode: string;+ sourceCodeLanguage: CodeEvalSourceCodeLanguage;+ onSourceCodeChange: (value: string) => void;+ editable: boolean;+ validationResult: CodeEvalValidationResult | null;+ headerAction?: ReactNode;+};++type ProtectedRange = {+ from: number;+ to: number;+};++type ContractRanges = {+ prelude: ProtectedRange | null;+ signature: ProtectedRange;+};++const PYTHON_EVALUATE_SIGNATURE_PATTERN =+ /(?:^|\n)def evaluate\s*\(\s*ctx\s*:\s*EvaluationContext\s*\)\s*->\s*EvaluationResult\s*:/;+const FORMAT_SHORTCUT_KEY = "Shift-Alt-f";+const FORMAT_SHORTCUT_ARIA = "Alt+Shift+F";+const TYPESCRIPT_KEYWORDS = new Set([+ "async",+ "await",+ "const",+ "let",+ "return",+ "export",+ "function",+ "type",+ "interface",+ "if",+ "else",+ "true",+ "false",+ "undefined",+ "null",+]);+const TYPESCRIPT_BUILTIN_TYPES = new Set([+ "any",+ "boolean",+ "number",+ "Promise",+ "Record",+ "string",+ "unknown",+]);++const typescriptCodeEvalLanguage = StreamLanguage.define({+ name: "typescript-code-eval",+ token: (stream: StringStream) => {+ if (stream.match("//")) {+ stream.skipToEnd();+ return "comment";+ }++ if (stream.match("/*")) {+ while (!stream.eol()) {+ if (stream.match("*/")) break;+ stream.next();+ }+ return "comment";+ }++ if (stream.match(/["'`]/, false)) {+ const quote = stream.next();+ let escaped = false;+ while (!stream.eol()) {+ const next = stream.next();+ if (next === quote && !escaped) break;+ escaped = next === "\\" && !escaped;+ }+ return "string";+ }++ const identifier = stream.match(/[A-Za-z_][A-Za-z0-9_]*/, false);+ if (identifier && identifier !== true) {+ const word = identifier[0];+ stream.match(word);+ if (TYPESCRIPT_KEYWORDS.has(word)) return "keyword";+ if (TYPESCRIPT_BUILTIN_TYPES.has(word) || /^[A-Z]/.test(word)) {+ return "typeName";+ }+ return null;+ }++ if (stream.match(/\b\d+(?:\.\d+)?\b/)) {+ return "number";+ }++ stream.next();+ return null;+ },+});++function createCodeEvalHoverExtension(hoverDocs: CodeEvalHoverDocs) {+ return hoverTooltip((view, pos) => {+ const line = view.state.doc.lineAt(pos);+ const text = line.text;+ const offset = pos - line.from;+ const before = text.slice(0, offset).match(/[A-Za-z_][A-Za-z0-9_]*$/)?.[0];+ const after = text.slice(offset).match(/^[A-Za-z0-9_]*/)?.[0] ?? "";+ const word = `${before ?? ""}${after}`;+ const hoverDoc = hoverDocs[word];+ if (!word || !hoverDoc) return null;++ const from = pos - (before?.length ?? 0);+ const to = from + word.length;++ return {+ pos: from,+ end: to,+ create() {+ const dom = document.createElement("div");+ dom.className =+ "max-w-xl whitespace-pre-wrap rounded-md border bg-popover px-3 py-2 font-mono text-xs text-popover-foreground shadow-md";+ dom.textContent = hoverDoc;+ return { dom };+ },+ };+ });+}++function findPythonContractRanges(source: string): ContractRanges | null {+ const match = source.match(PYTHON_EVALUATE_SIGNATURE_PATTERN);+ if (!match || match.index === undefined) return null;++ const signatureStart = match.index + (match[0].startsWith("\n") ? 1 : 0);+ const signatureLineEnd = source.indexOf("\n", signatureStart);+ const signatureTo =+ signatureLineEnd === -1 ? source.length : signatureLineEnd + 1;++ return {+ prelude: signatureStart > 0 ? { from: 0, to: signatureStart } : null,+ signature: { from: signatureStart, to: signatureTo },+ };+}++function findTypeScriptContractRanges(source: string): ContractRanges | null {+ if (!source.startsWith(TYPESCRIPT_CODE_EVAL_CONTRACT)) return null;++ return {+ prelude: { from: 0, to: TYPESCRIPT_CODE_EVAL_CONTRACT.length },+ signature: {+ from: TYPESCRIPT_CODE_EVAL_CONTRACT.length,+ to: TYPESCRIPT_CODE_EVAL_CONTRACT.length,+ },+ };+}++function getProtectedContractRanges(source: string): ProtectedRange[] {+ const ranges =+ findPythonContractRanges(source) ?? findTypeScriptContractRanges(source);+ if (!ranges) return [];++ return [+ ...(ranges.prelude ? [ranges.prelude] : []),+ ...(ranges.signature.from < ranges.signature.to ? [ranges.signature] : []),+ ];+}++function isChangeInProtectedRange(+ from: number,+ to: number,+ range: ProtectedRange,+) {+ if (from === to) {+ return from >= range.from && from < range.to;+ }++ return from < range.to && to > range.from;+}++const contractReadOnlyExtension = EditorState.changeFilter.of((tr) => {+ if (!tr.docChanged) return true;+ if (tr.annotation(ExternalChange)) return true;++ const protectedRanges = getProtectedContractRanges(+ tr.startState.doc.toString(),+ );+ if (protectedRanges.length === 0) return true;++ let touchesProtectedRange = false;+ tr.changes.iterChangedRanges((fromA, toA) => {+ if (+ protectedRanges.some((range) =>+ isChangeInProtectedRange(fromA, toA, range),+ )+ ) {+ touchesProtectedRange = true;+ }+ }, true);++ return touchesProtectedRange ? false : true;+});++const contractReadOnlyExtensions = [contractReadOnlyExtension];++async function formatTypeScriptSource(source: string) {+ const [{ format }, typescriptPlugin, estreePlugin] = await Promise.all([+ import("prettier/standalone"),+ import("prettier/plugins/typescript"),+ import("prettier/plugins/estree"),+ ]);++ const ranges = findTypeScriptContractRanges(source);+ if (!ranges?.prelude) {+ return format(source, {+ parser: "typescript",+ plugins: [typescriptPlugin, estreePlugin],+ });+ }++ const formattedEditableSource = await format(+ source.slice(ranges.prelude.to),+ {+ parser: "typescript",+ plugins: [typescriptPlugin, estreePlugin],+ },+ );++ return `${source.slice(0, ranges.prelude.to)}\n${formattedEditableSource.trimStart()}`;+}++function scrollCodeMirrorToBottom(view: EditorView) {+ if (typeof window === "undefined") return;++ window.requestAnimationFrame(() => {+ if (!view.dom.isConnected) return;++ view.dispatch({+ effects: EditorView.scrollIntoView(view.state.doc.length, { y: "end" }),+ });+ });+}++export function CodeEvalTemplateFormBody({+ sourceCode,+ sourceCodeLanguage,+ onSourceCodeChange,+ editable,+ validationResult,+ headerAction,+}: CodeEvalTemplateFormBodyProps) {+ const { resolvedTheme } = useTheme();+ const codeMirrorViewRef = useRef<EditorView | null>(null);+ const [isFormatting, setIsFormatting] = useState(false);+ const codeMirrorTheme = resolvedTheme === "dark" ? darkTheme : lightTheme;+ const languageLabel =+ sourceCodeLanguage === EvalTemplateSourceCodeLanguage.PYTHON+ ? "Python"+ : "TypeScript";+ const canFormatSource =+ sourceCodeLanguage === EvalTemplateSourceCodeLanguage.TYPESCRIPT;+ const shouldShowFormatButton = editable && canFormatSource;++ const handleCreateEditor = useCallback((view: EditorView) => {+ codeMirrorViewRef.current = view;+ scrollCodeMirrorToBottom(view);+ }, []);++ useEffect(() => {+ const view = codeMirrorViewRef.current;+ if (!view) return;++ scrollCodeMirrorToBottom(view);+ }, [sourceCode, sourceCodeLanguage]);++ const diagnostics = useMemo(+ () => validationResult?.diagnostics ?? [],+ [validationResult?.diagnostics],+ );++ const formatSource = useCallback(async () => {+ if (!editable || isFormatting || !canFormatSource) return;++ setIsFormatting(true);+ try {+ const formatted = await formatTypeScriptSource(sourceCode);+ onSourceCodeChange(formatted);+ } catch (error) {+ console.error(error);+ } finally {+ setIsFormatting(false);+ }+ }, [editable, isFormatting, canFormatSource, onSourceCodeChange, sourceCode]);++ const linterExtension = useMemo(+ () =>+ linter(() =>+ diagnostics.map(+ (diagnostic): Diagnostic => ({+ from: diagnostic.from,+ to: Math.max(diagnostic.from + 1, diagnostic.to),+ severity: diagnostic.severity,+ message: diagnostic.message,+ }),+ ),+ ),+ [diagnostics],+ );+ const formatShortcutExtension = useMemo(+ () =>+ keymap.of([+ {+ key: FORMAT_SHORTCUT_KEY,+ run: () => {+ void formatSource();+ return true;+ },+ },+ ]),+ [formatSource],+ );+ const languageExtension = useMemo(+ () =>+ sourceCodeLanguage === EvalTemplateSourceCodeLanguage.PYTHON+ ? python()+ : typescriptCodeEvalLanguage,+ [sourceCodeLanguage],+ );+ const codeEvalHoverExtension = useMemo(+ () =>+ createCodeEvalHoverExtension(getCodeEvalHoverDocs(sourceCodeLanguage)),+ [sourceCodeLanguage],+ );+ const protectedContractExtensions = useMemo(+ () => contractReadOnlyExtensions,+ [],+ );++ return (+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <div className="flex min-w-0 items-center gap-2">+ <span className="text-muted-foreground text-sm">{languageLabel}</span>+ {headerAction}+ </div>+ {shouldShowFormatButton ? (+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={isFormatting}+ aria-keyshortcuts={FORMAT_SHORTCUT_ARIA}+ onClick={() => void formatSource()}+ >+ {isFormatting && (+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />+ )}+ Format+ <kbd className="bg-muted text-muted-foreground pointer-events-none ml-2 hidden h-4 items-center gap-1 rounded border px-1.5 font-mono text-[10px] font-medium select-none sm:inline-flex">+ {typeof navigator !== "undefined" &&+ navigator.userAgent.includes("Macintosh") ? (+ <>+ <span className="text-xs">⇧</span>+ <span className="text-xs">⌥</span>F+ </>+ ) : (+ <>Shift+Alt+F</>+ )}+ </kbd>+ </Button>+ ) : null}+ </div>+ <CodeMirror+ value={sourceCode}+ theme={codeMirrorTheme}+ basicSetup={{+ foldGutter: true,+ highlightActiveLine: false,+ lineNumbers: true,+ searchKeymap: true,+ }}+ extensions={[+ ...(!editable ? [EditorState.readOnly.of(true)] : []),+ languageExtension,+ ...protectedContractExtensions,+ codeEvalHoverExtension,+ linterExtension,+ ...(shouldShowFormatButton ? [formatShortcutExtension] : []),+ EditorView.lineWrapping,+ EditorView.theme({+ "&.cm-focused": { outline: "none" },+ ".cm-gutters": { borderRight: "1px solid" },+ ".cm-scroller": {+ minHeight: "360px",+ maxHeight: "60dvh",+ overflow: "auto",+ },+ ".cm-content": {+ minHeight: "360px",+ },+ }),+ ]}+ editable={editable}+ onCreateEditor={handleCreateEditor}+ onChange={onSourceCodeChange}+ className="overflow-hidden rounded-md border text-xs"+ />+ </div>+ );+}diff --git a/web/src/features/evals/components/code-eval-test-run-card.tsx b/web/src/features/evals/components/code-eval-test-run-card.tsxnew file mode 100644index 0000000000..bc07d318f3--- /dev/null+++ b/web/src/features/evals/components/code-eval-test-run-card.tsx@@ -0,0 +1,346 @@+import { CodeMirrorEditor } from "@/src/components/editor";+import { TablePeekViewTraceDetail } from "@/src/components/table/peek/peek-trace-detail";+import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";+import { Badge } from "@/src/components/ui/badge";+import { Button } from "@/src/components/ui/button";+import { Card } from "@/src/components/ui/card";+import { Skeleton } from "@/src/components/ui/skeleton";+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import {+ type PreviewData,+ usePreviewData,+} from "@/src/features/evals/hooks/usePreviewData";+import { useFirstEvalPreviewPointer } from "@/src/features/evals/hooks/useEvalPreviewNavigation";+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";+import { detailPageListKeys } from "@/src/features/navigate-detail-pages/context";+import { api, type RouterOutputs } from "@/src/utils/api";+import {+ deepParseJson,+ EvalTargetObject,+ type EvalTemplate,+} from "@langfuse/shared";+import { ExternalLink, ListTree, Play, RotateCcw } from "lucide-react";+import Link from "next/link";+import { useMemo } from "react";+import { toast } from "sonner";++import { type EvalFormType } from "@/src/features/evals/utils/evaluator-form-utils";+import { getCodeEvalVariableMapping } from "@/src/features/evals/utils/code-eval-template-utils";+import {+ isEventTarget,+ isExperimentTarget,+} from "@/src/features/evals/utils/typeHelpers";++type CodeEvalTestRunResult =+ | RouterOutputs["evals"]["testRunCodeEval"]+ | undefined;+type CodeEvalTestRunScore = Extract<+ Exclude<CodeEvalTestRunResult, undefined>,+ { success: true }+>["result"]["scores"][number];+type CodeEvalInputPreviewData = Extract<+ PreviewData,+ { type: typeof EvalTargetObject.EVENT }+>;++function isCodeEvalTestTarget(+ target: EvalFormType["target"],+): target is+ | typeof EvalTargetObject.EVENT+ | typeof EvalTargetObject.EXPERIMENT {+ return isEventTarget(target) || isExperimentTarget(target);+}++export function CodeEvalTestRunCard({+ projectId,+ evalTemplate,+ target,+ scoreName,+ disabled = false,+ enableExecutionTracePeek = true,+}: {+ projectId: string;+ evalTemplate: EvalTemplate;+ target: EvalFormType["target"];+ scoreName: EvalFormType["scoreName"];+ disabled?: boolean;+ enableExecutionTracePeek?: boolean;+}) {+ const { isBetaEnabled } = useV4Beta();+ const isSupportedTarget = isCodeEvalTestTarget(target);+ const canPreview = isSupportedTarget && !disabled;+ const previewPointer = useFirstEvalPreviewPointer({+ target,+ useEventsTable: isBetaEnabled,+ });+ const peekNavigationProps = usePeekNavigation({+ queryParams: ["observation", "display", "timestamp"],+ expandConfig: {+ basePath: `/project/${projectId}/traces`,+ },+ });+ const peekConfig = useMemo(+ () => ({+ itemType: "TRACE" as const,+ detailNavigationKey: detailPageListKeys.traces,+ ...peekNavigationProps,+ }),+ [peekNavigationProps],+ );++ const { previewData, isLoading } = usePreviewData({+ projectId,+ enabled: canPreview && Boolean(previewPointer),+ target,+ traceId: previewPointer?.traceId,+ observationId: previewPointer?.observationId,+ timestamp: previewPointer?.timestamp,+ });++ const observationId = previewData?.observationId;+ const traceId = previewData?.traceId;+ const timestamp = previewData?.timestamp;++ const testRunMutation = api.evals.testRunCodeEval.useMutation({+ onSuccess: (result) => {+ if (result.success) {+ return;+ }++ toast.error(result.error.message);+ },+ });++ if (!isSupportedTarget || !canPreview) return null;++ return (+ <>+ <Card className="flex min-w-0 flex-col gap-4 p-4">+ <div className="flex items-center justify-between gap-3">+ <div className="flex min-w-0 items-center gap-2">+ <span className="text-sm font-medium">Test run</span>+ </div>+ <div className="flex shrink-0 items-center gap-2">+ {evalTemplate.projectId ? (+ <Button asChild variant="outline">+ <Link+ href={`/project/${projectId}/evals/templates/${evalTemplate.id}?mode=edit`}+ target="_blank"+ rel="noopener noreferrer"+ >+ Source code+ <ExternalLink className="ml-1 h-3.5 w-3.5" />+ </Link>+ </Button>+ ) : (+ <Button+ variant="outline"+ disabled+ title="Only user-managed templates can be edited"+ >+ Source code+ <ExternalLink className="ml-1 h-3.5 w-3.5" />+ </Button>+ )}+ <Button+ type="button"+ variant="outline"+ loading={testRunMutation.isPending}+ disabled={!observationId || isLoading}+ onClick={() => {+ if (!observationId || !traceId) return;++ testRunMutation.mutate({+ projectId,+ evalTemplateId: evalTemplate.id,+ target,+ mapping: getCodeEvalVariableMapping(),+ scoreName,+ observationId,+ traceId,+ startTime: timestamp,+ shouldReadFromObservationsTable: !isBetaEnabled,+ });+ }}+ >+ {testRunMutation.data ? (+ <RotateCcw className="mr-1.5 h-3.5 w-3.5" />+ ) : (+ <Play className="mr-1.5 h-3.5 w-3.5" />+ )}+ Test+ </Button>+ </div>+ </div>++ <CodeEvalTestRunInputPreview+ previewData={previewData}+ isLoading={isLoading}+ includeExperimentVariables={target === EvalTargetObject.EXPERIMENT}+ />++ {testRunMutation.data ? (+ <CodeEvalTestRunResultView+ result={testRunMutation.data}+ onShowExecutionTrace={+ enableExecutionTracePeek+ ? (executionTraceId) => {+ peekConfig.openPeek?.(executionTraceId);+ }+ : undefined+ }+ />+ ) : null}++ <p className="text-muted-foreground text-xs">+ Read-only preview. Inputs are sampled from the first matching+ observation.+ </p>+ </Card>+ {enableExecutionTracePeek ? (+ <TablePeekViewTraceDetail {...peekConfig} projectId={projectId} />+ ) : null}+ </>+ );+}++function CodeEvalTestRunInputPreview({+ previewData,+ isLoading,+ includeExperimentVariables,+}: {+ previewData: PreviewData | null;+ isLoading: boolean;+ includeExperimentVariables: boolean;+}) {+ if (isLoading) {+ const skeletonCount = includeExperimentVariables ? 5 : 3;+ return (+ <div className="grid gap-2">+ {Array.from({ length: skeletonCount }).map((_, index) => (+ <Skeleton key={index} className="h-24 w-full" />+ ))}+ </div>+ );+ }++ if (!previewData) {+ return (+ <div className="text-muted-foreground flex min-h-32 items-center justify-center rounded-md border border-dashed p-4 text-center text-sm">+ No matching observation+ </div>+ );+ }++ return (+ <CodeEvalTestRunInputCards+ previewData={previewData as CodeEvalInputPreviewData}+ includeExperimentVariables={includeExperimentVariables}+ />+ );+}++function CodeEvalTestRunInputCards({+ previewData,+ includeExperimentVariables,+}: {+ previewData: CodeEvalInputPreviewData;+ includeExperimentVariables: boolean;+}) {+ const inputPreviewJson = useMemo(() => {+ const data = previewData.data;++ return {+ observation: {+ input: deepParseJson(data.input),+ output: deepParseJson(data.output),+ metadata: deepParseJson(data.metadata),+ },+ ...(includeExperimentVariables+ ? {+ experiment: {+ itemExpectedOutput: deepParseJson(+ data.experimentItemExpectedOutput,+ ),+ itemMetadata: deepParseJson(data.experimentItemMetadata),+ },+ }+ : {}),+ };+ }, [includeExperimentVariables, previewData.data]);++ return (+ <div className="bg-muted/20 min-w-0 rounded-md border">+ <div className="flex items-center justify-between gap-3 border-b px-3 py-2">+ <span className="text-muted-foreground text-xs font-medium">+ Evaluator input+ </span>+ </div>+ <PrettyJsonView+ json={inputPreviewJson}+ currentView="pretty"+ isLoading={false}+ showNullValues={true}+ stickyTopLevelKey={false}+ showObservationTypeBadge={false}+ scrollable={true}+ className="max-h-[40dvh] [&_.border]:border-0 [&_.rounded-sm]:rounded-none"+ />+ </div>+ );+}++function CodeEvalTestRunResultView({+ result,+ onShowExecutionTrace,+}: {+ result: Exclude<CodeEvalTestRunResult, undefined>;+ onShowExecutionTrace?: (executionTraceId: string) => void;+}) {+ const resultJson = result.success+ ? { scores: result.result.scores.map(toUserFacingCodeEvalScore) }+ : { error: result.error };++ return (+ <div className="flex min-w-0 flex-col gap-3">+ <div className="flex items-center justify-between gap-3">+ <Badge variant={result.success ? "success" : "error"} className="w-fit">+ {result.success ? "Success" : "Failed"}+ </Badge>+ {onShowExecutionTrace ? (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={() => onShowExecutionTrace(result.executionTraceId)}+ >+ <ListTree className="mr-1.5 h-3.5 w-3.5" />+ Show execution trace+ </Button>+ ) : null}+ </div>+ <CodeMirrorEditor+ value={JSON.stringify(resultJson, null, 2)}+ editable={false}+ mode="json"+ minHeight={220}+ maxHeight="50dvh"+ className="bg-muted/20 [&_.cm-content]:cursor-default"+ />+ </div>+ );+}++function toUserFacingCodeEvalScore(+ score: CodeEvalTestRunScore,+): Record<string, unknown> {+ const { dataType, value, ...scoreFields } = score;+ const userFacingScore: Record<string, unknown> = {+ ...scoreFields,+ dataType,+ value:+ dataType === "BOOLEAN" && typeof value === "number" ? value === 1 : value,+ };++ return userFacingScore;+}diff --git a/web/src/features/evals/components/eval-template-type-selector.tsx b/web/src/features/evals/components/eval-template-type-selector.tsxnew file mode 100644index 0000000000..f4795ce8d8--- /dev/null+++ b/web/src/features/evals/components/eval-template-type-selector.tsx@@ -0,0 +1,132 @@+import { type UseFormReturn } from "react-hook-form";+import { type z } from "zod";+import {+ EvalTemplateSourceCodeLanguage,+ EvalTemplateType,+} from "@langfuse/shared";++import {+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/src/components/ui/form";+import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";+import { type templateFormSchema } from "@/src/features/evals/utils/template-form-schema";+import {+ type CodeEvalSourceCodeLanguage,+ getDefaultCodeEvalSource,+ isDefaultCodeEvalSource,+} from "@/src/features/evals/utils/code-eval-template-validation";++type EvalTemplateFormInput = z.input<typeof templateFormSchema>;+type EvalTemplateFormOutput = z.output<typeof templateFormSchema>;+type EvalTemplateFormReturn = UseFormReturn<+ EvalTemplateFormInput,+ unknown,+ EvalTemplateFormOutput+>;++export type EvalTemplateTypeSelectorMode = "all" | "code-only" | "hidden";++export function EvalTemplateTypeSelector({+ form,+ enabled,+ mode,+ hasExistingTemplate,+ onChange,+}: {+ form: EvalTemplateFormReturn;+ enabled: boolean;+ mode: EvalTemplateTypeSelectorMode;+ hasExistingTemplate: boolean;+ onChange?: () => void;+}) {+ const evalTemplateType = form.watch("type");+ const sourceCodeLanguage =+ form.watch("sourceCodeLanguage") ??+ EvalTemplateSourceCodeLanguage.TYPESCRIPT;+ const shouldShow = enabled && !hasExistingTemplate && mode !== "hidden";++ if (!shouldShow) return null;++ const selectedValue =+ evalTemplateType === EvalTemplateType.CODE+ ? sourceCodeLanguage+ : EvalTemplateType.LLM_AS_JUDGE;++ const handleTemplateTypeSelection = (+ nextValue:+ | typeof EvalTemplateType.LLM_AS_JUDGE+ | CodeEvalSourceCodeLanguage,+ ) => {+ if (nextValue === EvalTemplateType.LLM_AS_JUDGE) {+ form.setValue("type", EvalTemplateType.LLM_AS_JUDGE);+ onChange?.();+ return;+ }++ const currentSourceCode = form.getValues("sourceCode") ?? "";+ const shouldReplaceSourceCode =+ currentSourceCode.trim().length === 0 ||+ isDefaultCodeEvalSource(currentSourceCode);++ form.setValue("type", EvalTemplateType.CODE);+ form.setValue("sourceCodeLanguage", nextValue);++ if (shouldReplaceSourceCode) {+ form.setValue("sourceCode", getDefaultCodeEvalSource(nextValue));+ }++ onChange?.();+ };++ return (+ <FormField+ control={form.control}+ name="type"+ render={() => (+ <FormItem>+ <FormLabel>Type</FormLabel>+ <FormControl>+ <Tabs+ value={selectedValue}+ onValueChange={(value) =>+ handleTemplateTypeSelection(+ value as+ | typeof EvalTemplateType.LLM_AS_JUDGE+ | CodeEvalSourceCodeLanguage,+ )+ }+ >+ <TabsList className="grid w-fit max-w-fit grid-flow-col gap-4">+ {mode === "all" ? (+ <TabsTrigger+ value={EvalTemplateType.LLM_AS_JUDGE}+ className="min-w-[100px]"+ >+ LLM-as-judge+ </TabsTrigger>+ ) : null}+ <TabsTrigger+ value={EvalTemplateSourceCodeLanguage.TYPESCRIPT}+ className="min-w-[100px]"+ >+ TypeScript+ </TabsTrigger>+ <TabsTrigger+ value={EvalTemplateSourceCodeLanguage.PYTHON}+ className="min-w-[100px]"+ >+ Python+ </TabsTrigger>+ </TabsList>+ </Tabs>+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ );+}diff --git a/web/src/features/evals/components/eval-templates-table.tsx b/web/src/features/evals/components/eval-templates-table.tsxindex 9fbe0b6baa..901ebf65ea 100644--- a/web/src/features/evals/components/eval-templates-table.tsx+++ b/web/src/features/evals/components/eval-templates-table.tsx@@ -38,7 +38,17 @@ import { useEntitlementLimit } from "@/src/features/entitlements/hooks";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { Badge } from "@/src/components/ui/badge";import { getTemplateResultType } from "@/src/features/evals/utils/template-output";-import { type EvalTemplate } from "@langfuse/shared";+import {+ EvalTemplateSourceCodeLanguage,+ EvalTemplateType,+ type EvalTemplate,+} from "@langfuse/shared";+import { useIsCodeEvalEnabled } from "@/src/features/evals/hooks/useIsCodeEvalEnabled";+import {+ CODE_EVAL_ESCAPE_CONFIRM_MESSAGE,+ shouldShowEvalTemplate,+} from "@/src/features/evals/utils/code-eval-template-utils";+import { SiPython, SiTypescript } from "react-icons/si";export type EvalsTemplateRow = {name: string;@@ -51,11 +61,53 @@ export type EvalsTemplateRow = {actions?: string;provider?: string;model?: string;+ type?: EvalTemplateType;+ sourceCodeLanguage?: EvalTemplate["sourceCodeLanguage"];};const getMaintainerLabel = (maintainer: string) =>maintainer.replace(/ maintained$/, "");+const getCodeEvalLanguageLabel = (+ sourceCodeLanguage?: EvalTemplate["sourceCodeLanguage"],+) =>+ sourceCodeLanguage === EvalTemplateSourceCodeLanguage.PYTHON+ ? "Python"+ : sourceCodeLanguage === EvalTemplateSourceCodeLanguage.TYPESCRIPT+ ? "TypeScript"+ : "Code";++const TemplateTypeBadge = ({+ type,+ sourceCodeLanguage,+}: {+ type?: EvalTemplateType;+ sourceCodeLanguage?: EvalTemplate["sourceCodeLanguage"];+}) => {+ if (type === EvalTemplateType.CODE) {+ const label = getCodeEvalLanguageLabel(sourceCodeLanguage);+ const Icon =+ sourceCodeLanguage === EvalTemplateSourceCodeLanguage.PYTHON+ ? SiPython+ : sourceCodeLanguage === EvalTemplateSourceCodeLanguage.TYPESCRIPT+ ? SiTypescript+ : null;++ return (+ <Badge className="w-fit gap-1.5" variant="outline-solid">+ {Icon ? <Icon className="h-3 w-3" aria-hidden="true" /> : null}+ {label}+ </Badge>+ );+ }++ return (+ <Badge className="w-fit gap-1.5" variant="outline-solid">+ LLM-as-judge+ </Badge>+ );+};+const templateTableRowHeights: CustomHeights = {s: "h-8",m: "h-8",@@ -68,6 +120,7 @@ export default function EvalsTemplateTable({projectId: string;}) {const router = useRouter();+ const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();const { setDetailPageList } = useDetailPageLists();const [paginationState, setPaginationState] = usePaginationState(0, 50, {page: "pageIndex",@@ -162,11 +215,15 @@ export default function EvalsTemplateTable({const { templates: templateList = [] } = templates.data ?? {};setDetailPageList("eval-templates",- templateList.map((template) => ({ id: template.latestId })),+ templateList+ .filter((template) =>+ shouldShowEvalTemplate(template, isCodeEvalEnabled),+ )+ .map((template) => ({ id: template.latestId })),);}// eslint-disable-next-line react-hooks/exhaustive-deps- }, [templates.isSuccess, templates.data]);+ }, [templates.isSuccess, templates.data, isCodeEvalEnabled]);const columnHelper = createColumnHelper<EvalsTemplateRow>();@@ -179,6 +236,17 @@ export default function EvalsTemplateTable({return name ? <TableIdOrName value={name} /> : undefined;},}),+ columnHelper.accessor("type", {+ id: "type",+ header: "Type",+ size: 120,+ cell: ({ row }) => (+ <TemplateTypeBadge+ type={row.original.type}+ sourceCodeLanguage={row.original.sourceCodeLanguage}+ />+ ),+ }),columnHelper.accessor("resultType", {id: "resultType",header: "Score Result Type",@@ -253,7 +321,10 @@ export default function EvalsTemplateTable({const id = row.original.id;const provider = row.original.provider ?? null;const model = row.original.model ?? null;- const isInvalid = isTemplateInvalid({ provider, model });+ const type = row.original.type;+ const isInvalid = isTemplateInvalid({ provider, model, type });+ const isCodeTemplate = type === EvalTemplateType.CODE;+ const isUserMaintained = row.original.maintainer.includes("User");return (<div className="flex flex-row gap-2">@@ -281,7 +352,7 @@ export default function EvalsTemplateTable({>Use Evaluator</ActionButton>- {!row.original.maintainer.includes("User") ? (+ {!isUserMaintained && !isCodeTemplate ? (<Buttonaria-label="clone"variant="outline"@@ -295,7 +366,8 @@ export default function EvalsTemplateTable({><Copy className="h-3 w-3" /></Button>- ) : (+ ) : null}+ {isUserMaintained ? (<Buttonaria-label="edit"variant="outline"@@ -309,7 +381,7 @@ export default function EvalsTemplateTable({><Pen className="h-3 w-3" /></Button>- )}+ ) : null}</div>);},@@ -347,7 +419,10 @@ export default function EvalsTemplateTable({): EvalsTemplateRow => {return {name: template.name,- resultType: getTemplateResultType(template.outputDefinition),+ resultType:+ template.type === EvalTemplateType.CODE+ ? "Code-defined"+ : getTemplateResultType(template.outputDefinition),maintainer: getMaintainer(template),latestCreatedAt: template.latestCreatedAt,latestVersion: template.version,@@ -355,6 +430,8 @@ export default function EvalsTemplateTable({usageCount: template.usageCount,provider: template.provider,model: template.model,+ type: template.type,+ sourceCodeLanguage: template.sourceCodeLanguage,};};@@ -393,9 +470,11 @@ export default function EvalsTemplateTable({: {isLoading: false,isError: false,- data: safeExtract(templates.data, "templates", []).map(- (t) => convertToTableRow(t),- ),+ data: safeExtract(templates.data, "templates", [])+ .filter((template) =>+ shouldShowEvalTemplate(template, isCodeEvalEnabled),+ )+ .map((t) => convertToTableRow(t)),}}pagination={{@@ -417,7 +496,14 @@ export default function EvalsTemplateTable({if (!open) setEditTemplateId(null);}}>- <DialogContent className="max-h-[90vh] max-w-(--breakpoint-md) overflow-y-auto">+ <DialogContent+ className="max-h-[90vh] max-w-(--breakpoint-md) overflow-y-auto"+ confirmCloseOnEscape={+ template.data?.type === EvalTemplateType.CODE+ ? CODE_EVAL_ESCAPE_CONFIRM_MESSAGE+ : undefined+ }+ ><DialogHeader><DialogTitle>Edit evaluator</DialogTitle></DialogHeader>@@ -447,7 +533,14 @@ export default function EvalsTemplateTable({}}}>- <DialogContent className="max-h-[90vh] max-w-(--breakpoint-md) overflow-y-auto">+ <DialogContent+ className="max-h-[90vh] max-w-(--breakpoint-md) overflow-y-auto"+ confirmCloseOnEscape={+ cloneTemplate.data?.type === EvalTemplateType.CODE+ ? CODE_EVAL_ESCAPE_CONFIRM_MESSAGE+ : undefined+ }+ ><DialogHeader><DialogTitle>Clone evaluator</DialogTitle></DialogHeader>@@ -464,6 +557,7 @@ export default function EvalsTemplateTable({vars: cloneTemplate.data.vars,outputDefinition: cloneTemplate.data.outputDefinition as EvalTemplate["outputDefinition"],+ type: cloneTemplate.data.type,provider: cloneTemplate.data.provider,model: cloneTemplate.data.model,modelParams: cloneTemplate.data.modelParams as any,diff --git a/web/src/features/evals/components/evaluation-prompt-preview.tsx b/web/src/features/evals/components/evaluation-prompt-preview.tsxindex 436c96e0a5..46a08c7e2b 100644--- a/web/src/features/evals/components/evaluation-prompt-preview.tsx+++ b/web/src/features/evals/components/evaluation-prompt-preview.tsx@@ -100,7 +100,7 @@ const ColoredPromptView = ({fragment.content) : (<ColoredVariable- value={fragment.value || ""}+ value={fragment.value ?? ""}index={fragment.colorIndex || 0}/>)}@@ -173,7 +173,7 @@ export const EvaluationPromptPreview = ({// Add variableconst variableName = match[1];const variableValue =- extractedVariables.find((v) => v.variable === variableName)?.value ||+ extractedVariables.find((v) => v.variable === variableName)?.value ??"";fragments.push({diff --git a/web/src/features/evals/components/evaluator-form.tsx b/web/src/features/evals/components/evaluator-form.tsxindex 34eb9db4dd..fe9ce0d992 100644--- a/web/src/features/evals/components/evaluator-form.tsx+++ b/web/src/features/evals/components/evaluator-form.tsx@@ -3,6 +3,11 @@ import { InnerEvaluatorForm } from "@/src/features/evals/components/inner-evaluaimport { type PartialConfig } from "@/src/features/evals/types";import { useEvalCapabilities } from "@/src/features/evals/hooks/useEvalCapabilities";import { Skeleton } from "@/src/components/ui/skeleton";+import { useIsCodeEvalEnabled } from "@/src/features/evals/hooks/useIsCodeEvalEnabled";+import {+ isCodeEvalTemplate,+ shouldShowEvalTemplate,+} from "@/src/features/evals/utils/code-eval-template-utils";export const EvaluatorForm = (props: {projectId: string;@@ -22,13 +27,23 @@ export const EvaluatorForm = (props: {hidePreviewTable?: boolean;defaultTarget?: EvalTargetObject;}) => {- const evalCapabilities = useEvalCapabilities(props.projectId);+ const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();const currentTemplate =props.existingEvaluator?.evalTemplate ??- props.evalTemplates.find((t) => t.id === props.templateId);+ props.evalTemplates+ .filter((template) => shouldShowEvalTemplate(template, isCodeEvalEnabled))+ .find((t) => t.id === props.templateId);- if (!currentTemplate) {+ const evalCapabilities = useEvalCapabilities(props.projectId, {+ isCodeEvalTemplate:+ !!currentTemplate && isCodeEvalTemplate(currentTemplate),+ });++ if (+ !currentTemplate ||+ (isCodeEvalTemplate(currentTemplate) && !isCodeEvalEnabled)+ ) {return null;}diff --git a/web/src/features/evals/components/evaluator-selector.tsx b/web/src/features/evals/components/evaluator-selector.tsxindex 1c834270ab..1117d89522 100644--- a/web/src/features/evals/components/evaluator-selector.tsx+++ b/web/src/features/evals/components/evaluator-selector.tsx@@ -1,4 +1,8 @@-import { type EvalTemplate } from "@langfuse/shared";+import {+ EvalTemplateSourceCodeLanguage,+ EvalTemplateType,+ type EvalTemplate,+} from "@langfuse/shared";import {AlertCircle,CheckIcon,@@ -25,6 +29,73 @@ import { useSingleTemplateValidation } from "@/src/features/evals/hooks/useSinglimport { getMaintainer } from "@/src/features/evals/utils/typeHelpers";import { MaintainerTooltip } from "@/src/features/evals/components/maintainer-tooltip";import Link from "next/link";+import { useIsCodeEvalEnabled } from "@/src/features/evals/hooks/useIsCodeEvalEnabled";+import { shouldShowEvalTemplate } from "@/src/features/evals/utils/code-eval-template-utils";+import { SiPython, SiTypescript } from "react-icons/si";++const CodeTemplateLanguageIcon = ({+ sourceCodeLanguage,+}: {+ sourceCodeLanguage: EvalTemplate["sourceCodeLanguage"];+}) => {+ const language =+ sourceCodeLanguage === EvalTemplateSourceCodeLanguage.TYPESCRIPT+ ? { Icon: SiTypescript, title: "TypeScript" }+ : sourceCodeLanguage === EvalTemplateSourceCodeLanguage.PYTHON+ ? { Icon: SiPython, title: "Python" }+ : null;++ if (!language) return null;++ const { Icon } = language;++ return (+ <span+ title={language.title}+ aria-label={language.title}+ className="text-muted-foreground ml-1 inline-flex shrink-0"+ >+ <Icon className="h-3.5 w-3.5" aria-hidden="true" />+ </span>+ );+};++const getCodeTemplateLanguageTitle = (+ sourceCodeLanguage: EvalTemplate["sourceCodeLanguage"],+) =>+ sourceCodeLanguage === EvalTemplateSourceCodeLanguage.PYTHON+ ? "Python"+ : sourceCodeLanguage === EvalTemplateSourceCodeLanguage.TYPESCRIPT+ ? "TypeScript"+ : "Code";++const TemplatePreviewTooltipContent = ({+ template,+}: {+ template: EvalTemplate;+}) => {+ if (template.type === EvalTemplateType.CODE) {+ return (+ <>+ <p className="mb-1 font-medium">+ {getCodeTemplateLanguageTitle(template.sourceCodeLanguage)} source+ </p>+ <pre className="text-muted-foreground text-xs wrap-break-word whitespace-pre-wrap">+ {template.sourceCode}+ </pre>+ </>+ );+ }++ return (+ <>+ <p className="mb-1 font-medium">Evaluation prompt</p>+ <pre className="text-muted-foreground text-xs wrap-break-word whitespace-pre-wrap">+ {template.prompt}+ </pre>+ </>+ );+};interface EvaluatorSelectorProps {projectId: string;@@ -35,7 +106,6 @@ interface EvaluatorSelectorProps {name: string,version?: number,) => void;- onCreateNew?: () => void;}export function EvaluatorSelector({@@ -43,12 +113,15 @@ export function EvaluatorSelector({evalTemplates,selectedTemplateId,onTemplateSelect,- onCreateNew,}: EvaluatorSelectorProps) {const [search, setSearch] = useState("");+ const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();+ const visibleEvalTemplates = evalTemplates.filter((template) =>+ shouldShowEvalTemplate(template, isCodeEvalEnabled),+ );// Group templates by name and whether they are managed by Langfuse- const groupedTemplates = evalTemplates.reduce(+ const groupedTemplates = visibleEvalTemplates.reduce((acc, template) => {const group = template.projectId ? "custom" : "langfuse";if (!acc[group][template.name]) {@@ -139,16 +212,24 @@ export function EvaluatorSelector({><Tooltip><TooltipTrigger asChild>- <span>{name}</span>+ <div className="flex min-w-0 items-center">+ <span className="truncate">{name}</span>+ {latestVersion.type === EvalTemplateType.CODE ? (+ <CodeTemplateLanguageIcon+ sourceCodeLanguage={+ latestVersion.sourceCodeLanguage+ }+ />+ ) : null}+ </div></TooltipTrigger><TooltipContentside="right"className="max-h-[300px] max-w-[400px] overflow-y-auto">- <p className="mb-1 font-medium">Evaluation prompt</p>- <pre className="text-muted-foreground text-xs wrap-break-word whitespace-pre-wrap">- {latestVersion.prompt}- </pre>+ <TemplatePreviewTooltipContent+ template={latestVersion}+ /></TooltipContent></Tooltip>{isInvalid && (@@ -230,16 +311,24 @@ export function EvaluatorSelector({><Tooltip><TooltipTrigger asChild>- <div className="mr-1">{name}</div>+ <div className="mr-1 flex min-w-0 items-center">+ <span className="truncate">{name}</span>+ {latestVersion.type === EvalTemplateType.CODE ? (+ <CodeTemplateLanguageIcon+ sourceCodeLanguage={+ latestVersion.sourceCodeLanguage+ }+ />+ ) : null}+ </div></TooltipTrigger><TooltipContentside="right"className="max-h-[300px] max-w-[400px] overflow-y-auto">- <p className="mb-1 font-medium">Evaluation prompt</p>- <pre className="text-muted-foreground text-xs wrap-break-word whitespace-pre-wrap">- {latestVersion.prompt}- </pre>+ <TemplatePreviewTooltipContent+ template={latestVersion}+ /></TooltipContent></Tooltip><MaintainerTooltip@@ -296,18 +385,6 @@ export function EvaluatorSelector({</InputCommandGroup></>)}-- {onCreateNew && (- <>- <InputCommandSeparator alwaysRender />- <InputCommandGroup forceMount>- <InputCommandItem onSelect={onCreateNew}>- Create custom evaluator- <ExternalLink className="ml-auto h-4 w-4" />- </InputCommandItem>- </InputCommandGroup>- </>- )}</InputCommandList></InputCommand>);diff --git a/web/src/features/evals/components/inner-evaluator-form.tsx b/web/src/features/evals/components/inner-evaluator-form.tsxindex 4110004835..13c51dbad0 100644--- a/web/src/features/evals/components/inner-evaluator-form.tsx+++ b/web/src/features/evals/components/inner-evaluator-form.tsx@@ -36,6 +36,7 @@ import {} from "@/src/features/filters/components/filter-builder";import {type EvalTemplate,+ EvalTemplateSourceCodeLanguage,variableMapping,observationVariableMapping,} from "@langfuse/shared";@@ -86,7 +87,9 @@ import {FlaskConical,InfoIcon,ListTree,+ ExternalLink,} from "lucide-react";+import Link from "next/link";import {isDatasetTarget,isEventTarget,@@ -106,6 +109,15 @@ import {import { useEvalConfigFilterOptions } from "@/src/features/evals/hooks/useEvalConfigFilterOptions";import { VariableMappingCard } from "@/src/features/evals/components/variable-mapping-card";import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";+import { useIsCodeEvalEnabled } from "@/src/features/evals/hooks/useIsCodeEvalEnabled";+import {+ getCodeEvalVariableMapping,+ isCodeEvalTemplate,+ resolveCodeEvalTarget,+} from "@/src/features/evals/utils/code-eval-template-utils";+import { CodeEvalTestRunCard } from "@/src/features/evals/components/code-eval-test-run-card";+import { getExperimentEvalPreviewFilters } from "@/src/features/evals/utils/experiment-eval-preview-utils";+import { cn } from "@/src/utils/tailwind";/*** Adds propagation warnings to columns that require OTEL SDK with span propagation@@ -290,6 +302,58 @@ const ObservationsPreview = memo(ObservationsPreview.displayName = "ObservationsPreview";+function getCodeEvalSourceLanguageLabel(+ sourceCodeLanguage: EvalTemplate["sourceCodeLanguage"],+) {+ return sourceCodeLanguage === EvalTemplateSourceCodeLanguage.PYTHON+ ? "Python"+ : "TypeScript";+}++function CodeEvalSourceLink({+ projectId,+ evalTemplate,+}: {+ projectId: string;+ evalTemplate: EvalTemplate;+}) {+ const sourceCodeLanguage =+ evalTemplate.sourceCodeLanguage ??+ EvalTemplateSourceCodeLanguage.TYPESCRIPT;+ const languageLabel = getCodeEvalSourceLanguageLabel(sourceCodeLanguage);++ const editButton = evalTemplate.projectId ? (+ <Button asChild variant="outline">+ <Link+ href={`/project/${projectId}/evals/templates/${evalTemplate.id}?mode=edit`}+ target="_blank"+ rel="noopener noreferrer"+ >+ Edit source code+ <ExternalLink className="ml-1 h-3.5 w-3.5" />+ </Link>+ </Button>+ ) : (+ <Button+ variant="outline"+ disabled+ title="Only user-managed templates can be edited"+ >+ Edit source code+ <ExternalLink className="ml-1 h-3.5 w-3.5" />+ </Button>+ );++ return (+ <div className="bg-muted/20 flex max-w-[500px] items-center justify-between gap-3 rounded-md border px-3 py-2">+ <span className="text-muted-foreground text-sm">{languageLabel}</span>+ {editButton}+ </div>+ );+}++const EMPTY_FILTER_STATE: z.infer<typeof singleFilter>[] = [];+export const InnerEvaluatorForm = (props: {projectId: string;evalTemplate: EvalTemplate;@@ -318,6 +382,10 @@ export const InnerEvaluatorForm = (props: {const capture = usePostHogClientCapture();const router = useRouter();const [showTraceConfirmDialog, setShowTraceConfirmDialog] = useState(false);+ const { isBetaEnabled } = useV4Beta();+ const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();+ const isCodeEvalConfig =+ isCodeEvalEnabled && isCodeEvalTemplate(props.evalTemplate);// Destructure eval capabilities passed from parentconst { allowLegacy, allowPropagationFilters } = props.evalCapabilities;@@ -359,9 +427,41 @@ export const InnerEvaluatorForm = (props: {props.defaultTarget ??EvalTargetObject.EVENT,);- const defaultTarget = defaultTargetResult.success+ const parsedDefaultTarget = defaultTargetResult.success? defaultTargetResult.data: EvalTargetObject.EVENT;+ const defaultTarget = isCodeEvalConfig+ ? resolveCodeEvalTarget(parsedDefaultTarget)+ : parsedDefaultTarget;++ const getDefaultMapping = () => {+ if (isCodeEvalConfig) {+ return getCodeEvalVariableMapping();+ }++ if (props.existingEvaluator?.variableMapping) {+ return isEventTarget(props.existingEvaluator.targetObject) ||+ isExperimentTarget(props.existingEvaluator.targetObject)+ ? z+ .array(observationVariableMapping)+ .parse(props.existingEvaluator.variableMapping)+ : z+ .array(variableMapping)+ .parse(props.existingEvaluator.variableMapping);+ }++ return z.array(variableMapping).parse(+ props.evalTemplate+ ? props.evalTemplate.vars.map((v) => ({+ templateVariable: v,+ langfuseObject: "trace" as const,+ objectName: null,+ selectedColumnId: "input",+ jsonSelector: null,+ }))+ : [],+ );+ };const form = useForm({resolver: zodResolver(evalConfigFormSchema),@@ -379,26 +479,7 @@ export const InnerEvaluatorForm = (props: {? // For new observation evaluators, default to GENERATION typeDEFAULT_OBSERVATION_FILTER: [],- mapping: props.existingEvaluator?.variableMapping- ? isEventTarget(props.existingEvaluator.targetObject) ||- isExperimentTarget(props.existingEvaluator.targetObject)- ? z- .array(observationVariableMapping)- .parse(props.existingEvaluator.variableMapping)- : z- .array(variableMapping)- .parse(props.existingEvaluator.variableMapping)- : z.array(variableMapping).parse(- props.evalTemplate- ? props.evalTemplate.vars.map((v) => ({- templateVariable: v,- langfuseObject: "trace" as const,- objectName: null,- selectedColumnId: "input",- jsonSelector: null,- }))- : [],- ),+ mapping: getDefaultMapping(),sampling: props.existingEvaluator?.sampling? props.existingEvaluator.sampling.toNumber(): 1,@@ -417,12 +498,13 @@ export const InnerEvaluatorForm = (props: {const currentMapping = form.watch("mapping") ?? [];const syncStatus = useVariableMappingSync({- templateVars: props.evalTemplate?.vars,+ templateVars: isCodeEvalConfig ? [] : props.evalTemplate?.vars,currentMapping: currentMapping,});useEffect(() => {if (!props.evalTemplate) return;+ if (isCodeEvalConfig) return;const mapping = form.getValues("mapping");@@ -471,6 +553,7 @@ export const InnerEvaluatorForm = (props: {props.disabled,props.existingEvaluator,syncStatus,+ isCodeEvalConfig,]);const utils = api.useUtils();@@ -497,6 +580,19 @@ export const InnerEvaluatorForm = (props: {);const watchedTarget = form.watch("target");+ const watchedScoreName = form.watch("scoreName");+ const watchedFilter = form.watch("filter") ?? EMPTY_FILTER_STATE;+ const shouldShowExperimentEventsPreview =+ isExperimentTarget(watchedTarget) && isBetaEnabled;+ const shouldShowEventsPreview =+ isEventTarget(watchedTarget) || shouldShowExperimentEventsPreview;+ const eventsPreviewFilterState = useMemo(+ () =>+ shouldShowExperimentEventsPreview+ ? getExperimentEvalPreviewFilters(watchedFilter)+ : watchedFilter,+ [shouldShowExperimentEventsPreview, watchedFilter],+ );// Clear mapping error if user switches away from trace targetuseEffect(() => {@@ -550,8 +646,21 @@ export const InnerEvaluatorForm = (props: {return;}+ if (+ isCodeEvalConfig &&+ !isEventTarget(values.target) &&+ !isExperimentTarget(values.target)+ ) {+ form.setError("target", {+ type: "manual",+ message: "Code evaluators can only run on observations or experiments.",+ });+ return;+ }+// Block NEW trace-level evals that target observationsif (+ !isCodeEvalConfig &&props.mode !== "edit" &&isTraceTarget(values.target) &&values.mapping.some(@@ -566,10 +675,15 @@ export const InnerEvaluatorForm = (props: {return;}- const validatedVarMapping = validateAndTransformVariableMapping(- values.mapping,- values.target as EvalTargetObject,- );+ const validatedVarMapping = isCodeEvalConfig+ ? {+ success: true as const,+ data: getCodeEvalVariableMapping(),+ }+ : validateAndTransformVariableMapping(+ values.mapping,+ values.target as EvalTargetObject,+ );if (!validatedVarMapping.success) {form.setError("mapping", {@@ -671,18 +785,19 @@ export const InnerEvaluatorForm = (props: {} else if (newUserFacingTarget === "event") {actualTarget = EvalTargetObject.EVENT;} else {- // offline-experiment: only use EXPERIMENT if beta is enabled AND OTEL is selected- actualTarget = useOtelDataForExperiment+ // offline-experiment: code evaluators always use the observation-backed experiment target+ actualTarget = isCodeEvalConfig? EvalTargetObject.EXPERIMENT- : EvalTargetObject.DATASET;+ : useOtelDataForExperiment+ ? EvalTargetObject.EXPERIMENT+ : EvalTargetObject.DATASET;}// Transform variable mapping for new target typeconst currentMapping = form.getValues("mapping");- const newMapping = targetState.transformMapping(- currentMapping,- actualTarget,- );+ const newMapping = isCodeEvalConfig+ ? getCodeEvalVariableMapping()+ : targetState.transformMapping(currentMapping, actualTarget);// Update form state with target-appropriate default filtersform.setValue(@@ -699,21 +814,40 @@ export const InnerEvaluatorForm = (props: {return actualTarget;}+ const shouldShowCodeEvalTestPanel =+ isCodeEvalConfig &&+ !props.disabled &&+ (isEventTarget(watchedTarget) ||+ (isExperimentTarget(watchedTarget) && isBetaEnabled));+ const shouldShowCodeEvalSourceLinkInSettingsCard =+ isCodeEvalConfig &&+ !props.disabled &&+ isExperimentTarget(watchedTarget) &&+ !isBetaEnabled;+const formBody = (- <div className="grid gap-4">- <FormField- control={form.control}- name="scoreName"- render={({ field }) => (- <FormItem>- <FormLabel>Generated Score Name</FormLabel>- <FormControl>- <Input {...field} />- </FormControl>- <FormMessage />- </FormItem>- )}- />+ <div+ className={cn(+ "grid gap-4",+ shouldShowCodeEvalTestPanel &&+ "xl:grid-cols-[minmax(0,2fr)_minmax(320px,1fr)] xl:items-start",+ )}+ >+ <div className={cn(shouldShowCodeEvalTestPanel && "xl:col-span-2")}>+ <FormField+ control={form.control}+ name="scoreName"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Generated Score Name</FormLabel>+ <FormControl>+ <Input {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>{!props.hideTargetSection && (<Card className="flex max-w-full flex-col gap-2 overflow-y-auto p-4">{hasInvalidTraceFilters && (@@ -1136,14 +1270,14 @@ export const InnerEvaluatorForm = (props: {{isTraceTarget(form.watch("target")) && (<TracesPreviewprojectId={props.projectId}- filterState={form.watch("filter") ?? []}+ filterState={watchedFilter}/>)}- {isEventTarget(form.watch("target")) && (+ {shouldShowEventsPreview && (<ObservationsPreviewprojectId={props.projectId}- filterState={form.watch("filter") ?? []}+ filterState={eventsPreviewFilterState}isNewCompatible={props.evalCapabilities.isNewCompatible}compatibilityCheckWasPerformed={props.evalCapabilities.compatibilityCheckWasPerformed@@ -1203,25 +1337,42 @@ export const InnerEvaluatorForm = (props: {)}</>)}+ {shouldShowCodeEvalSourceLinkInSettingsCard ? (+ <CodeEvalSourceLink+ projectId={props.projectId}+ evalTemplate={props.evalTemplate}+ />+ ) : null}</>)}</div></Card>)}- <VariableMappingCard- projectId={props.projectId}- availableVariables={availableVariables}- evalTemplate={props.evalTemplate}- form={form}- disabled={props.disabled}- shouldWrapVariables={props.shouldWrapVariables}- hideAdvancedSettings={props.hideAdvancedSettings}- oldConfigId={props.oldConfigId}- isNewCompatible={props.evalCapabilities.isNewCompatible}- compatibilityCheckWasPerformed={- props.evalCapabilities.compatibilityCheckWasPerformed- }- />+ {shouldShowCodeEvalTestPanel ? (+ <CodeEvalTestRunCard+ projectId={props.projectId}+ evalTemplate={props.evalTemplate}+ target={watchedTarget}+ scoreName={watchedScoreName}+ disabled={props.disabled}+ enableExecutionTracePeek={!props.existingEvaluator}+ />+ ) : isCodeEvalConfig ? null : (+ <VariableMappingCard+ projectId={props.projectId}+ availableVariables={availableVariables}+ evalTemplate={props.evalTemplate}+ form={form}+ disabled={props.disabled}+ shouldWrapVariables={props.shouldWrapVariables}+ hideAdvancedSettings={props.hideAdvancedSettings}+ oldConfigId={props.oldConfigId}+ isNewCompatible={props.evalCapabilities.isNewCompatible}+ compatibilityCheckWasPerformed={+ props.evalCapabilities.compatibilityCheckWasPerformed+ }+ />+ )}</div>);diff --git a/web/src/features/evals/components/select-evaluator-list.tsx b/web/src/features/evals/components/select-evaluator-list.tsxindex 18b6635d7a..996236972f 100644--- a/web/src/features/evals/components/select-evaluator-list.tsx+++ b/web/src/features/evals/components/select-evaluator-list.tsx@@ -8,7 +8,7 @@ import {DialogTitle,} from "@/src/components/ui/dialog";import { Button } from "@/src/components/ui/button";-import { PlusIcon } from "lucide-react";+import { BrainCircuit, Code2 } from "lucide-react";import { EvaluatorSelector } from "./evaluator-selector";import { EvalTemplateForm } from "./template-form";import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";@@ -16,7 +16,14 @@ import { SetupDefaultEvalModelCard } from "@/src/features/evals/components/set-uimport { useTemplateValidation } from "@/src/features/evals/hooks/useTemplateValidation";import { Card } from "@/src/components/ui/card";import { Skeleton } from "@/src/components/ui/skeleton";-import { type EvalTemplate } from "@langfuse/shared";+import {+ EvalTemplateSourceCodeLanguage,+ EvalTemplateType,+ type EvalTemplate,+} from "@langfuse/shared";+import { getDefaultCodeEvalSource } from "@/src/features/evals/utils/code-eval-template-starter-examples";+import { useIsCodeEvalEnabled } from "@/src/features/evals/hooks/useIsCodeEvalEnabled";+import { CODE_EVAL_ESCAPE_CONFIRM_MESSAGE } from "@/src/features/evals/utils/code-eval-template-utils";type SelectEvaluatorListProps = {projectId: string;@@ -25,6 +32,10 @@ type SelectEvaluatorListProps = {export function SelectEvaluatorList({ projectId }: SelectEvaluatorListProps) {const router = useRouter();const [isCreateTemplateOpen, setIsCreateTemplateOpen] = useState(false);+ const [customEvaluatorType, setCustomEvaluatorType] = useState<+ typeof EvalTemplateType.LLM_AS_JUDGE | typeof EvalTemplateType.CODE | null+ >(null);+ const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();const handleSelectEvaluator = (template: EvalTemplate) => {router.push(`/project/${projectId}/evals/new?evaluator=${template.id}`);@@ -48,7 +59,10 @@ export function SelectEvaluatorList({ projectId }: SelectEvaluatorListProps) {const utils = api.useUtils();- const handleOpenCreateEvaluator = () => {+ const handleOpenCreateEvaluator = (+ type: typeof EvalTemplateType.LLM_AS_JUDGE | typeof EvalTemplateType.CODE,+ ) => {+ setCustomEvaluatorType(type);setIsCreateTemplateOpen(true);};@@ -61,63 +75,131 @@ export function SelectEvaluatorList({ projectId }: SelectEvaluatorListProps) {return (<>- <Card className="grid max-h-[90vh] grid-rows-[auto_1fr_auto] overflow-hidden p-3">- <div className="flex flex-col overflow-hidden">- {templates.isLoading ? (- <Skeleton className="h-full w-full" />- ) : templates.isError ? (- <div className="text-destructive py-8 text-center">- Error: {templates.error.message}- </div>- ) : templates.data?.templates.length === 0 ? (- <div className="text-muted-foreground py-8 text-center">- No evaluators found. Create a new evaluator to get started.- </div>- ) : (- <div className="flex-1 overflow-hidden">- <EvaluatorSelector- projectId={projectId}- evalTemplates={templates.data?.templates || []}- selectedTemplateId={selectedTemplate?.id || undefined}- onTemplateSelect={(templateId) =>- handleTemplateSelect(templateId)- }- />- </div>- )}+ <div className="mb-4 flex max-h-full min-h-0 flex-col gap-5">+ <div className="shrink-0 space-y-2">+ <h2 className="text-base font-semibold">Create from scratch</h2>+ <div className="flex flex-wrap gap-3">+ {isCodeEvalEnabled ? (+ <Button+ type="button"+ variant="outline"+ className="h-auto min-h-24 w-full justify-start gap-3 px-4 py-4 text-left whitespace-normal sm:w-[360px]"+ onClick={() => handleOpenCreateEvaluator(EvalTemplateType.CODE)}+ >+ <Code2 className="h-5 w-5 shrink-0" />+ <span className="flex flex-col gap-1">+ <span className="font-medium">Code evaluator</span>+ <span className="text-muted-foreground text-sm font-normal">+ Run TypeScript or Python logic to create Langfuse scores.+ </span>+ </span>+ </Button>+ ) : null}+ <Button+ type="button"+ variant="outline"+ className="h-auto min-h-24 w-full justify-start gap-3 px-4 py-4 text-left whitespace-normal sm:w-[360px]"+ onClick={() =>+ handleOpenCreateEvaluator(EvalTemplateType.LLM_AS_JUDGE)+ }+ >+ <BrainCircuit className="h-5 w-5 shrink-0" />+ <span className="flex flex-col gap-1">+ <span className="font-medium">LLM as a judge evaluator</span>+ <span className="text-muted-foreground text-sm font-normal">+ Use a prompt and model to score traces or observations.+ </span>+ </span>+ </Button>+ </div></div>- {!isSelectionValid && (- <div className="px-4">- <SetupDefaultEvalModelCard projectId={projectId} />- </div>- )}- </Card>+ <div className="flex max-h-full min-h-0 flex-col gap-2">+ <h2 className="shrink-0 text-base font-semibold">Use existing</h2>+ <Card className="grid max-h-full min-h-0 grid-rows-[minmax(0,1fr)_auto] overflow-y-auto p-3">+ <div className="flex min-h-0 flex-col overflow-hidden">+ {templates.isLoading ? (+ <Skeleton className="h-full w-full" />+ ) : templates.isError ? (+ <div className="text-destructive py-8 text-center">+ Error: {templates.error.message}+ </div>+ ) : templates.data?.templates.length === 0 ? (+ <div className="text-muted-foreground py-8 text-center">+ No evaluators found. Create a new evaluator to get started.+ </div>+ ) : (+ <div className="flex-1 overflow-hidden">+ <EvaluatorSelector+ projectId={projectId}+ evalTemplates={templates.data?.templates || []}+ selectedTemplateId={selectedTemplate?.id || undefined}+ onTemplateSelect={(templateId) =>+ handleTemplateSelect(templateId)+ }+ />+ </div>+ )}+ </div>- <div className="mt-2 flex flex-row justify-end">- <div className="flex justify-end gap-2">- <Button onClick={handleOpenCreateEvaluator}>- <PlusIcon className="mr-2 h-4 w-4" />- Create Custom Evaluator- </Button>+ {!isSelectionValid && (+ <div className="px-4">+ <SetupDefaultEvalModelCard projectId={projectId} />+ </div>+ )}+ </Card></div></div><Dialogopen={isCreateTemplateOpen}- onOpenChange={setIsCreateTemplateOpen}+ onOpenChange={(open) => {+ setIsCreateTemplateOpen(open);+ if (!open) {+ setCustomEvaluatorType(null);+ }+ }}>- <DialogContent className="max-h-[90vh] max-w-(--breakpoint-md) overflow-y-auto">+ <DialogContent+ className="max-h-[90vh] max-w-(--breakpoint-md) overflow-y-auto"+ confirmCloseOnEscape={+ customEvaluatorType === EvalTemplateType.CODE+ ? CODE_EVAL_ESCAPE_CONFIRM_MESSAGE+ : undefined+ }+ ><DialogHeader><DialogTitle>Create new evaluator</DialogTitle></DialogHeader><EvalTemplateForm+ key={customEvaluatorType ?? "custom-evaluator"}projectId={projectId}preventRedirect={true}isEditing={true}useDialog={true}+ templateTypeSelectorMode={+ customEvaluatorType === EvalTemplateType.CODE+ ? "code-only"+ : "hidden"+ }+ preFilledFormValues={{+ name: "",+ type: customEvaluatorType ?? EvalTemplateType.LLM_AS_JUDGE,+ prompt: "",+ vars: [],+ ...(customEvaluatorType === EvalTemplateType.CODE+ ? {+ sourceCode: getDefaultCodeEvalSource(+ EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ ),+ sourceCodeLanguage:+ EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ }+ : {}),+ }}onFormSuccess={(newTemplate) => {setIsCreateTemplateOpen(false);+ setCustomEvaluatorType(null);void utils.evals.allTemplates.invalidate();if (newTemplate) {setSelectedTemplate(newTemplate);diff --git a/web/src/features/evals/components/template-form.tsx b/web/src/features/evals/components/template-form.tsxindex 7471b0a7c7..b046f6d6d6 100644--- a/web/src/features/evals/components/template-form.tsx+++ b/web/src/features/evals/components/template-form.tsx@@ -18,9 +18,6 @@ import {createBooleanEvalOutputDefinition,createCategoricalEvalOutputDefinition,createNumericEvalOutputDefinition,- EvalOutputDataTypeSchema,- getCategoricalCategoryRuleViolations,- getMinimumCategoricalCategoriesMessage,MinimumCategoricalCategoryCount,type PersistedEvalOutputDefinition,PersistedEvalOutputDefinitionSchema,@@ -28,6 +25,8 @@ import {extractVariables,getIsCharOrUnderscore,resolvePersistedEvalOutputDefinition,+ EvalTemplateType,+ EvalTemplateSourceCodeLanguage,} from "@langfuse/shared";import router from "next/router";import { type EvalTemplate } from "@langfuse/shared";@@ -43,6 +42,7 @@ import {getDefaultOutputDefinitionFormValues,shouldReplaceDefaultOutputDefinitionField,} from "@/src/features/evals/utils/template-form-defaults";+import { templateFormSchema } from "@/src/features/evals/utils/template-form-schema";import { CodeMirrorEditor } from "@/src/components/editor";import { Card, CardContent } from "@/src/components/ui/card";import { type RouterInput } from "@/src/utils/types";@@ -50,7 +50,7 @@ import { useEvaluationModel } from "@/src/features/evals/hooks/useEvaluationModeimport { Checkbox } from "@/src/components/ui/checkbox";import { ManageDefaultEvalModel } from "@/src/features/evals/components/manage-default-eval-model";import { DialogFooter, DialogBody } from "@/src/components/ui/dialog";-import { AlertCircle, PlusIcon, Trash } from "lucide-react";+import { AlertCircle, AlertTriangle, PlusIcon, Trash } from "lucide-react";import { useValidateCustomModel } from "@/src/features/evals/hooks/useValidateCustomModel";import {Select,@@ -59,16 +59,34 @@ import {SelectTrigger,SelectValue,} from "@/src/components/ui/select";+import { useIsCodeEvalEnabled } from "@/src/features/evals/hooks/useIsCodeEvalEnabled";+import { CodeEvalTemplateFormBody } from "@/src/features/evals/components/code-eval-template-form-body";+import {+ type CodeEvalSourceCodeLanguage,+ getCodeEvalSourceForEditor,+ getDefaultCodeEvalSource,+ formatAndStripCodeEvalSourceForSubmit,+} from "@/src/features/evals/utils/code-eval-template-validation";+import { useCodeEvalSourceValidation } from "@/src/features/evals/hooks/useCodeEvalSourceValidation";+import {+ EvalTemplateTypeSelector,+ type EvalTemplateTypeSelectorMode,+} from "@/src/features/evals/components/eval-template-type-selector";+import { Alert, AlertDescription } from "@/src/components/ui/alert";+import {+ useEvalCapabilities,+ type EvalCapabilities,+} from "@/src/features/evals/hooks/useEvalCapabilities";-type PartialEvalTemplate = Omit<- EvalTemplate,- "id" | "version" | "createdAt" | "updatedAt"-> & { id?: string };+type PartialEvalTemplate = Partial<EvalTemplate> &+ Pick<EvalTemplate, "name" | "prompt" | "vars" | "outputDefinition">;export const EvalTemplateForm = (props: {projectId: string;useDialog: boolean;existingEvalTemplate?: PartialEvalTemplate;+ preFilledFormValues?: EvalTemplateFormPreFill;+ templateTypeSelectorMode?: EvalTemplateTypeSelectorMode;onFormSuccess?: (template?: EvalTemplate) => void;onBeforeSubmit?: (template: RouterInput["evals"]["createTemplate"],@@ -79,7 +97,7 @@ export const EvalTemplateForm = (props: {cloneSourceId?: string | null;}) => {return (- <div className="max-w-6xl">+ <div className={props.useDialog ? "max-w-6xl" : "w-full"}><InnerEvalTemplateFormkey={props.existingEvalTemplate?.id ?? "new"}{...props}@@ -93,10 +111,14 @@ export const EvalTemplateForm = (props: {props.existingEvalTemplate? {name: props.existingEvalTemplate.name,- prompt: props.existingEvalTemplate.prompt,+ prompt: props.existingEvalTemplate.prompt ?? "",vars: props.existingEvalTemplate.vars,outputDefinition: props.existingEvalTemplate.outputDefinition as PersistedEvalOutputDefinition,+ type: props.existingEvalTemplate.type,+ sourceCode: props.existingEvalTemplate.sourceCode,+ sourceCodeLanguage:+ props.existingEvalTemplate.sourceCodeLanguage ?? undefined,selectedModel: props.existingEvalTemplate.provider? {provider: props.existingEvalTemplate.provider as string,@@ -108,7 +130,7 @@ export const EvalTemplateForm = (props: {}: undefined,}- : undefined+ : props.preFilledFormValues}/></div>@@ -121,71 +143,8 @@ const selectedModelSchema = z.object({modelParams: ZodModelConfig,});-const categoricalOptionSchema = z.object({- value: z.string().trim().min(1, "Enter a category value"),-});--const formSchema = z- .object({- name: z.string().min(1, "Enter a name"),- prompt: z- .string()- .min(1, "Enter a prompt")- .refine((val) => {- const variables = extractVariables(val);- const matches = variables.map((variable) => {- // check regex here- if (variable.match(/^[A-Za-z_]+$/)) {- return true;- }- return false;- });- return !matches.includes(false);- }, "Variables must only contain letters and underscores (_)"),-- variables: z.array(- z.string().min(1, "Variables must have at least one character"),- ),- scoreDataType: EvalOutputDataTypeSchema.default(ScoreDataTypeEnum.NUMERIC),- scoreDescription: z.string().min(1, "Enter a score function"),- reasoningDescription: z.string().min(1, "Enter a reasoning function"),- categories: z.array(categoricalOptionSchema).default([]),- shouldAllowMultipleMatches: z.boolean().default(false),- referencedEvaluators: z- .enum(EvalReferencedEvaluators)- .optional()- .default(EvalReferencedEvaluators.PERSIST),- shouldUseDefaultModel: z.boolean().default(true),- })- .superRefine((value, ctx) => {- if (value.scoreDataType !== ScoreDataTypeEnum.CATEGORICAL) {- return;- }-- getCategoricalCategoryRuleViolations(- value.categories.map((category) => category.value),- ).forEach((violation) => {- switch (violation.type) {- case "minimum_count":- ctx.addIssue({- code: "custom",- message: getMinimumCategoricalCategoriesMessage(),- path: ["categories"],- });- return;- case "duplicate_value":- ctx.addIssue({- code: "custom",- message: "Categories must be unique",- path: ["categories", violation.index, "value"],- });- return;- }- });- });-const toOutputDefinitionFormValues = (- outputDefinition?: PersistedEvalOutputDefinition,+ outputDefinition?: PersistedEvalOutputDefinition | null,) => {if (!outputDefinition) {return getDefaultOutputDefinitionFormValues();@@ -214,9 +173,12 @@ const toOutputDefinitionFormValues = (export type EvalTemplateFormPreFill = {name: string;+ type?: EvalTemplateType;prompt: string;vars: string[];- outputDefinition: PersistedEvalOutputDefinition;+ outputDefinition?: PersistedEvalOutputDefinition | null;+ sourceCode?: string | null;+ sourceCodeLanguage?: CodeEvalSourceCodeLanguage | null;selectedModel?: {provider: string;model: string;@@ -231,6 +193,7 @@ export const InnerEvalTemplateForm = (props: {useDialog: boolean;// pre-filled values from langfuse-defined template or template from dbpreFilledFormValues?: EvalTemplateFormPreFill;+ templateTypeSelectorMode?: EvalTemplateTypeSelectorMode;// template to be updatedexistingEvalTemplateId?: string;existingEvalTemplateName?: string;@@ -243,6 +206,8 @@ export const InnerEvalTemplateForm = (props: {}) => {const capture = usePostHogClientCapture();const [formError, setFormError] = useState<string | null>(null);+ const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();+ const templateTypeSelectorMode = props.templateTypeSelectorMode ?? "all";// Determine if we should use default model or custom model// If existing template has no provider, it was using default model@@ -281,17 +246,31 @@ export const InnerEvalTemplateForm = (props: {const outputDefinitionFormValues = toOutputDefinitionFormValues(props.preFilledFormValues?.outputDefinition,);+ const defaultSourceCodeLanguage =+ props.preFilledFormValues?.sourceCodeLanguage ??+ EvalTemplateSourceCodeLanguage.TYPESCRIPT;// updates the form based on the pre-filled data// either form update or from langfuse-generated templateconst form = useForm({- resolver: zodResolver(formSchema),+ resolver: zodResolver(templateFormSchema),disabled: !props.isEditing,defaultValues: {name:props.existingEvalTemplateName ?? props.preFilledFormValues?.name ?? "",+ type:+ templateTypeSelectorMode === "code-only"+ ? EvalTemplateType.CODE+ : (props.preFilledFormValues?.type ?? EvalTemplateType.LLM_AS_JUDGE),prompt: props.preFilledFormValues?.prompt ?? undefined,variables: props.preFilledFormValues?.vars ?? [],+ sourceCode: props.preFilledFormValues?.sourceCode+ ? getCodeEvalSourceForEditor({+ sourceCode: props.preFilledFormValues.sourceCode,+ sourceCodeLanguage: defaultSourceCodeLanguage,+ })+ : getDefaultCodeEvalSource(defaultSourceCodeLanguage),+ sourceCodeLanguage: defaultSourceCodeLanguage,scoreDataType: outputDefinitionFormValues.scoreDataType,reasoningDescription: outputDefinitionFormValues.reasoningDescription,scoreDescription: outputDefinitionFormValues.scoreDescription,@@ -313,6 +292,26 @@ export const InnerEvalTemplateForm = (props: {});const useDefaultModel = form.watch("shouldUseDefaultModel");+ const evalTemplateType = form.watch("type");+ const sourceCodeLanguage =+ form.watch("sourceCodeLanguage") ??+ EvalTemplateSourceCodeLanguage.TYPESCRIPT;+ const sourceCode = form.watch("sourceCode") ?? "";+ const showCodeTemplateForm =+ isCodeEvalEnabled && evalTemplateType === EvalTemplateType.CODE;+ const evalCapabilities = useEvalCapabilities(props.projectId, {+ isCodeEvalTemplate: showCodeTemplateForm,+ });+ const {+ isValid: isCodeEvalSourceValid,+ validationResult: codeValidationResult,+ validate: validateCodeEvalSource,+ reset: resetCodeEvalSourceValidation,+ } = useCodeEvalSourceValidation({+ enabled: showCodeTemplateForm,+ sourceCode,+ sourceCodeLanguage,+ });const scoreDataType = form.watch("scoreDataType");const isCategoricalOutput = scoreDataType === ScoreDataTypeEnum.CATEGORICAL;const isBooleanOutput = scoreDataType === ScoreDataTypeEnum.BOOLEAN;@@ -353,8 +352,9 @@ export const InnerEvalTemplateForm = (props: {}};- const extractedVariables = form.watch("prompt")- ? extractVariables(form.watch("prompt")).filter(getIsCharOrUnderscore)+ const promptValue = form.watch("prompt");+ const extractedVariables = promptValue+ ? extractVariables(promptValue).filter(getIsCharOrUnderscore): undefined;const utils = api.useUtils();@@ -398,35 +398,99 @@ export const InnerEvalTemplateForm = (props: {}}, [evaluatorsByTemplateNameQuery.data, form]);- function onSubmit(values: z.infer<typeof formSchema>) {+ async function submitEvalTemplate(+ evalTemplate: RouterInput["evals"]["createTemplate"],+ ) {+ // Check if we need to perform any pre-submission validation or confirmation+ if (props.onBeforeSubmit && !props.onBeforeSubmit(evalTemplate)) {+ return; // Stop submission - the parent will handle it+ }++ await createEvalTemplateMutation+ .mutateAsync(evalTemplate)+ .then((res) => {+ props.onFormSuccess?.(res);+ form.reset();+ props.setIsEditing?.(false);+ if (props.preventRedirect) {+ return;+ }+ void router.push(+ `/project/${props.projectId}/evals/templates/${res.id}`,+ );+ })+ .catch((error) => {+ if ("message" in error && typeof error.message === "string") {+ setFormError(error.message as string);+ return;+ } else {+ setFormError(JSON.stringify(error));+ console.error(error);+ }+ });+ }++ async function onSubmit(values: z.infer<typeof templateFormSchema>) {capture(props.isEditing? "eval_templates:update_form_submit": "eval_templates:new_form_submit",);+ if (values.type === EvalTemplateType.CODE) {+ const submittedSourceCodeLanguage =+ values.sourceCodeLanguage ?? EvalTemplateSourceCodeLanguage.TYPESCRIPT;+ const isValidSource = await validateCodeEvalSource({+ sourceCode: values.sourceCode ?? "",+ sourceCodeLanguage: submittedSourceCodeLanguage,+ });++ if (!isValidSource) {+ return;+ }++ const formattedSourceCode = await formatAndStripCodeEvalSourceForSubmit({+ sourceCode: values.sourceCode ?? "",+ sourceCodeLanguage: submittedSourceCodeLanguage,+ });++ const evalTemplate = {+ type: EvalTemplateType.CODE,+ name: values.name,+ projectId: props.projectId,+ sourceCode: formattedSourceCode,+ sourceCodeLanguage: submittedSourceCodeLanguage,+ referencedEvaluators: values.referencedEvaluators,+ cloneSourceId: props.cloneSourceId ?? undefined,+ } satisfies RouterInput["evals"]["createTemplate"];++ await submitEvalTemplate(evalTemplate);+ return;+ }+const outputDefinition =values.scoreDataType === ScoreDataTypeEnum.CATEGORICAL? createCategoricalEvalOutputDefinition({- scoreDescription: values.scoreDescription,- reasoningDescription: values.reasoningDescription,+ scoreDescription: values.scoreDescription ?? "",+ reasoningDescription: values.reasoningDescription ?? "",categories: values.categories.map((category) => category.value),shouldAllowMultipleMatches: values.shouldAllowMultipleMatches,}): values.scoreDataType === ScoreDataTypeEnum.BOOLEAN? createBooleanEvalOutputDefinition({- scoreDescription: values.scoreDescription,- reasoningDescription: values.reasoningDescription,+ scoreDescription: values.scoreDescription ?? "",+ reasoningDescription: values.reasoningDescription ?? "",}): createNumericEvalOutputDefinition({- scoreDescription: values.scoreDescription,- reasoningDescription: values.reasoningDescription,+ scoreDescription: values.scoreDescription ?? "",+ reasoningDescription: values.reasoningDescription ?? "",});const evalTemplate = {+ type: EvalTemplateType.LLM_AS_JUDGE,name: values.name,projectId: props.projectId,- prompt: values.prompt,+ prompt: values.prompt ?? "",// Only include model details if not using default modelprovider: values.shouldUseDefaultModel? undefined@@ -438,8 +502,8 @@ export const InnerEvalTemplateForm = (props: {vars: extractedVariables ?? [],outputDefinition,referencedEvaluators: values.referencedEvaluators,- sourceTemplateId: props.cloneSourceId ?? undefined,- };+ cloneSourceId: props.cloneSourceId ?? undefined,+ } satisfies RouterInput["evals"]["createTemplate"];// Only validate model if not using defaultif (!values.shouldUseDefaultModel) {@@ -464,33 +528,7 @@ export const InnerEvalTemplateForm = (props: {}}- // Check if we need to perform any pre-submission validation or confirmation- if (props.onBeforeSubmit && !props.onBeforeSubmit(evalTemplate)) {- return; // Stop submission - the parent will handle it- }-- createEvalTemplateMutation- .mutateAsync(evalTemplate)- .then((res) => {- props.onFormSuccess?.(res);- form.reset();- props.setIsEditing?.(false);- if (props.preventRedirect) {- return;- }- void router.push(- `/project/${props.projectId}/evals/templates/${res.id}`,- );- })- .catch((error) => {- if ("message" in error && typeof error.message === "string") {- setFormError(error.message as string);- return;- } else {- setFormError(JSON.stringify(error));- console.error(error);- }- });+ await submitEvalTemplate(evalTemplate);}const formBody = (@@ -506,7 +544,7 @@ export const InnerEvalTemplateForm = (props: {<FormItem><FormLabel>Name</FormLabel><FormControl>- <Input {...field} placeholder="Select a template name" />+ <Input {...field} placeholder="Select a name" /></FormControl><FormMessage /></FormItem>@@ -518,337 +556,380 @@ export const InnerEvalTemplateForm = (props: {</>) : undefined}- {/* Model Selection Section */}- <Card>- <CardContent>- <p className="my-2 font-semibold">Model</p>+ <EvalTemplateTypeSelector+ form={form}+ enabled={isCodeEvalEnabled}+ mode={templateTypeSelectorMode}+ hasExistingTemplate={Boolean(props.existingEvalTemplateId)}+ onChange={() => {+ resetCodeEvalSourceValidation();+ setFormError(null);+ }}+ />++ {showCodeTemplateForm ? (+ <div className="space-y-3">+ {props.isEditing ? (+ <CodeEvalSdkVersionCallout evalCapabilities={evalCapabilities} />+ ) : null}<FormFieldcontrol={form.control}- name="shouldUseDefaultModel"+ name="sourceCode"render={({ field }) => (- <FormItem className="mt-3 flex flex-row items-center space-y-0 space-x-3">- <FormControl>- <Checkbox- checked={field.value}- onCheckedChange={field.onChange}- disabled={!props.isEditing}- />- </FormControl>- <div className="space-y-0 leading-none">- <FormLabel>Use default evaluation model</FormLabel>- <FormDescription className="text-xs">- <ManageDefaultEvalModel- projectId={props.projectId}- variant="color-coded"- setUpMessage={- <>- No default model set. LLM-as-a-judge evaluations- require an LLM connection for scoring. This default is- used by all templates that don't specify their- own model.{" "}- <a- href="https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge#how-llm-as-a-judge-works"- target="_blank"- rel="noopener noreferrer"- className="underline"- >- Learn more.- </a>- </>- }- className="text-sm font-normal"- />- </FormDescription>- </div>- </FormItem>+ <CodeEvalTemplateFormBody+ sourceCode={field.value ?? ""}+ sourceCodeLanguage={sourceCodeLanguage}+ onSourceCodeChange={(value) => {+ field.onChange(value);+ setFormError(null);+ }}+ editable={Boolean(props.isEditing)}+ validationResult={codeValidationResult}+ />)}/>- {/* Only show model parameters if using custom model */}- {!useDefaultModel &&- (!props.isEditing && !isCustomModelValid ? (- <div className="text-destructive mt-2 flex items-center space-x-1 text-sm">- <AlertCircle className="h-4 w-4" />- <p>- This evaluator is configured to use{" "}- {modelParams.provider.value}s models but no API key exists.- Add a key or choose another provider.- </p>+ </div>+ ) : (+ <>+ {/* Model Selection Section */}+ <Card>+ <CardContent>+ <p className="my-2 font-semibold">Model</p>+ <FormField+ control={form.control}+ name="shouldUseDefaultModel"+ render={({ field }) => (+ <FormItem className="mt-3 flex flex-row items-center space-y-0 space-x-3">+ <FormControl>+ <Checkbox+ checked={field.value}+ onCheckedChange={field.onChange}+ disabled={!props.isEditing}+ />+ </FormControl>+ <div className="space-y-0 leading-none">+ <FormLabel>Use default evaluation model</FormLabel>+ <FormDescription className="text-xs">+ <ManageDefaultEvalModel+ projectId={props.projectId}+ variant="color-coded"+ setUpMessage={+ <>+ No default model set. LLM-as-a-judge evaluations+ require an LLM connection for scoring. This+ default is used by all templates that don't+ specify their own model.{" "}+ <a+ href="https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge#how-llm-as-a-judge-works"+ target="_blank"+ rel="noopener noreferrer"+ className="underline"+ >+ Learn more.+ </a>+ </>+ }+ className="text-sm font-normal"+ />+ </FormDescription>+ </div>+ </FormItem>+ )}+ />+ {/* Only show model parameters if using custom model */}+ {!useDefaultModel &&+ (!props.isEditing && !isCustomModelValid ? (+ <div className="text-destructive mt-2 flex items-center space-x-1 text-sm">+ <AlertCircle className="h-4 w-4" />+ <p>+ This evaluator is configured to use{" "}+ {modelParams.provider.value}s models but no API key+ exists. Add a key or choose another provider.+ </p>+ </div>+ ) : (+ <ModelParameters+ customHeader={+ <p className="text-sm leading-none font-medium">+ Custom model configuration+ </p>+ }+ {...{+ modelParams,+ availableModels,+ providerModelCombinations,+ availableProviders,+ updateModelParamValue: updateModelParamValue,+ setModelParamEnabled,+ modelParamsDescription:+ "Select a model which supports function calling.",+ }}+ formDisabled={!props.isEditing}+ />+ ))}+ </CardContent>+ </Card>++ <Card>+ <CardContent className="space-y-6">+ <div className="space-y-2">+ <p className="my-2 font-semibold">Prompt</p>+ <FormField+ control={form.control}+ name="prompt"+ render={({ field }) => (+ <>+ <FormItem>+ <FormLabel>Evaluation prompt</FormLabel>+ <FormDescription>+ Define your llm-as-a-judge evaluation template. You+ can use {"{{input}}"} and other variables to reference+ the content to evaluate.+ </FormDescription>+ <FormControl>+ <CodeMirrorEditor+ value={field.value ?? ""}+ onChange={field.onChange}+ editable={props.isEditing}+ mode="prompt"+ minHeight={200}+ maxHeight="50dvh"+ />+ </FormControl>+ <FormMessage />+ <PromptVariableListPreview+ variables={extractedVariables ?? []}+ />+ </FormItem>+ </>+ )}+ /></div>- ) : (- <ModelParameters- customHeader={- <p className="text-sm leading-none font-medium">- Custom model configuration- </p>- }- {...{- modelParams,- availableModels,- providerModelCombinations,- availableProviders,- updateModelParamValue: updateModelParamValue,- setModelParamEnabled,- modelParamsDescription:- "Select a model which supports function calling.",- }}- formDisabled={!props.isEditing}++ <FormField+ control={form.control}+ name="scoreDataType"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Score type</FormLabel>+ <FormDescription>+ Choose whether the evaluator should return a numeric+ score, a boolean verdict, or one of a fixed set of+ categories.+ </FormDescription>+ <Select+ value={field.value}+ disabled={!props.isEditing}+ onValueChange={(value) => {+ const nextScoreDataType = value as+ | typeof ScoreDataTypeEnum.NUMERIC+ | typeof ScoreDataTypeEnum.BOOLEAN+ | typeof ScoreDataTypeEnum.CATEGORICAL;+ const shouldEnableMultipleMatches =+ nextScoreDataType === ScoreDataTypeEnum.CATEGORICAL+ ? form.getValues("shouldAllowMultipleMatches")+ : false;++ field.onChange(nextScoreDataType);++ if (+ nextScoreDataType === ScoreDataTypeEnum.CATEGORICAL &&+ (form.getValues("categories") ?? []).length === 0+ ) {+ replace(+ Array.from(+ { length: MinimumCategoricalCategoryCount },+ () => ({ value: "" }),+ ),+ );+ }++ if (+ nextScoreDataType !== ScoreDataTypeEnum.CATEGORICAL+ ) {+ form.setValue("shouldAllowMultipleMatches", false);+ }++ applyDefaultOutputDefinitionCopy({+ scoreDataType: nextScoreDataType,+ shouldAllowMultipleMatches:+ shouldEnableMultipleMatches ?? false,+ });+ }}+ >+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select a score type" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ <SelectItem value={ScoreDataTypeEnum.NUMERIC}>+ Numeric+ </SelectItem>+ <SelectItem value={ScoreDataTypeEnum.BOOLEAN}>+ Boolean+ </SelectItem>+ <SelectItem value={ScoreDataTypeEnum.CATEGORICAL}>+ Categorical+ </SelectItem>+ </SelectContent>+ </Select>+ <FormMessage />+ </FormItem>+ )}/>- ))}- </CardContent>- </Card>-- <Card>- <CardContent className="space-y-6">- <div className="space-y-2">- <p className="my-2 font-semibold">Prompt</p>- <FormField- control={form.control}- name="prompt"- render={({ field }) => (- <>++ {isCategoricalOutput ? (+ <FormField+ control={form.control}+ name="categories"+ render={() => (+ <FormItem>+ <div>+ <FormLabel>Categories</FormLabel>+ <FormDescription>+ Add the allowed category values the model may return.+ Categories must be exhaustive. If you need a catch-all+ outcome (e.g. 'No match'), add it explicitly+ as one of the categories.+ </FormDescription>+ </div>+ <div className="space-y-3">+ {categoryFields.map((field, index) => (+ <div+ key={field.id}+ className="grid gap-3 rounded-md border p-3 md:grid-cols-[minmax(0,1fr)_auto]"+ >+ <FormField+ control={form.control}+ name={`categories.${index}.value`}+ render={({ field }) => (+ <FormItem>+ <FormLabel className="text-muted-foreground text-xs">+ Category+ </FormLabel>+ <FormControl>+ <Input {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <div className="flex items-end">+ <Button+ type="button"+ variant="ghost"+ size="icon"+ disabled={!props.isEditing}+ onClick={() => remove(index)}+ >+ <Trash className="text-muted-foreground h-4 w-4" />+ </Button>+ </div>+ </div>+ ))}+ </div>+ <Button+ type="button"+ variant="outline"+ className="text-muted-foreground"+ disabled={!props.isEditing}+ onClick={() => append({ value: "" })}+ >+ <PlusIcon className="mr-1.5 h-4 w-4" />+ Add category+ </Button>+ <FormField+ control={form.control}+ name="shouldAllowMultipleMatches"+ render={({ field }) => (+ <FormItem className="mt-3 flex flex-row items-center space-y-0 space-x-3">+ <FormControl>+ <Checkbox+ checked={field.value}+ onCheckedChange={(checked) => {+ field.onChange(checked);+ applyDefaultOutputDefinitionCopy({+ scoreDataType:+ ScoreDataTypeEnum.CATEGORICAL,+ shouldAllowMultipleMatches:+ Boolean(checked),+ });+ }}+ disabled={!props.isEditing}+ />+ </FormControl>+ <div className="space-y-0.5 leading-none">+ <FormLabel>Allow multiple matches</FormLabel>+ <FormDescription>+ Lets the model return more than one category.+ One score will be created for each selected+ match.+ </FormDescription>+ </div>+ </FormItem>+ )}+ />+ {categoriesErrorMessage ? (+ <p className="text-destructive text-sm font-medium">+ {categoriesErrorMessage}+ </p>+ ) : null}+ </FormItem>+ )}+ />+ ) : null}+ <FormField+ control={form.control}+ name="reasoningDescription"+ render={({ field }) => (<FormItem>- <FormLabel>Evaluation prompt</FormLabel>+ <FormLabel>Score reasoning prompt</FormLabel><FormDescription>- Define your llm-as-a-judge evaluation template. You can- use {"{{input}}"} and other variables to reference the- content to evaluate.+ Define how the LLM should explain its evaluation. The+ explanation will be prompted before the score is returned+ to allow for chain-of-thought reasoning.</FormDescription><FormControl>- <CodeMirrorEditor- value={field.value}- onChange={field.onChange}- editable={props.isEditing}- mode="prompt"- minHeight={200}- maxHeight="50dvh"- />+ <Input {...field} /></FormControl><FormMessage />- <PromptVariableListPreview- variables={extractedVariables ?? []}- /></FormItem>- </>- )}- />- </div>-- <FormField- control={form.control}- name="scoreDataType"- render={({ field }) => (- <FormItem>- <FormLabel>Score type</FormLabel>- <FormDescription>- Choose whether the evaluator should return a numeric score, a- boolean verdict, or one of a fixed set of categories.- </FormDescription>- <Select- value={field.value}- disabled={!props.isEditing}- onValueChange={(value) => {- const nextScoreDataType = value as- | typeof ScoreDataTypeEnum.NUMERIC- | typeof ScoreDataTypeEnum.BOOLEAN- | typeof ScoreDataTypeEnum.CATEGORICAL;- const shouldEnableMultipleMatches =- nextScoreDataType === ScoreDataTypeEnum.CATEGORICAL- ? form.getValues("shouldAllowMultipleMatches")- : false;-- field.onChange(nextScoreDataType);-- if (- nextScoreDataType === ScoreDataTypeEnum.CATEGORICAL &&- (form.getValues("categories") ?? []).length === 0- ) {- replace(- Array.from(- { length: MinimumCategoricalCategoryCount },- () => ({ value: "" }),- ),- );- }-- if (nextScoreDataType !== ScoreDataTypeEnum.CATEGORICAL) {- form.setValue("shouldAllowMultipleMatches", false);- }-- applyDefaultOutputDefinitionCopy({- scoreDataType: nextScoreDataType,- shouldAllowMultipleMatches:- shouldEnableMultipleMatches ?? false,- });- }}- >- <FormControl>- <SelectTrigger>- <SelectValue placeholder="Select a score type" />- </SelectTrigger>- </FormControl>- <SelectContent>- <SelectItem value={ScoreDataTypeEnum.NUMERIC}>- Numeric- </SelectItem>- <SelectItem value={ScoreDataTypeEnum.BOOLEAN}>- Boolean- </SelectItem>- <SelectItem value={ScoreDataTypeEnum.CATEGORICAL}>- Categorical- </SelectItem>- </SelectContent>- </Select>- <FormMessage />- </FormItem>- )}- />+ )}+ />- {isCategoricalOutput ? (- <FormField- control={form.control}- name="categories"- render={() => (- <FormItem>- <div>- <FormLabel>Categories</FormLabel>+ <FormField+ control={form.control}+ name="scoreDescription"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ {isCategoricalOutput+ ? "Category selection prompt"+ : isBooleanOutput+ ? "Boolean verdict prompt"+ : "Score output prompt"}+ </FormLabel><FormDescription>- Add the allowed category values the model may return.- Categories must be exhaustive. If you need a catch-all- outcome (e.g. 'No match'), add it explicitly as- one of the categories.+ {isCategoricalOutput+ ? shouldAllowMultipleMatches+ ? "Define how the LLM should choose one or more categories from the list below."+ : "Define how the LLM should choose exactly one category from the list below."+ : isBooleanOutput+ ? "Define how the LLM should return either true or false based on the evaluation criteria."+ : "Define how the LLM should return the evaluation score in natural language. Needs to yield a numeric value."}</FormDescription>- </div>- <div className="space-y-3">- {categoryFields.map((field, index) => (- <div- key={field.id}- className="grid gap-3 rounded-md border p-3 md:grid-cols-[minmax(0,1fr)_auto]"- >- <FormField- control={form.control}- name={`categories.${index}.value`}- render={({ field }) => (- <FormItem>- <FormLabel className="text-muted-foreground text-xs">- Category- </FormLabel>- <FormControl>- <Input {...field} />- </FormControl>- <FormMessage />- </FormItem>- )}- />- <div className="flex items-end">- <Button- type="button"- variant="ghost"- size="icon"- disabled={!props.isEditing}- onClick={() => remove(index)}- >- <Trash className="text-muted-foreground h-4 w-4" />- </Button>- </div>- </div>- ))}- </div>- <Button- type="button"- variant="outline"- className="text-muted-foreground"- disabled={!props.isEditing}- onClick={() => append({ value: "" })}- >- <PlusIcon className="mr-1.5 h-4 w-4" />- Add category- </Button>- <FormField- control={form.control}- name="shouldAllowMultipleMatches"- render={({ field }) => (- <FormItem className="mt-3 flex flex-row items-center space-y-0 space-x-3">- <FormControl>- <Checkbox- checked={field.value}- onCheckedChange={(checked) => {- field.onChange(checked);- applyDefaultOutputDefinitionCopy({- scoreDataType: ScoreDataTypeEnum.CATEGORICAL,- shouldAllowMultipleMatches: Boolean(checked),- });- }}- disabled={!props.isEditing}- />- </FormControl>- <div className="space-y-0.5 leading-none">- <FormLabel>Allow multiple matches</FormLabel>- <FormDescription>- Lets the model return more than one category. One- score will be created for each selected match.- </FormDescription>- </div>- </FormItem>- )}- />- {categoriesErrorMessage ? (- <p className="text-destructive text-sm font-medium">- {categoriesErrorMessage}- </p>- ) : null}- </FormItem>- )}- />- ) : null}- <FormField- control={form.control}- name="reasoningDescription"- render={({ field }) => (- <FormItem>- <FormLabel>Score reasoning prompt</FormLabel>- <FormDescription>- Define how the LLM should explain its evaluation. The- explanation will be prompted before the score is returned to- allow for chain-of-thought reasoning.- </FormDescription>- <FormControl>- <Input {...field} />- </FormControl>- <FormMessage />- </FormItem>- )}- />-- <FormField- control={form.control}- name="scoreDescription"- render={({ field }) => (- <FormItem>- <FormLabel>- {isCategoricalOutput- ? "Category selection prompt"- : isBooleanOutput- ? "Boolean verdict prompt"- : "Score output prompt"}- </FormLabel>- <FormDescription>- {isCategoricalOutput- ? shouldAllowMultipleMatches- ? "Define how the LLM should choose one or more categories from the list below."- : "Define how the LLM should choose exactly one category from the list below."- : isBooleanOutput- ? "Define how the LLM should return either true or false based on the evaluation criteria."- : "Define how the LLM should return the evaluation score in natural language. Needs to yield a numeric value."}- </FormDescription>- <FormControl>- <Input {...field} />- </FormControl>- <FormMessage />- </FormItem>- )}- />- </CardContent>- </Card>+ <FormControl>+ <Input {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </CardContent>+ </Card>+ </>+ )}</>);@@ -858,6 +939,7 @@ export const InnerEvalTemplateForm = (props: {<Buttontype="submit"loading={createEvalTemplateMutation.isPending}+ disabled={showCodeTemplateForm && !isCodeEvalSourceValid}className="w-full">Save@@ -873,7 +955,10 @@ export const InnerEvalTemplateForm = (props: {return (<Form {...form}>- <form onSubmit={form.handleSubmit(onSubmit)} className="mt-2 space-y-4">+ <form+ onSubmit={form.handleSubmit(onSubmit)}+ className="mt-2 w-full space-y-4"+ >{props.useDialog ? <DialogBody>{formBody}</DialogBody> : formBody}{props.useDialog ? (@@ -885,3 +970,47 @@ export const InnerEvalTemplateForm = (props: {</Form>);};++function CodeEvalSdkVersionCallout({+ evalCapabilities,+}: {+ evalCapabilities: EvalCapabilities;+}) {+ if (+ evalCapabilities.isLoading ||+ !evalCapabilities.compatibilityCheckWasPerformed ||+ evalCapabilities.isNewCompatible+ ) {+ return null;+ }++ return (+ <Alert+ variant="default"+ className="border-dark-yellow bg-light-yellow max-w-4xl"+ >+ <AlertTriangle className="text-dark-yellow h-4 w-4" />+ <AlertDescription>+ <div className="flex flex-col gap-1">+ <span className="text-foreground font-medium">+ Please verify your SDK version+ </span>+ <span className="text-foreground text-sm">+ Code evaluators require JS SDK v4+ or Python SDK v3+. You can create+ this evaluator now, but it will only run once your project ingests+ data with a compatible SDK.{" "}+ <a+ href="https://langfuse.com/docs/observability/sdk/upgrade-path"+ target="_blank"+ rel="noopener noreferrer"+ className="text-dark-blue font-medium hover:opacity-80"+ >+ Learn more+ </a>+ .+ </span>+ </div>+ </AlertDescription>+ </Alert>+ );+}diff --git a/web/src/features/evals/components/template-selector.tsx b/web/src/features/evals/components/template-selector.tsxindex 7189599d9d..46c9e5e423 100644--- a/web/src/features/evals/components/template-selector.tsx+++ b/web/src/features/evals/components/template-selector.tsx@@ -38,6 +38,8 @@ import { useSingleTemplateValidation } from "@/src/features/evals/hooks/useSinglimport { getMaintainer } from "@/src/features/evals/utils/typeHelpers";import { MaintainerTooltip } from "@/src/features/evals/components/maintainer-tooltip";import { env } from "@/src/env.mjs";+import { useIsCodeEvalEnabled } from "@/src/features/evals/hooks/useIsCodeEvalEnabled";+import { shouldShowEvalTemplate } from "@/src/features/evals/utils/code-eval-template-utils";type TemplateSelectorProps = {projectId: string;@@ -68,6 +70,10 @@ export const TemplateSelector = ({}: TemplateSelectorProps) => {const [isPopoverOpen, setIsPopoverOpen] = useState(false);const [search, setSearch] = useState("");+ const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();+ const visibleEvalTemplates = evalTemplates.filter((template) =>+ shouldShowEvalTemplate(template, isCodeEvalEnabled),+ );const {activeTemplates,isTemplateActive,@@ -89,7 +95,7 @@ export const TemplateSelector = ({});// Group templates by name and whether they are managed by Langfuse- const groupedTemplates = evalTemplates.reduce(+ const groupedTemplates = visibleEvalTemplates.reduce((acc, template) => {const group = template.projectId ? "custom" : "langfuse";if (!acc[group][template.name]) {diff --git a/web/src/features/evals/components/variable-mapping-card.tsx b/web/src/features/evals/components/variable-mapping-card.tsxindex c98f8765a9..85b7c28c32 100644--- a/web/src/features/evals/components/variable-mapping-card.tsx+++ b/web/src/features/evals/components/variable-mapping-card.tsx@@ -29,10 +29,10 @@ import {import { Skeleton } from "@/src/components/ui/skeleton";import {isEventTarget,+ isExperimentTarget,isLegacyEvalTarget,isTraceTarget,isTraceOrDatasetObject,- isTraceOrEventTarget,} from "@/src/features/evals/utils/typeHelpers";import {FormControl,@@ -53,6 +53,13 @@ import { useVariableMappingSync } from "@/src/features/evals/hooks/useVariableMaimport { Button } from "@/src/components/ui/button";import Link from "next/link";import { useRouter } from "next/router";+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";+import {+ type EvalPreviewPointer,+ buildEvalPreviewNavigationPath,+ getEvalPreviewDetailPageListKey,+ getEvalPreviewPointerFromDetailPageEntry,+} from "@/src/features/evals/hooks/useEvalPreviewNavigation";export const VariableMappingCard = ({projectId,@@ -80,14 +87,18 @@ export const VariableMappingCard = ({compatibilityCheckWasPerformed?: boolean;}) => {const [showPreview, setShowPreview] = useState(false);- const [selectedPreviewIds, setSelectedPreviewIds] = useState<{- traceId?: string;- observationId?: string;- }>();+ const [selectedPreviewPointer, setSelectedPreviewPointer] =+ useState<EvalPreviewPointer>();const router = useRouter();+ const { isBetaEnabled } = useV4Beta();const peekId =typeof router.query.peek === "string" ? router.query.peek : undefined;const isPeekView = Boolean(peekId);+ const target = form.watch("target");+ const shouldShowPreviewForTarget =+ isTraceTarget(target) ||+ isEventTarget(target) ||+ (isExperimentTarget(target) && isBetaEnabled);const { fields } = useFieldArray({control: form.control,@@ -103,40 +114,50 @@ export const VariableMappingCard = ({projectId,form,disabled,- isPeekView ? (selectedPreviewIds ?? {}) : undefined,+ isPeekView ? selectedPreviewPointer : undefined,);const nonOtelCompatible = compatibilityCheckWasPerformed && !isNewCompatible;+ const shouldDisablePreviewForNonOtel =+ nonOtelCompatible && (isEventTarget(target) || isExperimentTarget(target));useEffect(() => {- const target = form.getValues("target");- // Disable preview for event targets only when SDK check was performed and user is not on OTEL SDK- const shouldDisableForNonOtel = isEventTarget(target) && nonOtelCompatible;-- if (isTraceOrEventTarget(target) && !disabled && !shouldDisableForNonOtel) {+ if (+ shouldShowPreviewForTarget &&+ !disabled &&+ !shouldDisablePreviewForNonOtel+ ) {setShowPreview(true);} else {- // For dataset and experiment targets, or event targets without OTEL SDKsetShowPreview(false);}if (isPeekView) {- setSelectedPreviewIds(undefined);+ setSelectedPreviewPointer(undefined);}- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [form.watch("target"), disabled, isPeekView, nonOtelCompatible]);+ }, [+ target,+ disabled,+ isPeekView,+ shouldShowPreviewForTarget,+ shouldDisablePreviewForNonOtel,+ ]);useEffect(() => {if (isPeekView) {- setSelectedPreviewIds(undefined);+ setSelectedPreviewPointer(undefined);}}, [isPeekView, peekId]);- // Hide preview controls for event targets only when SDK check was performed and user is not on OTEL SDKconst shouldShowPreviewControls =- isTraceOrEventTarget(form.watch("target")) &&- !disabled &&- !(isEventTarget(form.watch("target")) && nonOtelCompatible);+ shouldShowPreviewForTarget && !disabled && !shouldDisablePreviewForNonOtel;+ const previewNavigationListKey = getEvalPreviewDetailPageListKey(+ target,+ isBetaEnabled,+ );+ const evalPreviewBasePath = hideAdvancedSettings+ ? `/project/${projectId}/evals/remap?evaluator=${oldConfigId}`+ : `/project/${projectId}/evals/new?evaluator=${evalTemplate.id}`;const mappingControlButtons = (<div className="flex items-center gap-2">@@ -149,48 +170,33 @@ export const VariableMappingCard = ({disabled={disabled}/>{showPreview &&- (previewData ? (+ (previewData && previewNavigationListKey ? (<DetailPageNavcurrentId={previewData.type === EvalTargetObject.EVENT? previewData.observationId: previewData.traceId}- listKey={- isEventTarget(form.watch("target"))- ? "observations"- : "traces"- }+ listKey={previewNavigationListKey}onNavigate={isPeekView? (entry) => {- if (isEventTarget(form.watch("target"))) {- setSelectedPreviewIds({- traceId: entry.params?.traceId,- observationId: entry.id,- });- } else {- setSelectedPreviewIds({- traceId: entry.id,- observationId: undefined,- });- }+ setSelectedPreviewPointer(+ getEvalPreviewPointerFromDetailPageEntry(+ entry,+ target,+ ),+ );}: undefined}- path={(entry) => {- const isEvent = isEventTarget(form.watch("target"));- const basePath = hideAdvancedSettings- ? `/project/${projectId}/evals/remap?evaluator=${oldConfigId}`- : `/project/${projectId}/evals/new?evaluator=${evalTemplate.id}`;- if (isEvent) {- // For observations/events: entry.id is observationId, entry.params.traceId is traceId- return `${basePath}&traceId=${entry.params?.traceId}&observationId=${entry.id}`;- } else {- // For traces: entry.id is traceId- return `${basePath}&traceId=${entry.id}`;- }- }}+ path={(entry) =>+ buildEvalPreviewNavigationPath({+ basePath: evalPreviewBasePath,+ entry,+ target,+ })+ }/>) : (<div className="flex flex-row gap-1">diff --git a/web/src/features/evals/hooks/useCodeEvalSourceValidation.ts b/web/src/features/evals/hooks/useCodeEvalSourceValidation.tsnew file mode 100644index 0000000000..d6f696781b--- /dev/null+++ b/web/src/features/evals/hooks/useCodeEvalSourceValidation.ts@@ -0,0 +1,125 @@+import { useCallback, useEffect, useState } from "react";+import { EvalTemplateSourceCodeLanguage } from "@langfuse/shared";++import {+ type CodeEvalSourceCodeLanguage,+ type CodeEvalValidationResult,+ validateCodeEvalSourceWithLanguage,+} from "@/src/features/evals/utils/code-eval-template-validation";++type UseCodeEvalSourceValidationParams = {+ enabled: boolean;+ sourceCode: string;+ sourceCodeLanguage: CodeEvalSourceCodeLanguage;+};++type ValidateCodeEvalSourceParams = {+ sourceCode?: string;+ sourceCodeLanguage?: CodeEvalSourceCodeLanguage;+};++function getLanguageLabel(sourceCodeLanguage: CodeEvalSourceCodeLanguage) {+ return sourceCodeLanguage === EvalTemplateSourceCodeLanguage.PYTHON+ ? "Python"+ : "TypeScript";+}++async function getCodeEvalValidationResult({+ sourceCode,+ sourceCodeLanguage,+}: {+ sourceCode: string;+ sourceCodeLanguage: CodeEvalSourceCodeLanguage;+}): Promise<CodeEvalValidationResult> {+ try {+ return await validateCodeEvalSourceWithLanguage({+ source: sourceCode,+ sourceCodeLanguage,+ });+ } catch (error) {+ return {+ sourceBytes: new TextEncoder().encode(sourceCode).length,+ hasErrors: true,+ diagnostics: [+ {+ from: 0,+ to: Math.max(1, sourceCode.length),+ severity: "error",+ message:+ error instanceof Error+ ? error.message+ : `Failed to validate ${getLanguageLabel(sourceCodeLanguage)} source.`,+ },+ ],+ };+ }+}++export function useCodeEvalSourceValidation({+ enabled,+ sourceCode,+ sourceCodeLanguage,+}: UseCodeEvalSourceValidationParams) {+ const [validationResult, setValidationResult] =+ useState<CodeEvalValidationResult | null>(null);+ const [isPending, setIsPending] = useState(false);++ const reset = useCallback(() => {+ setValidationResult(null);+ setIsPending(false);+ }, []);++ const validate = useCallback(+ async (params?: ValidateCodeEvalSourceParams) => {+ const nextSourceCode = params?.sourceCode ?? sourceCode;+ const nextSourceCodeLanguage =+ params?.sourceCodeLanguage ?? sourceCodeLanguage;++ setIsPending(true);+ const result = await getCodeEvalValidationResult({+ sourceCode: nextSourceCode,+ sourceCodeLanguage: nextSourceCodeLanguage,+ });+ setValidationResult(result);+ setIsPending(false);++ return !result.hasErrors;+ },+ [sourceCode, sourceCodeLanguage],+ );++ useEffect(() => {+ if (!enabled) {+ reset();+ return;+ }++ let isActive = true;+ setIsPending(true);++ const timeout = setTimeout(() => {+ getCodeEvalValidationResult({ sourceCode, sourceCodeLanguage })+ .then((result) => {+ if (!isActive) return;+ setValidationResult(result);+ })+ .finally(() => {+ if (isActive) setIsPending(false);+ });+ }, 250);++ return () => {+ isActive = false;+ clearTimeout(timeout);+ };+ }, [enabled, reset, sourceCode, sourceCodeLanguage]);++ return {+ isValid:+ Boolean(validationResult) && !isPending && !validationResult?.hasErrors,+ isPending,+ validationResult,+ validate,+ reset,+ };+}diff --git a/web/src/features/evals/hooks/useEvalCapabilities.ts b/web/src/features/evals/hooks/useEvalCapabilities.tsindex cffd9a1c54..b5c7ac5f1d 100644--- a/web/src/features/evals/hooks/useEvalCapabilities.ts+++ b/web/src/features/evals/hooks/useEvalCapabilities.ts@@ -2,6 +2,7 @@ import { useSession } from "next-auth/react";import { api } from "@/src/utils/api";import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";+import { useIsCodeEvalEnabled } from "@/src/features/evals/hooks/useIsCodeEvalEnabled";export interface EvalCapabilities {isNewCompatible: boolean;@@ -15,12 +16,22 @@ export interface EvalCapabilities {/*** Hook to determine which eval configuration features are available* @param projectId - The project ID to check+ * @param options - Optional configuration+ * @param options.isCodeEvalTemplate - When true and code evals are enabled, disables legacy eval options* @returns Capabilities object indicating which eval features are allowed*/-export function useEvalCapabilities(projectId: string): EvalCapabilities {+export function useEvalCapabilities(+ projectId: string,+ options?: {+ isCodeEvalTemplate?: boolean;+ },+): EvalCapabilities {const { data: session, status: sessionStatus } = useSession();const isSessionLoading = sessionStatus === "loading";const { isBetaEnabled } = useV4Beta();+ const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();+ const isCodeEvalConfig =+ isCodeEvalEnabled && (options?.isCodeEvalTemplate ?? false);// Query SDK version info from events table (only when v4 beta is enabled)const sdkVersionInfo = api.events.getSdkVersionInfo.useQuery(@@ -48,8 +59,9 @@ export function useEvalCapabilities(projectId: string): EvalCapabilities {isNewCompatible: isOtel,// True when v4 beta is enabled (SDK check query was run)compatibilityCheckWasPerformed: isBetaEnabled,- // Allow legacy if: not cloud OR user has legacy evals OR user can toggle v4 (existing user)- allowLegacy: !isLangfuseCloud || hasLegacyEvals || canToggleV4,+ // Allow legacy if: not code eval AND (not cloud OR user has legacy evals OR user can toggle v4)+ allowLegacy:+ !isCodeEvalConfig && (!isLangfuseCloud || hasLegacyEvals || canToggleV4),// Allow propagation filters only when using OTEL and spans are propagatingallowPropagationFilters: isOtel && isPropagating,isLoading:diff --git a/web/src/features/evals/hooks/useEvalConfigMappingData.ts b/web/src/features/evals/hooks/useEvalConfigMappingData.tsindex 4c7c4a9344..7209469612 100644--- a/web/src/features/evals/hooks/useEvalConfigMappingData.ts+++ b/web/src/features/evals/hooks/useEvalConfigMappingData.ts@@ -1,12 +1,18 @@import { type EvalFormType } from "@/src/features/evals/utils/evaluator-form-utils";import { EvalTargetObject, type ObservationType } from "@langfuse/shared";-import { type UseFormReturn } from "react-hook-form";+import { type UseFormReturn, useWatch } from "react-hook-form";import { useRouter } from "next/router";import {type PreviewData,usePreviewData,} from "@/src/features/evals/hooks/usePreviewData";import { useEffect, useRef } from "react";+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";+import {+ type EvalPreviewPointer,+ getEvalPreviewPointerFromUrlQuery,+ useFirstEvalPreviewPointer,+} from "@/src/features/evals/hooks/useEvalPreviewNavigation";type EvalConfigMappingData = {namesByObject: Map<string, Set<string>>;@@ -18,36 +24,35 @@ export function useEvalConfigMappingData(projectId: string,form: UseFormReturn<EvalFormType>,disabled = false,- selectedPreviewIds?: {- traceId?: string;- observationId?: string;- },+ selectedPreviewPointer?: EvalPreviewPointer,): EvalConfigMappingData {const router = useRouter();+ const { isBetaEnabled } = useV4Beta();- // In full-page mode, keep using URL params. In peek mode, callers can manage preview ids locally.- const traceId =- selectedPreviewIds?.traceId ??- (typeof router.query.traceId === "string"- ? router.query.traceId- : undefined);- const observationId =- selectedPreviewIds?.observationId ??- (typeof router.query.observationId === "string"- ? router.query.observationId- : undefined);+ const targetValue = useWatch({ control: form.control, name: "target" });+ const firstPreviewPointer = useFirstEvalPreviewPointer({+ target: targetValue,+ useEventsTable: isBetaEnabled,+ });+ const urlPreviewPointer = getEvalPreviewPointerFromUrlQuery(+ router.query,+ targetValue,+ );+ // Peek navigation wins over URL state; URL state wins over the table's first row.+ const previewPointer =+ selectedPreviewPointer ?? urlPreviewPointer ?? firstPreviewPointer;- const { previewData, isLoading } = usePreviewData(+ const { previewData, isLoading } = usePreviewData({projectId,- form,- !disabled,- traceId,- observationId,- );+ enabled: !disabled && Boolean(previewPointer),+ target: targetValue,+ traceId: previewPointer?.traceId,+ observationId: previewPointer?.observationId,+ timestamp: previewPointer?.timestamp,+ });- const targetValue = form.watch("target");const prevTargetRef = useRef(targetValue);- const isLocallyManagedPreview = Boolean(selectedPreviewIds);+ const isLocallyManagedPreview = Boolean(selectedPreviewPointer);// drop the traceId and observation-related params from the URL query parameters when target changesuseEffect(() => {@@ -61,7 +66,8 @@ export function useEvalConfigMappingData(prevTargetRef.current !== undefined) {// Remove navigation-related params when target changes- const { traceId, observationId, ...restQuery } = router.query;+ const { traceId, observationId, timestamp, startTime, ...restQuery } =+ router.query;// Use replace to avoid adding to browser historyvoid router.replace(@@ -84,7 +90,7 @@ export function useEvalConfigMappingData(// Only populate observation names for trace evals (where observations are available)if (previewData?.type === EvalTargetObject.TRACE) {- previewData?.data?.observations.forEach((observation) => {+ previewData.trace.observations.forEach((observation) => {if (observation.type && observation.name) {observationTypeToNames.get(observation.type)?.add(observation.name);}@@ -92,7 +98,7 @@ export function useEvalConfigMappingData(}return {- namesByObject: new Map<string, Set<string>>(),+ namesByObject: observationTypeToNames,isLoading,previewData,};diff --git a/web/src/features/evals/hooks/useEvalPreviewNavigation.ts b/web/src/features/evals/hooks/useEvalPreviewNavigation.tsnew file mode 100644index 0000000000..1deecd122c--- /dev/null+++ b/web/src/features/evals/hooks/useEvalPreviewNavigation.ts@@ -0,0 +1,151 @@+import {+ detailPageListKeys,+ type EventDetailPageListEntry,+ type ListEntry,+ type ObservationDetailPageListEntry,+ type TraceDetailPageListEntry,+ useFirstDetailPageListEntry,+} from "@/src/features/navigate-detail-pages/context";+import { type NextRouter } from "next/router";+import {+ EvalTargetObject,+ type EvalTargetObject as EvalTargetObjectType,+} from "@langfuse/shared";+import {+ isEventTarget,+ isExperimentTarget,+} from "@/src/features/evals/utils/typeHelpers";++export type EvalPreviewPointer = {+ traceId?: string;+ observationId?: string;+ timestamp?: Date;+};++type EvalPreviewDetailPageListEntry =+ | TraceDetailPageListEntry+ | ObservationDetailPageListEntry+ | EventDetailPageListEntry;++export function getEvalPreviewDetailPageListKey(+ target: EvalTargetObjectType,+ useEventsTable: boolean,+) {+ if (target === EvalTargetObject.TRACE) return detailPageListKeys.traces;+ if (isExperimentTarget(target)) return detailPageListKeys.events;+ if (isEventTarget(target)) {+ return useEventsTable+ ? detailPageListKeys.events+ : detailPageListKeys.observations;+ }+ return undefined;+}++function parseTimestamp(timestamp: string | string[] | undefined) {+ if (Array.isArray(timestamp)) return undefined;+ if (!timestamp) return undefined;++ try {+ const date = new Date(decodeURIComponent(timestamp));+ return Number.isNaN(date.getTime()) ? undefined : date;+ } catch {+ return undefined;+ }+}++export function getEvalPreviewPointerFromDetailPageEntry(+ entry: ListEntry | undefined,+ target: EvalTargetObjectType,+): EvalPreviewPointer | undefined {+ if (!entry) return undefined;++ if (target === EvalTargetObject.TRACE) {+ return {+ traceId: entry.id,+ timestamp: parseTimestamp(entry.params?.timestamp),+ };+ }++ const observationEntry = entry as ObservationDetailPageListEntry;+ const traceId = observationEntry.params?.traceId;+ if (!traceId) return undefined;++ return {+ traceId,+ observationId: observationEntry.id,+ timestamp: parseTimestamp(+ observationEntry.params?.startTime ?? observationEntry.params?.timestamp,+ ),+ };+}++export function getEvalPreviewPointerFromUrlQuery(+ query: NextRouter["query"],+ target: EvalTargetObjectType,+): EvalPreviewPointer | undefined {+ const traceId = typeof query.traceId === "string" ? query.traceId : undefined;+ if (!traceId) return undefined;++ const observationId =+ typeof query.observationId === "string" ? query.observationId : undefined;+ const timestamp =+ target === EvalTargetObject.TRACE+ ? parseTimestamp(query.timestamp)+ : (parseTimestamp(query.startTime) ?? parseTimestamp(query.timestamp));++ if (target === EvalTargetObject.TRACE) {+ return { traceId, timestamp };+ }++ return observationId && timestamp+ ? { traceId, observationId, timestamp }+ : undefined;+}++export function buildEvalPreviewNavigationPath({+ basePath,+ entry,+ target,+}: {+ basePath: string;+ entry: ListEntry;+ target: EvalTargetObjectType;+}) {+ const pointer = getEvalPreviewPointerFromDetailPageEntry(entry, target);+ if (!pointer) return basePath;++ const params = new URLSearchParams();++ if (pointer.traceId) params.set("traceId", pointer.traceId);+ if (pointer.observationId) params.set("observationId", pointer.observationId);+ if (pointer.timestamp) {+ params.set(+ target === EvalTargetObject.TRACE ? "timestamp" : "startTime",+ pointer.timestamp.toISOString(),+ );+ }++ return `${basePath}${basePath.includes("?") ? "&" : "?"}${params.toString()}`;+}++export function useFirstEvalPreviewNavigationEntry({+ target,+ useEventsTable,+}: {+ target: EvalTargetObjectType;+ useEventsTable: boolean;+}): EvalPreviewDetailPageListEntry | undefined {+ const key = getEvalPreviewDetailPageListKey(target, useEventsTable);+ return useFirstDetailPageListEntry<EvalPreviewDetailPageListEntry>(key);+}++export function useFirstEvalPreviewPointer({+ target,+ useEventsTable,+}: {+ target: EvalTargetObjectType;+ useEventsTable: boolean;+}): EvalPreviewPointer | undefined {+ const entry = useFirstEvalPreviewNavigationEntry({ target, useEventsTable });+ return getEvalPreviewPointerFromDetailPageEntry(entry, target);+}diff --git a/web/src/features/evals/hooks/useExtractVariables.ts b/web/src/features/evals/hooks/useExtractVariables.tsindex 0404cfc6d2..65bc43f0db 100644--- a/web/src/features/evals/hooks/useExtractVariables.ts+++ b/web/src/features/evals/hooks/useExtractVariables.ts@@ -2,7 +2,10 @@ import { type PreviewData } from "@/src/features/evals/hooks/usePreviewData";import { type VariableMapping } from "@/src/features/evals/utils/evaluator-form-utils";import { api } from "@/src/utils/api";import { showErrorToast } from "@/src/features/notifications/showErrorToast";-import { EvalTargetObject, extractValueFromObject } from "@langfuse/shared";+import {+ EvalTargetObject,+ extractValueFromObjectAsString,+} from "@langfuse/shared";import { useEffect, useState, useRef } from "react";/**@@ -18,9 +21,21 @@ function getObservationByName(return observations.find((o) => o.name === objectName) || null;}+function normalizePreviewColumnId(selectedColumnId: string) {+ switch (selectedColumnId) {+ case "expected_output":+ case "experiment_item_expected_output":+ return "experimentItemExpectedOutput";+ case "experiment_item_metadata":+ return "experimentItemMetadata";+ default:+ return selectedColumnId;+ }+}+type ExtractedVariable = {variable: string;- value: unknown;+ value: string;};type ExtractionError =@@ -116,24 +131,27 @@ export function useExtractVariables({if (!mapping ||!mapping.selectedColumnId ||- (!mapping.langfuseObject && !(previewData.type === "event"))+ (!mapping.langfuseObject && previewData.type !== EvalTargetObject.EVENT)) {return { variable, value: "n/a" };}let object;+ const selectedColumnId = normalizePreviewColumnId(+ mapping.selectedColumnId,+ );- if (previewData.type === "event") {+ if (previewData.type === EvalTargetObject.EVENT) {object = previewData.data; // Already has input/output} else {// Trace eval: can map to trace or observation fieldsif (mapping.langfuseObject === "trace") {- object = previewData.data;+ object = previewData.trace;} else if (mapping.langfuseObject !== "dataset_item") {// Find observation by name from mappingconst observation = getObservationByName(mapping.objectName,- previewData.data.observations as Record<string, unknown>[],+ previewData.trace.observations as Record<string, unknown>[],);if (observation?.id) {@@ -143,8 +161,8 @@ export function useExtractVariables({await utils.observations.byId.fetch({observationId: observation.id as string,startTime: observation.startTime as Date | null,- traceId: previewData.data.id as string,- projectId: previewData.data.projectId as string,+ traceId: previewData.trace.id as string,+ projectId: previewData.trace.projectId as string,});object = observationWithInputAndOutput;} catch (error) {@@ -158,9 +176,9 @@ export function useExtractVariables({return { variable, value: "n/a" };}- const { value, error } = extractValueFromObject(+ const { value, error } = extractValueFromObjectAsString(object,- mapping.selectedColumnId,+ selectedColumnId,mapping.jsonSelector ?? undefined,);return {diff --git a/web/src/features/evals/hooks/useIsCodeEvalEnabled.ts b/web/src/features/evals/hooks/useIsCodeEvalEnabled.tsnew file mode 100644index 0000000000..ca05e70444--- /dev/null+++ b/web/src/features/evals/hooks/useIsCodeEvalEnabled.ts@@ -0,0 +1,7 @@+import { isCodeEvalEnabled } from "@/src/features/evals/server/isCodeEvalEnabled";++export function useIsCodeEvalEnabled(): { enabled: boolean } {+ return {+ enabled: isCodeEvalEnabled(),+ };+}diff --git a/web/src/features/evals/hooks/usePreviewData.ts b/web/src/features/evals/hooks/usePreviewData.tsindex 93a4e244d1..45a3e7454c 100644--- a/web/src/features/evals/hooks/usePreviewData.ts+++ b/web/src/features/evals/hooks/usePreviewData.ts@@ -1,208 +1,320 @@-import { type EvalFormType } from "@/src/features/evals/utils/evaluator-form-utils";-import { api, type RouterOutputs } from "@/src/utils/api";-import { EvalTargetObject, type FilterState } from "@langfuse/shared";-import { type UseFormReturn } from "react-hook-form";-import { isEventTarget } from "@/src/features/evals/utils/typeHelpers";+import {+ isEventTarget,+ isExperimentTarget,+} from "@/src/features/evals/utils/typeHelpers";import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";+import { api, type RouterOutputs } from "@/src/utils/api";+import {+ EvalTargetObject,+ extractValueFromObject,+ type EvalTargetObject as EvalTargetObjectType,+} from "@langfuse/shared";-export type PreviewData =- | {- type: typeof EvalTargetObject.TRACE;- traceId: string;- data: RouterOutputs["traces"]["byIdWithObservationsAndScores"];- }- | {- type: typeof EvalTargetObject.EVENT;- traceId: string;- observationId: string;- data:- | RouterOutputs["observations"]["byId"]- | RouterOutputs["events"]["batchIO"][number]- | undefined;- };--// Temporary workaround to make filter backwards compatible with generations table-const transformFilterForGenerations = (filter: FilterState | null) => {- if (!filter) return [];- return filter.map((f) => {- if (f.column === "tags") {- return {- ...f,- column: "traceTags",- };- }- return f;- });+export type PreviewDataFields = {+ input: unknown;+ output: unknown;+ metadata: unknown;+ experimentItemExpectedOutput: unknown;+ experimentItemMetadata: unknown;};-export function usePreviewData(- projectId: string,- form: UseFormReturn<EvalFormType>,- enabled: boolean,- traceId: string | undefined,- observationId: string | undefined,-): { previewData: PreviewData | null; isLoading: boolean } {- const { isBetaEnabled } = useV4Beta();+type TracePreviewData = {+ type: typeof EvalTargetObject.TRACE;+ traceId: string;+ timestamp: Date | null;+ observationId?: undefined;+ trace: RouterOutputs["traces"]["byIdWithObservationsAndScores"];+};- // For trace evals without traceId: fetch latest trace matching filter- const target = form.watch("target");- const isEventEval = isEventTarget(target);- const isTraceEval = target === EvalTargetObject.TRACE;- const latestTrace = api.traces.all.useQuery(- {- projectId,- filter: form.watch("filter"),- searchQuery: "",- searchType: [],- limit: 1,- page: 0,- orderBy: { column: "timestamp", order: "DESC" },- },- {- enabled: enabled && !traceId && isTraceEval,- },- );+type ObservationPreviewData = {+ type: typeof EvalTargetObject.EVENT;+ traceId: string;+ observationId: string;+ timestamp: Date | null;+ data: PreviewDataFields;+};++export type PreviewData = TracePreviewData | ObservationPreviewData;++type PreviewResult = {+ previewData: PreviewData | null;+ isLoading: boolean;+};++type UsePreviewDataParams = {+ projectId: string;+ enabled: boolean;+ target: EvalTargetObjectType;+ traceId?: string;+ observationId?: string;+ timestamp?: Date;+};++type PreviewMode = "none" | "trace" | "observation" | "event" | "experiment";++const EMPTY_PREVIEW_RESULT: PreviewResult = {+ previewData: null,+ isLoading: false,+};++function getPreviewMode({+ enabled,+ target,+ shouldUseEventsTable,+}: {+ enabled: boolean;+ target: EvalTargetObjectType;+ shouldUseEventsTable: boolean;+}): PreviewMode {+ if (!enabled) return "none";+ if (target === EvalTargetObject.TRACE) return "trace";+ if (isExperimentTarget(target) && shouldUseEventsTable) return "experiment";+ if (isEventTarget(target)) {+ return shouldUseEventsTable ? "event" : "observation";+ }+ return "none";+}++function normalizePreviewDataFields(+ record: Record<string, unknown> | null | undefined,+): PreviewDataFields {+ return {+ input: getRecordValue(record, "input"),+ output: getRecordValue(record, "output"),+ metadata: getRecordValue(record, "metadata"),+ experimentItemExpectedOutput: getRecordValue(+ record,+ "experimentItemExpectedOutput",+ ),+ experimentItemMetadata: getRecordValue(record, "experimentItemMetadata"),+ };+}- const actualTraceId = traceId ?? latestTrace.data?.traces[0]?.id;+function getRecordValue(+ record: Record<string, unknown> | null | undefined,+ selectedColumnId: string,+) {+ if (!record) return null;++ const { value } = extractValueFromObject(record, selectedColumnId);+ return value === undefined ? null : value;+}- // For trace evals: fetch full trace with observations+function useTracePreview({+ projectId,+ traceId,+ timestamp,+ enabled,+}: Pick<UsePreviewDataParams, "projectId" | "traceId" | "timestamp"> & {+ enabled: boolean;+}): PreviewResult {const traceDetails = api.traces.byIdWithObservationsAndScores.useQuery({projectId,- traceId: actualTraceId as string,+ traceId: traceId as string,+ timestamp: timestamp ?? null,},{- enabled: enabled && !!actualTraceId && isTraceEval,+ enabled: enabled && !!traceId,},);- const latestObservation = api.generations.all.useQuery(- {- projectId,- filter: transformFilterForGenerations(form.watch("filter")) ?? [],- searchQuery: "",- searchType: [],- limit: 1,- page: 0,- orderBy: {- column: "startTime",- order: "DESC",- },- },- {- enabled: enabled && !observationId && isEventEval && !isBetaEnabled,- },- );+ return {+ previewData:+ traceDetails.data && traceId+ ? {+ type: EvalTargetObject.TRACE,+ traceId,+ timestamp: traceDetails.data.timestamp ?? timestamp ?? null,+ trace: traceDetails.data,+ }+ : null,+ isLoading: traceDetails.isLoading,+ };+}- const latestObservationBeta = api.events.all.useQuery(+function useObservationPreview({+ projectId,+ traceId,+ observationId,+ timestamp,+ enabled,+}: Pick<+ UsePreviewDataParams,+ "projectId" | "traceId" | "observationId" | "timestamp"+> & {+ enabled: boolean;+}): PreviewResult {+ const observationDetails = api.observations.byId.useQuery({projectId,- filter: form.watch("filter") ?? [],- searchQuery: "",- searchType: [],- limit: 1,- page: 0,- orderBy: {- column: "startTime",- order: "DESC",- },+ traceId: traceId as string,+ observationId: observationId as string,+ startTime: timestamp ?? null,},{- enabled: enabled && !observationId && isEventEval && isBetaEnabled,+ enabled: enabled && !!traceId && !!observationId,},);- const latestObservationTraceId = !!observationId- ? traceId- : isBetaEnabled- ? latestObservationBeta.data?.observations[0]?.traceId- : latestObservation.data?.generations[0]?.traceId;- const latestObservationObservationId = !!observationId- ? observationId- : isBetaEnabled- ? latestObservationBeta.data?.observations[0]?.id- : latestObservation.data?.generations[0]?.id;-- const latestObservationStartTime =- latestObservationBeta.data?.observations[0]?.startTime;- const latestObservationEndTime =- latestObservationBeta.data?.observations[0]?.endTime;-- // For event evals: fetch only the single observation- const observationDetails = api.observations.byId.useQuery(+ return {+ previewData:+ observationDetails.data && traceId && observationId+ ? {+ type: EvalTargetObject.EVENT,+ traceId,+ observationId,+ timestamp: observationDetails.data.startTime ?? null,+ data: normalizePreviewDataFields(+ observationDetails.data as Record<string, unknown>,+ ),+ }+ : null,+ isLoading: observationDetails.isLoading,+ };+}++function useEventPreview({+ projectId,+ traceId,+ observationId,+ timestamp,+ enabled,+}: Pick<+ UsePreviewDataParams,+ "projectId" | "traceId" | "observationId" | "timestamp"+> & {+ enabled: boolean;+}): PreviewResult {+ const eventDetails = api.events.batchIO.useQuery({projectId,- traceId: latestObservationTraceId as string,- observationId: latestObservationObservationId as string,- startTime: null,+ observations: [+ {+ id: observationId as string,+ traceId: traceId as string,+ },+ ],+ minStartTime: timestamp as Date,+ maxStartTime: timestamp as Date,+ truncated: false,},{- enabled:- enabled &&- !!latestObservationTraceId &&- !!latestObservationObservationId &&- isEventEval &&- !isBetaEnabled,+ enabled: enabled && !!observationId && !!traceId && !!timestamp,},);- const observationDetailsBeta = api.events.batchIO.useQuery(+ return {+ previewData:+ observationId && traceId && timestamp && eventDetails.data?.[0]+ ? {+ type: EvalTargetObject.EVENT,+ traceId,+ observationId,+ timestamp,+ data: normalizePreviewDataFields(+ eventDetails.data[0] as Record<string, unknown>,+ ),+ }+ : null,+ isLoading: eventDetails.isLoading,+ };+}++function useExperimentPreview({+ projectId,+ traceId,+ observationId,+ timestamp,+ enabled,+}: Pick<+ UsePreviewDataParams,+ "projectId" | "traceId" | "observationId" | "timestamp"+> & {+ enabled: boolean;+}): PreviewResult {+ const experimentDetails = api.events.experimentBatchIO.useQuery({projectId,observations: [{- id: latestObservationObservationId as string,- traceId: latestObservationTraceId as string,+ id: observationId as string,+ traceId: traceId as string,},],- minStartTime: latestObservationStartTime as Date,- maxStartTime: latestObservationEndTime as Date,+ minStartTime: timestamp as Date,+ maxStartTime: timestamp as Date,truncated: false,},{- enabled:- enabled &&- !!latestObservationTraceId &&- !!latestObservationObservationId &&- !!latestObservationStartTime &&- !!latestObservationEndTime &&- isEventEval &&- isBetaEnabled,+ enabled: enabled && !!observationId && !!traceId && !!timestamp,},);- const previewData: PreviewData | null = isEventEval- ? (isBetaEnabled- ? observationDetailsBeta.data?.[0]- : observationDetails.data) &&- latestObservationTraceId &&- latestObservationObservationId- ? {- type: EvalTargetObject.EVENT,- traceId: latestObservationTraceId,- observationId: latestObservationObservationId,- data: isBetaEnabled- ? observationDetailsBeta.data?.[0]- : observationDetails.data,- }- : null- : traceDetails.data && actualTraceId- ? {- type: EvalTargetObject.TRACE,- traceId: actualTraceId,- data: traceDetails.data,- }- : null;-- const isLoading =- latestTrace.isLoading ||- traceDetails.isLoading ||- (isBetaEnabled- ? observationDetailsBeta.isLoading- : observationDetails.isLoading);-return {- previewData,- isLoading,+ previewData:+ observationId && traceId && timestamp && experimentDetails.data?.[0]+ ? {+ type: EvalTargetObject.EVENT,+ traceId,+ observationId,+ timestamp,+ data: normalizePreviewDataFields(+ experimentDetails.data[0] as Record<string, unknown>,+ ),+ }+ : null,+ isLoading: experimentDetails.isLoading,};}++export function usePreviewData({+ projectId,+ enabled,+ target,+ traceId,+ observationId,+ timestamp,+}: UsePreviewDataParams): PreviewResult {+ const { isBetaEnabled } = useV4Beta();+ const mode = getPreviewMode({+ enabled,+ target,+ shouldUseEventsTable: isBetaEnabled,+ });++ const tracePreview = useTracePreview({+ projectId,+ traceId,+ timestamp,+ enabled: mode === "trace",+ });+ const observationPreview = useObservationPreview({+ projectId,+ traceId,+ observationId,+ timestamp,+ enabled: mode === "observation",+ });+ const eventPreview = useEventPreview({+ projectId,+ traceId,+ observationId,+ timestamp,+ enabled: mode === "event",+ });+ const experimentPreview = useExperimentPreview({+ projectId,+ traceId,+ observationId,+ timestamp,+ enabled: mode === "experiment",+ });++ if (mode === "trace") return tracePreview;+ if (mode === "observation") return observationPreview;+ if (mode === "event") return eventPreview;+ if (mode === "experiment") return experimentPreview;++ return EMPTY_PREVIEW_RESULT;+}diff --git a/web/src/features/evals/hooks/useSingleTemplateValidation.ts b/web/src/features/evals/hooks/useSingleTemplateValidation.tsindex 76074b42c0..4448204fbe 100644--- a/web/src/features/evals/hooks/useSingleTemplateValidation.ts+++ b/web/src/features/evals/hooks/useSingleTemplateValidation.ts@@ -1,24 +1,31 @@import { api } from "@/src/utils/api";import { type EvalTemplate } from "@langfuse/shared";+import { useIsCodeEvalEnabled } from "@/src/features/evals/hooks/useIsCodeEvalEnabled";+import { isCodeEvalTemplate } from "@/src/features/evals/utils/code-eval-template-utils";export function useSingleTemplateValidation({projectId,}: {projectId: string;}) {+ const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();const { data: defaultModel } = api.defaultLlmModel.fetchDefaultModel.useQuery({ projectId },);const templateRequiresDefaultModel = (- template: Partial<EvalTemplate> & Pick<EvalTemplate, "provider" | "model">,+ template: Partial<Pick<EvalTemplate, "provider" | "model" | "type">>,): boolean => {+ if (isCodeEvalTemplate(template)) return false;+return !template.provider || !template.model;};const isTemplateInvalid = (- template: Partial<EvalTemplate> & Pick<EvalTemplate, "provider" | "model">,+ template: Partial<Pick<EvalTemplate, "provider" | "model" | "type">>,): boolean => {+ if (isCodeEvalTemplate(template)) return !isCodeEvalEnabled;+return templateRequiresDefaultModel(template) && !defaultModel;};diff --git a/web/src/features/evals/hooks/useTemplateValidation.ts b/web/src/features/evals/hooks/useTemplateValidation.tsindex d2561ff9cc..939cb13ed6 100644--- a/web/src/features/evals/hooks/useTemplateValidation.ts+++ b/web/src/features/evals/hooks/useTemplateValidation.ts@@ -2,6 +2,8 @@ import { useEffect } from "react";import { api } from "@/src/utils/api";import { useState } from "react";import { type EvalTemplate } from "@langfuse/shared/src/db";+import { useIsCodeEvalEnabled } from "@/src/features/evals/hooks/useIsCodeEvalEnabled";+import { isCodeEvalTemplate } from "@/src/features/evals/utils/code-eval-template-utils";export function useTemplateValidation({projectId,@@ -10,6 +12,7 @@ export function useTemplateValidation({projectId: string;onValidSelection?: (template: EvalTemplate) => void;}) {+ const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();const [selectedTemplate, setSelectedTemplate] = useState<EvalTemplate | null>(null,);@@ -22,6 +25,14 @@ export function useTemplateValidation({// validate that either a default eval model is set or the selected eval has a custom modeluseEffect(() => {if (selectedTemplate) {+ if (isCodeEvalTemplate(selectedTemplate)) {+ setIsSelectionValid(isCodeEvalEnabled);+ if (isCodeEvalEnabled) {+ onValidSelection?.(selectedTemplate);+ }+ return;+ }+if (!(selectedTemplate.provider || defaultModel.data?.provider)) {setIsSelectionValid(false);return;@@ -37,7 +48,7 @@ export function useTemplateValidation({onValidSelection?.(selectedTemplate);}// eslint-disable-next-line react-hooks/exhaustive-deps- }, [selectedTemplate?.id, onValidSelection]);+ }, [selectedTemplate?.id, onValidSelection, isCodeEvalEnabled]);return { isSelectionValid, selectedTemplate, setSelectedTemplate };}diff --git a/web/src/features/evals/hooks/useTemplatesValidation.ts b/web/src/features/evals/hooks/useTemplatesValidation.tsindex 65d2b08cf3..f161c0c5c9 100644--- a/web/src/features/evals/hooks/useTemplatesValidation.ts+++ b/web/src/features/evals/hooks/useTemplatesValidation.ts@@ -1,5 +1,7 @@import { useState, useEffect } from "react";import { api } from "@/src/utils/api";+import { useIsCodeEvalEnabled } from "@/src/features/evals/hooks/useIsCodeEvalEnabled";+import { isCodeEvalTemplate } from "@/src/features/evals/utils/code-eval-template-utils";export function useTemplatesValidation({projectId,@@ -9,6 +11,7 @@ export function useTemplatesValidation({selectedTemplateIds?: string[];}) {const [isSelectionValid, setIsSelectionValid] = useState(true);+ const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();// Fetch default modelconst { data: defaultModel, isLoading: isLoadingDefaultModel } =@@ -26,18 +29,28 @@ export function useTemplatesValidation({useEffect(() => {if (isLoadingDefaultModel) return;+ // Find selected templates+ const selectedTemplates = (templatesData?.templates || []).filter(+ (template) => selectedTemplateIds.includes(template.id),+ );++ if (+ selectedTemplates.some(+ (template) => isCodeEvalTemplate(template) && !isCodeEvalEnabled,+ )+ ) {+ setIsSelectionValid(false);+ return;+ }+// If there's no default model, check if any of the selected templates requires oneif (!defaultModel) {- // Find selected templates- const selectedTemplates = (templatesData?.templates || []).filter(- (template) => selectedTemplateIds.includes(template.id),- );-- // Check if any template requires a default model (has no provider/model specified)+ // Check if any LLM-as-a-judge template requires a default model (has no provider/model specified)const requiresDefaultModel = selectedTemplates.some(- (template) => !template.provider || !template.model,+ (template) =>+ !isCodeEvalTemplate(template) &&+ (!template.provider || !template.model),);-setIsSelectionValid(!requiresDefaultModel);} else {// If there is a default model, selection is valid@@ -46,6 +59,7 @@ export function useTemplatesValidation({}, [defaultModel,isLoadingDefaultModel,+ isCodeEvalEnabled,selectedTemplateIds,templatesData?.templates,]);@@ -56,15 +70,16 @@ export function useTemplatesValidation({const isTemplateValid = (templateId: string): boolean => {if (!templatesData?.templates) return true;- // If we have a default model, all templates are valid- if (defaultModel) return true;-// Find the templateconst template = templatesData.templates.find((t) => t.id === templateId);if (!template) return true;+ if (isCodeEvalTemplate(template)) return isCodeEvalEnabled;++ // If we have a default model, all LLM-as-a-judge templates are valid+ if (defaultModel) return true;// If template has no provider or model, it requires a default model- return !(template.provider === undefined || template.model === undefined);+ return Boolean(template.provider && template.model);};return {diff --git a/web/src/features/evals/pages/evaluators.tsx b/web/src/features/evals/pages/evaluators.tsxindex b9269749da..fc95787e3f 100644--- a/web/src/features/evals/pages/evaluators.tsx+++ b/web/src/features/evals/pages/evaluators.tsx@@ -60,7 +60,7 @@ export default function EvaluatorsPage() {return (<PageheaderProps={{- title: "LLM-as-a-Judge Evaluators",+ title: "Evaluators",help: {description:"Configure a langfuse managed or custom evaluator to evaluate incoming traces.",@@ -78,7 +78,7 @@ export default function EvaluatorsPage() {<><PageheaderProps={{- title: "LLM-as-a-Judge Evaluators",+ title: "Evaluators",help: {description:"Configure a langfuse managed or custom evaluator to evaluate incoming traces.",diff --git a/web/src/features/evals/pages/new-evaluator.tsx b/web/src/features/evals/pages/new-evaluator.tsxindex a41dd4f6c4..bf0ab1bc69 100644--- a/web/src/features/evals/pages/new-evaluator.tsx+++ b/web/src/features/evals/pages/new-evaluator.tsx@@ -14,6 +14,8 @@ import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccesimport { getMaintainer } from "@/src/features/evals/utils/typeHelpers";import { MaintainerTooltip } from "@/src/features/evals/components/maintainer-tooltip";import { DefaultEvalModelSetup } from "@/src/features/evals/components/default-eval-model-setup";+import { useIsCodeEvalEnabled } from "@/src/features/evals/hooks/useIsCodeEvalEnabled";+import { shouldShowEvalTemplate } from "@/src/features/evals/utils/code-eval-template-utils";// Multi-step setup process// 0. Set up default model (optional, only if no default model exists): /project/:projectId/evals/new@@ -23,6 +25,7 @@ export default function NewEvaluatorPage() {const router = useRouter();const projectId = router.query.projectId as string;const evaluatorId = router.query.evaluator as string | undefined;+ const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();const hasDefaultModelReadAccess = useHasProjectAccess({projectId,@@ -36,9 +39,6 @@ export default function NewEvaluatorPage() {const hasDefaultModel = !!defaultModel;- // Calculate step number: if no default model, start at 0, otherwise start at 1- const stepInt = !hasDefaultModel ? 0 : !evaluatorId ? 1 : 2;-const hasAccess = useHasProjectAccess({projectId,scope: "evalTemplate:CUD",@@ -55,9 +55,16 @@ export default function NewEvaluatorPage() {},);- const currentTemplate = evalTemplates.data?.templates.find(- (t) => t.id === evaluatorId,- );+ const currentTemplate = evalTemplates.data?.templates+ .filter((template) => shouldShowEvalTemplate(template, isCodeEvalEnabled))+ .find((t) => t.id === evaluatorId);++ // Determine starting step:+ // - Step 2: Configure evaluator (when template already selected via evaluatorId)+ // - Step 1: Select template (when default model exists or code evals enabled)+ // - Step 0: Set up default model first+ const canSkipDefaultModel = isCodeEvalEnabled || hasDefaultModel;+ const stepInt = evaluatorId ? 2 : canSkipDefaultModel ? 1 : 0;if (!hasAccess) {return <div>You do not have access to this page.</div>;diff --git a/web/src/features/evals/pages/templates.tsx b/web/src/features/evals/pages/templates.tsxindex 262d8eea9f..4dee11f7e0 100644--- a/web/src/features/evals/pages/templates.tsx+++ b/web/src/features/evals/pages/templates.tsx@@ -33,7 +33,7 @@ export default function TemplatesPage() {return (<PageheaderProps={{- title: "LLM-as-a-Judge Evaluators",+ title: "Evaluators",help: {description: "View all langfuse managed and custom evaluators.",href: "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge",diff --git a/web/src/features/evals/server/codeEvalTestRun.ts b/web/src/features/evals/server/codeEvalTestRun.tsnew file mode 100644index 0000000000..f0ebfe2092--- /dev/null+++ b/web/src/features/evals/server/codeEvalTestRun.ts@@ -0,0 +1,422 @@+import { randomUUID } from "node:crypto";+import {+ DEFAULT_TRACE_ENVIRONMENT,+ eventTypes,+ createW3CTraceId,+ extractObservationVariables,+ getEventsStreamForEval,+ getObservationById,+ processEventBatch,+ resolveConfiguredCodeEvalDispatcher,+ runCodeBasedEvaluationDispatch,+ type CodeEvalUserVisibleErrorCode,+ type DispatchResult,+ type InternalTraceWriteInput,+} from "@langfuse/shared/src/server";+import { TRPCError } from "@trpc/server";++import {+ LangfuseNotFoundError,+ LangfuseInternalTraceEnvironment,+ observationForEvalSchema,+ type EvalTargetObject,+ type EvalTemplateCodeBased,+ type FilterCondition,+ type ObservationForEval,+ type ObservationVariableMapping,+} from "@langfuse/shared";+import { EvalTemplateType, type PrismaClient } from "@langfuse/shared/src/db";+import { env } from "@/src/env.mjs";+import { getExperimentEvalPreviewFilters } from "@/src/features/evals/utils/experiment-eval-preview-utils";+import {+ isEventTarget,+ isExperimentTarget,+} from "@/src/features/evals/utils/typeHelpers";++export type CodeEvalTestRunResult =+ | {+ success: true;+ result: DispatchResult;+ executionTraceId: string;+ executionTraceFromTimestamp: Date;+ }+ | {+ success: false;+ error: {+ code: CodeEvalUserVisibleErrorCode;+ message: string;+ };+ executionTraceId: string;+ executionTraceFromTimestamp: Date;+ };++export async function runCodeEvalTest(params: {+ prisma: PrismaClient;+ orgId: string;+ projectId: string;+ evalTemplateId: string;+ target: EvalTargetObject;+ mapping: ObservationVariableMapping[];+ scoreName: string;+ observationId: string;+ traceId: string;+ startTime: Date;+ shouldReadFromObservationsTable?: boolean;+}): Promise<CodeEvalTestRunResult> {+ const observation = await getObservationForEvalById({+ projectId: params.projectId,+ id: params.observationId,+ traceId: params.traceId,+ startTime: params.startTime,+ shouldReadFromObservationsTable: params.shouldReadFromObservationsTable,+ });++ return runCodeEvalTestForObservation({+ ...params,+ observation,+ });+}++export async function runCodeEvalTestForJobConfig(params: {+ prisma: PrismaClient;+ orgId: string;+ projectId: string;+ evalTemplateId: string;+ target: EvalTargetObject;+ mapping: ObservationVariableMapping[];+ scoreName: string;+ filter: FilterCondition[] | null;+}): Promise<CodeEvalTestRunResult> {+ const observation = await getObservationForEvalByFilter({+ projectId: params.projectId,+ target: params.target,+ filter: params.filter,+ });++ return runCodeEvalTestForObservation({+ ...params,+ observation,+ });+}++async function runCodeEvalTestForObservation(params: {+ prisma: PrismaClient;+ orgId: string;+ projectId: string;+ evalTemplateId: string;+ target: EvalTargetObject;+ mapping: ObservationVariableMapping[];+ scoreName: string;+ observation: ObservationForEval;+}): Promise<CodeEvalTestRunResult> {+ const dispatcher = resolveConfiguredCodeEvalDispatcher();++ if (!dispatcher) {+ throw new TRPCError({+ code: "PRECONDITION_FAILED",+ message: "Code eval dispatcher is not configured",+ });+ }++ const codeTemplate = (await params.prisma.evalTemplate.findFirst({+ where: {+ id: params.evalTemplateId,+ type: EvalTemplateType.CODE,+ sourceCode: { not: null },+ sourceCodeLanguage: { not: null },+ OR: [{ projectId: params.projectId }, { projectId: null }],+ },+ })) as EvalTemplateCodeBased | null;++ if (!codeTemplate) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Evaluator template not found",+ });+ }++ const extractedVariables = extractObservationVariables({+ observation: params.observation,+ variableMapping: params.mapping,+ });+ const executionTraceId = createW3CTraceId();+ const traceName = `Test evaluator: ${codeTemplate.name}`;+ const executionMetadata = {+ dispatcher_name: dispatcher.name,+ code_eval_runtime: codeTemplate.sourceCodeLanguage,+ eval_template_id: codeTemplate.id,+ eval_template_version: codeTemplate.version,+ score_name: params.scoreName,+ target_object: params.target,+ target_trace_id: params.observation.trace_id,+ target_observation_id: params.observation.span_id,+ };++ const dispatchOutcome = await runCodeBasedEvaluationDispatch({+ dispatcher,+ organizationId: params.orgId,+ projectId: params.projectId,+ executionTraceId,+ jobExecutionId: executionTraceId,+ template: codeTemplate,+ extractedVariables,+ hasExperimentContext: Boolean(params.observation.experiment_id),+ traceName,+ metadata: executionMetadata,+ writeTrace: writeTraceViaIngestion,+ });++ if (dispatchOutcome.success) {+ return {+ success: true,+ result: dispatchOutcome.result,+ executionTraceId: dispatchOutcome.executionTraceId,+ executionTraceFromTimestamp: dispatchOutcome.executionTraceFromTimestamp,+ };+ }++ return {+ success: false,+ error: {+ code: dispatchOutcome.error.code,+ message: dispatchOutcome.error.message,+ },+ executionTraceId: dispatchOutcome.executionTraceId,+ executionTraceFromTimestamp: dispatchOutcome.executionTraceFromTimestamp,+ };+}++async function getObservationForEvalByFilter(params: {+ projectId: string;+ target: EvalTargetObject;+ filter: FilterCondition[] | null;+}): Promise<ObservationForEval> {+ if (!isEventTarget(params.target) && !isExperimentTarget(params.target)) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Code evaluators can only run on observations or experiments.",+ });+ }++ const filter = isExperimentTarget(params.target)+ ? getExperimentEvalPreviewFilters(params.filter)+ : params.filter;++ const stream = await getEventsStreamForEval({+ projectId: params.projectId,+ filter,+ rowLimit: 1,+ });++ for await (const row of stream) {+ return observationForEvalSchema.parse(row);+ }++ throw new TRPCError({+ code: "PRECONDITION_FAILED",+ message:+ "No matching observation found to test this code evaluator. Adjust the filters and try again.",+ });+}++async function getObservationForEvalById(params: {+ projectId: string;+ id: string;+ traceId: string;+ startTime: Date;+ shouldReadFromObservationsTable?: boolean;+}): Promise<ObservationForEval> {+ if (+ env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS !== "true" ||+ params.shouldReadFromObservationsTable+ ) {+ return getObservationForEvalByIdFromLegacyObservations(params);+ }++ const startTimeUpperBound = new Date(params.startTime.getTime() + 1);++ const stream = await getEventsStreamForEval({+ projectId: params.projectId,+ filter: [+ {+ type: "string",+ column: "traceId",+ operator: "=",+ value: params.traceId,+ },+ {+ type: "datetime",+ column: "startTime",+ operator: ">=",+ value: params.startTime,+ },+ {+ type: "datetime",+ column: "startTime",+ operator: "<",+ value: startTimeUpperBound,+ },+ {+ type: "stringOptions",+ column: "id",+ operator: "any of",+ value: [params.id],+ },+ ],+ rowLimit: 1,+ });++ for await (const row of stream) {+ return observationForEvalSchema.parse(row);+ }++ throwObservationNotFound();+}++async function getObservationForEvalByIdFromLegacyObservations(params: {+ projectId: string;+ id: string;+ traceId: string;+ startTime: Date;+}): Promise<ObservationForEval> {+ const observation = await getObservationById({+ projectId: params.projectId,+ id: params.id,+ traceId: params.traceId,+ startTime: params.startTime,+ fetchWithInputOutput: true,+ }).catch((error) => {+ if (error instanceof LangfuseNotFoundError) {+ throwObservationNotFound();+ }++ throw error;+ });++ if (!observation) {+ throwObservationNotFound();+ }++ return observationForEvalSchema.parse({+ span_id: observation.id,+ trace_id: observation.traceId,+ project_id: params.projectId,+ parent_span_id: observation.parentObservationId,+ type: observation.type,+ name: observation.name ?? "",+ environment: observation.environment ?? DEFAULT_TRACE_ENVIRONMENT,+ version: observation.version,+ level: observation.level,+ status_message: observation.statusMessage,+ trace_name: null,+ user_id: null,+ session_id: null,+ tags: [],+ release: null,+ provided_model_name: observation.model,+ model_parameters: observation.modelParameters,+ prompt_id: observation.promptId,+ prompt_name: observation.promptName,+ prompt_version: observation.promptVersion,+ provided_usage_details: observation.providedUsageDetails ?? {},+ provided_cost_details: observation.providedCostDetails ?? {},+ usage_details: observation.usageDetails ?? {},+ cost_details: observation.costDetails ?? {},+ tool_definitions: observation.toolDefinitions ?? {},+ tool_calls: observation.toolCalls ?? [],+ tool_call_names: observation.toolCallNames ?? [],+ tool_call_count: observation.toolCallNames?.length ?? 0,+ experiment_id: null,+ experiment_name: null,+ experiment_description: null,+ experiment_dataset_id: null,+ experiment_item_id: null,+ experiment_item_expected_output: null,+ experiment_item_metadata: null,+ experiment_item_root_span_id: null,+ input: observation.input,+ output: observation.output,+ metadata: observation.metadata,+ });+}++function throwObservationNotFound(): never {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Observation not found",+ });+}++async function writeTraceViaIngestion(trace: InternalTraceWriteInput) {+ const rootEventInput =+ trace.eventInputs.find(+ (eventInput) => eventInput.spanId === trace.rootSpanId,+ ) ?? trace.eventInputs[0];++ if (!rootEventInput) return;++ const timestamp = new Date().toISOString();+ const traceEvent = {+ id: randomUUID(),+ type: eventTypes.TRACE_CREATE,+ timestamp,+ body: {+ id: rootEventInput.traceId,+ timestamp: rootEventInput.startTimeISO,+ name: rootEventInput.traceName ?? rootEventInput.name,+ environment: getInternalEvalEnvironment(rootEventInput.environment),+ input: rootEventInput.input,+ output: rootEventInput.output,+ metadata: rootEventInput.metadata,+ release: rootEventInput.release,+ version: rootEventInput.version,+ public: rootEventInput.public,+ tags: rootEventInput.tags,+ sessionId: rootEventInput.sessionId,+ userId: rootEventInput.userId,+ },+ };++ const spanEvents = trace.eventInputs.map((eventInput) => ({+ id: randomUUID(),+ type: eventTypes.SPAN_CREATE,+ timestamp,+ body: {+ id: eventInput.spanId,+ traceId: eventInput.traceId,+ name: eventInput.name,+ environment: getInternalEvalEnvironment(eventInput.environment),+ startTime: eventInput.startTimeISO,+ endTime: eventInput.endTimeISO,+ input: eventInput.input,+ output: eventInput.output,+ metadata: eventInput.metadata,+ level: eventInput.level,+ statusMessage: eventInput.statusMessage,+ parentObservationId: eventInput.parentSpanId,+ version: eventInput.version,+ },+ }));++ const result = await processEventBatch(+ [traceEvent, ...spanEvents],+ {+ validKey: true,+ scope: {+ projectId: rootEventInput.projectId,+ accessLevel: "project",+ },+ } satisfies Parameters<typeof processEventBatch>[1],+ { delay: 0, isLangfuseInternal: true },+ );++ if (result.errors.length > 0) {+ throw new Error(result.errors[0]?.error ?? "Failed to write trace");+ }+}++function getInternalEvalEnvironment(environment: string | undefined) {+ return environment === LangfuseInternalTraceEnvironment.CodeEval+ ? LangfuseInternalTraceEnvironment.CodeEval+ : LangfuseInternalTraceEnvironment.LLMJudge;+}diff --git a/web/src/features/evals/server/defaultEvalModelRouter.ts b/web/src/features/evals/server/defaultEvalModelRouter.tsindex a557d7d194..427e2ffdc6 100644--- a/web/src/features/evals/server/defaultEvalModelRouter.ts+++ b/web/src/features/evals/server/defaultEvalModelRouter.ts@@ -4,6 +4,7 @@ import {protectedProjectProcedure,} from "@/src/server/api/trpc";import { z } from "zod";+import { findDefaultModelEvalTemplateIds } from "./defaultModelEvalTemplateRepository";import {EvaluatorBlockReason,ZodModelConfig,@@ -57,15 +58,9 @@ export const defaultEvalModelRouter = createTRPCRouter({});const result = await ctx.prisma.$transaction(async (tx) => {- const evalTemplates = await tx.evalTemplate.findMany({- where: {- OR: [{ projectId: input.projectId }, { projectId: null }],- provider: null,- model: null,- },- select: {- id: true,- },+ const evalTemplateIds = await findDefaultModelEvalTemplateIds({+ tx,+ projectId: input.projectId,});const blockResult = await blockEvaluatorConfigsInTx({@@ -73,7 +68,7 @@ export const defaultEvalModelRouter = createTRPCRouter({projectId: input.projectId,where: {evalTemplateId: {- in: evalTemplates.map((template) => template.id),+ in: evalTemplateIds,},},blockReason: EvaluatorBlockReason.DEFAULT_EVAL_MODEL_MISSING,diff --git a/web/src/features/evals/server/defaultModelEvalTemplateRepository.ts b/web/src/features/evals/server/defaultModelEvalTemplateRepository.tsnew file mode 100644index 0000000000..2c1238618c--- /dev/null+++ b/web/src/features/evals/server/defaultModelEvalTemplateRepository.ts@@ -0,0 +1,23 @@+import { EvalTemplateType, type Prisma } from "@langfuse/shared/src/db";++export async function findDefaultModelEvalTemplateIds({+ tx,+ projectId,+}: {+ tx: Prisma.TransactionClient;+ projectId: string;+}) {+ const evalTemplates = await tx.evalTemplate.findMany({+ where: {+ OR: [{ projectId }, { projectId: null }],+ provider: null,+ model: null,+ type: EvalTemplateType.LLM_AS_JUDGE,+ },+ select: {+ id: true,+ },+ });++ return evalTemplates.map((template) => template.id);+}diff --git a/web/src/features/evals/server/evalTemplateCreation.ts b/web/src/features/evals/server/evalTemplateCreation.tsnew file mode 100644index 0000000000..1d9df0fad5--- /dev/null+++ b/web/src/features/evals/server/evalTemplateCreation.ts@@ -0,0 +1,150 @@+import { z } from "zod";+import {+ compilePersistedEvalOutputDefinition,+ EvalTemplateSourceCodeLanguage,+ EvalTemplateType,+ PersistedEvalOutputDefinitionSchema,+ ZodModelConfig,+} from "@langfuse/shared";+import {+ CODE_EVAL_SOURCE_MAX_BYTES,+ DefaultEvalModelService,+ testModelCall,+} from "@langfuse/shared/src/server";+import { TRPCError } from "@trpc/server";+import { assertUnreachable } from "@/src/utils/types";+import { EvalReferencedEvaluators } from "@/src/features/evals/types";+import { isCodeEvalEnabled } from "@/src/features/evals/server/isCodeEvalEnabled";++export const CODE_EVAL_TEMPLATE_VARIABLES = [+ "input",+ "output",+ "metadata",+ "experimentItemExpectedOutput",+ "experimentItemMetadata",+] as const;++const CreateEvalTemplateBaseInputSchema = z.object({+ name: z.string().min(1),+ projectId: z.string(),+ cloneSourceId: z.string().optional(),+ referencedEvaluators: z+ .enum(EvalReferencedEvaluators)+ .optional()+ .default(EvalReferencedEvaluators.PERSIST),+});++const CreateLlmAsJudgeEvalTemplateInputSchema =+ CreateEvalTemplateBaseInputSchema.extend({+ type: z.literal(EvalTemplateType.LLM_AS_JUDGE),+ prompt: z.string(),+ provider: z.string().nullish(),+ model: z.string().nullish(),+ modelParams: ZodModelConfig.nullish(),+ vars: z.array(z.string()),+ outputDefinition: PersistedEvalOutputDefinitionSchema,+ });++const CreateLegacyLlmAsJudgeEvalTemplateInputSchema =+ CreateEvalTemplateBaseInputSchema.extend({+ type: z.undefined().optional(),+ prompt: z.string(),+ provider: z.string().nullish(),+ model: z.string().nullish(),+ modelParams: ZodModelConfig.nullish(),+ vars: z.array(z.string()),+ outputDefinition: PersistedEvalOutputDefinitionSchema,+ }).transform((input) => ({+ ...input,+ type: EvalTemplateType.LLM_AS_JUDGE,+ }));++const CreateCodeEvalTemplateInputSchema =+ CreateEvalTemplateBaseInputSchema.extend({+ type: z.literal(EvalTemplateType.CODE),+ sourceCode: z+ .string()+ .min(1)+ .refine(+ (sourceCode) =>+ Buffer.byteLength(sourceCode, "utf8") <= CODE_EVAL_SOURCE_MAX_BYTES,+ {+ message: `Source code must be ${CODE_EVAL_SOURCE_MAX_BYTES} bytes or less`,+ },+ ),+ sourceCodeLanguage: z.enum([+ EvalTemplateSourceCodeLanguage.PYTHON,+ EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ ]),+ });++const CreateTypedEvalTemplateInputSchema = z.discriminatedUnion("type", [+ CreateLlmAsJudgeEvalTemplateInputSchema,+ CreateCodeEvalTemplateInputSchema,+]);++export const CreateEvalTemplateInputSchema = z.union([+ CreateTypedEvalTemplateInputSchema,+ CreateLegacyLlmAsJudgeEvalTemplateInputSchema,+]);++type CreateEvalTemplateInput = z.infer<typeof CreateEvalTemplateInputSchema>;+type CreateLlmAsJudgeEvalTemplateInput = z.infer<+ typeof CreateLlmAsJudgeEvalTemplateInputSchema+>;++async function validateLlmAsJudgeTemplateModel(+ input: CreateLlmAsJudgeEvalTemplateInput,+) {+ const modelConfig = await DefaultEvalModelService.fetchValidModelConfig(+ input.projectId,+ input.provider ?? undefined,+ input.model ?? undefined,+ input.modelParams,+ );++ if (!modelConfig.valid) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "No valid llm model found for this project",+ });+ }++ try {+ await testModelCall({+ provider: modelConfig.config.provider,+ model: modelConfig.config.model,+ apiKey: modelConfig.config.apiKey,+ modelConfig: input.modelParams,+ structuredOutputSchema: compilePersistedEvalOutputDefinition(+ input.outputDefinition,+ ).outputResultSchema,+ });+ } catch (err) {+ const message = err instanceof Error ? err.message : "Unknown error";+ throw new TRPCError({+ code: "PRECONDITION_FAILED",+ message: `Model configuration not valid for evaluation. ${message}`,+ });+ }+}++export async function validateEvalTemplateCreation(+ input: CreateEvalTemplateInput,+) {+ switch (input.type) {+ case EvalTemplateType.LLM_AS_JUDGE:+ await validateLlmAsJudgeTemplateModel(input);+ return;+ case EvalTemplateType.CODE:+ if (!isCodeEvalEnabled()) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "Code evals are not enabled",+ });+ }+ return;+ default:+ assertUnreachable(input);+ }+}diff --git a/web/src/features/evals/server/evaluator-preflight.ts b/web/src/features/evals/server/evaluator-preflight.tsindex d2b4c874ec..a297c5506b 100644--- a/web/src/features/evals/server/evaluator-preflight.ts+++ b/web/src/features/evals/server/evaluator-preflight.ts@@ -1,5 +1,6 @@import {compilePersistedEvalOutputDefinition,+ EvalTemplateType,PersistedEvalOutputDefinitionSchema,} from "@langfuse/shared";import {@@ -9,6 +10,7 @@ import {export type EvaluatorPreflightDefinition = {name: string;+ type?: EvalTemplateType | null;provider?: string | null;model?: string | null;modelParams?: unknown;@@ -19,6 +21,10 @@ export async function getEvaluatorDefinitionPreflightError(params: {projectId: string;template: EvaluatorPreflightDefinition;}): Promise<string | null> {+ if (params.template.type === EvalTemplateType.CODE) {+ return null;+ }+const modelConfig = await DefaultEvalModelService.fetchValidModelConfig(params.projectId,params.template.provider ?? undefined,diff --git a/web/src/features/evals/server/isCodeEvalEnabled.ts b/web/src/features/evals/server/isCodeEvalEnabled.tsnew file mode 100644index 0000000000..acc2777432--- /dev/null+++ b/web/src/features/evals/server/isCodeEvalEnabled.ts@@ -0,0 +1,5 @@+import { env } from "@/src/env.mjs";++export function isCodeEvalEnabled(): boolean {+ return env.NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED === "true";+}diff --git a/web/src/features/evals/server/router.ts b/web/src/features/evals/server/router.tsindex e2fcdd7c90..0907a9767e 100644--- a/web/src/features/evals/server/router.ts+++ b/web/src/features/evals/server/router.ts@@ -7,9 +7,6 @@ import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAcimport { auditLog } from "@/src/features/audit-logs/auditLog";import {DEFAULT_TRACE_JOB_DELAY,- ZodModelConfig,- PersistedEvalOutputDefinitionSchema,- compilePersistedEvalOutputDefinition,deriveEvaluatorDisplayStateFromExecutionCounts,type OrderByState,singleFilter,@@ -29,6 +26,8 @@ import {EvalTargetObjectSchema,validateEvaluatorFiltersForTarget,InvalidRequestError,+ EvalTemplateType,+ type EvalTemplateSourceCodeLanguage,} from "@langfuse/shared";import {getQueue,@@ -41,15 +40,13 @@ import {QueueJobs,tableColumnsToSqlFilterAndPrefix,orderByToPrismaSql,- DefaultEvalModelService,- testModelCall,invalidateProjectEvalConfigCaches,} from "@langfuse/shared/src/server";import { TRPCError } from "@trpc/server";import { EvalReferencedEvaluators } from "@/src/features/evals/types";import { EvaluatorStatus } from "../types";import { traceException } from "@langfuse/shared/src/server";-import { isNotNullOrUndefined } from "@/src/utils/types";+import { assertUnreachable, isNotNullOrUndefined } from "@/src/utils/types";import { v4 as uuidv4 } from "uuid";import { env } from "@/src/env.mjs";import { type JobExecution, type PrismaClient } from "@prisma/client";@@ -68,6 +65,17 @@ import {JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE,} from "@/src/features/evals/server/audit-log-resource-types";import { getEvaluatorDefinitionPreflightError } from "@/src/features/evals/server/evaluator-preflight";+import {+ runCodeEvalTest,+ runCodeEvalTestForJobConfig,+} from "@/src/features/evals/server/codeEvalTestRun";+import {+ CODE_EVAL_TEMPLATE_VARIABLES,+ CreateEvalTemplateInputSchema,+ validateEvalTemplateCreation,+} from "@/src/features/evals/server/evalTemplateCreation";+import { isCodeEvalEnabled } from "@/src/features/evals/server/isCodeEvalEnabled";+export { CreateEvalTemplateInputSchema } from "@/src/features/evals/server/evalTemplateCreation";// Filter columns that used to be backed by the Postgres `traces` and// `scores` JOINs. Those tables now live in ClickHouse, so the eval logs@@ -105,13 +113,14 @@ const ConfigWithTemplateSchema = z.object({createdAt: z.coerce.date(),updatedAt: z.coerce.date(),projectId: z.string().nullable(),- prompt: z.string(),+ prompt: z.string().nullable(),provider: z.string().nullable(),model: z.string().nullable(),modelParams: jsonSchema.nullable(),vars: z.array(z.string()),- outputDefinition: jsonSchema,+ outputDefinition: jsonSchema.nullable(),version: z.number(),+ type: z.enum(EvalTemplateType),}).nullish(),});@@ -139,22 +148,6 @@ const filterAndValidateDbEvaluatorList = (return acc;}, [] as EvalJobConfigWithTemplate[]);-export const CreateEvalTemplateInputSchema = z.object({- name: z.string().min(1),- projectId: z.string(),- prompt: z.string(),- provider: z.string().nullish(),- model: z.string().nullish(),- modelParams: ZodModelConfig.nullish(),- vars: z.array(z.string()),- outputDefinition: PersistedEvalOutputDefinitionSchema,- cloneSourceId: z.string().optional(),- referencedEvaluators: z- .enum(EvalReferencedEvaluators)- .optional()- .default(EvalReferencedEvaluators.PERSIST),-});-const CreateEvalJobSchema = z.object({projectId: z.string(),evalTemplateId: z.string(),@@ -172,6 +165,21 @@ const CreateEvalJobSchema = z.object({status: z.enum(EvaluatorStatus).optional().default(JobConfigState.ACTIVE),});+const CodeEvalTestRunSchema = z.object({+ projectId: z.string(),+ evalTemplateId: z.string(),+ target: z.union([+ z.literal(EvalTargetObject.EVENT),+ z.literal(EvalTargetObject.EXPERIMENT),+ ]),+ mapping: z.array(observationVariableMapping),+ scoreName: z.string().min(1),+ observationId: z.string(),+ traceId: z.string(),+ startTime: z.coerce.date(),+ shouldReadFromObservationsTable: z.boolean().optional().default(false),+});+const UpdateEvalJobSchema = z.object({scoreName: z.string().min(1).optional(),filter: z.array(singleFilter).optional(),@@ -238,6 +246,7 @@ const validateEvalTemplateCanRun = async ({projectId,template: {name: template.name,+ type: template.type,provider: template.provider,model: template.model,modelParams: template.modelParams,@@ -253,6 +262,63 @@ const validateEvalTemplateCanRun = async ({}};+const assertCodeEvalJobConfigTestSucceeds = async ({+ prisma,+ orgId,+ projectId,+ evalTemplateId,+ target,+ mapping,+ scoreName,+ filter,+}: {+ prisma: PrismaClient;+ orgId: string;+ projectId: string;+ evalTemplateId: string;+ target: EvalTargetObject;+ mapping: unknown;+ scoreName: string;+ filter: z.infer<typeof singleFilter>[] | null;+}) => {+ if (+ target !== EvalTargetObject.EVENT &&+ target !== EvalTargetObject.EXPERIMENT+ ) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Code evaluators can only run on observations or experiments.",+ });+ }++ const parsedMapping = z.array(observationVariableMapping).parse(mapping);++ if (env.LANGFUSE_ENABLE_EVENTS_TABLE_UI === "true") {+ const result = await runCodeEvalTestForJobConfig({+ prisma,+ orgId,+ projectId,+ evalTemplateId,+ target,+ mapping: parsedMapping,+ scoreName,+ filter,+ });++ if (!result.success) {+ throw new TRPCError({+ code: "PRECONDITION_FAILED",+ message: result.error.message,+ });+ }+ } else if (target === EvalTargetObject.EXPERIMENT) {+ return;+ } else {+ // TODO: add self-hosting path for target events+ return;+ }+};+export const evalRouter = createTRPCRouter({globalJobConfigs: protectedProjectProcedure.input(z.object({ projectId: z.string() }))@@ -481,6 +547,9 @@ export const evalRouter = createTRPCRouter({...(input.isUserManaged? { projectId: input.projectId }: { projectId: null }),+ ...(isCodeEvalEnabled()+ ? {}+ : { type: { not: EvalTemplateType.CODE } }),},orderBy: [{ version: "desc" }],});@@ -510,6 +579,9 @@ export const evalRouter = createTRPCRouter({input.searchQuery && input.searchQuery.trim() !== ""? Prisma.sql`AND name ILIKE ${`%${input.searchQuery}%`}`: Prisma.empty;+ const typeCondition = isCodeEvalEnabled()+ ? Prisma.empty+ : Prisma.sql`AND type != ${EvalTemplateType.CODE}::"EvalTemplateType"`;const [templates, count] = await Promise.all([ctx.prisma.$queryRaw<@@ -523,6 +595,8 @@ export const evalRouter = createTRPCRouter({partner?: string;provider?: string;model?: string;+ type: EvalTemplateType;+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage | null;outputDefinition: unknown;}>>`@@ -533,6 +607,8 @@ export const evalRouter = createTRPCRouter({et.project_id,et.provider,et.model,+ et.type,+ et.source_code_language,et.partner,et.version,et.created_at,@@ -544,16 +620,18 @@ export const evalRouter = createTRPCRouter({SELECT idFROM eval_templatesWHERE name = et.name AND+ type = et.type AND(project_id = et.project_id OR (project_id IS NULL AND et.project_id IS NULL)))AND jc.project_id = ${input.projectId}) as usage_countFROM (- SELECT DISTINCT ON (project_id, name) *+ SELECT DISTINCT ON (project_id, name, type) *FROM eval_templatesWHERE (project_id = ${input.projectId} OR project_id IS NULL)${searchCondition}- ORDER BY project_id, name, version DESC+ ${typeCondition}+ ORDER BY project_id, name, type, version DESC) et)SELECT@@ -561,6 +639,8 @@ export const evalRouter = createTRPCRouter({name,provider,model,+ type,+ source_code_language as "sourceCodeLanguage",partner,project_id as "projectId",version,@@ -569,17 +649,18 @@ export const evalRouter = createTRPCRouter({COALESCE(usage_count, 0)::int as "usageCount"FROMlatest_templates- ORDER BY project_id, partner, name+ ORDER BY project_id, partner, name, typeLIMIT ${input.limit}OFFSET ${input.page * input.limit}`,ctx.prisma.$queryRaw<Array<{ count: bigint }>>`SELECT COUNT(*) as countFROM (- SELECT DISTINCT project_id, name+ SELECT DISTINCT project_id, name, typeFROM eval_templatesWHERE (project_id = ${input.projectId} OR project_id IS NULL)${searchCondition}+ ${typeCondition}) t`,]);@@ -608,6 +689,9 @@ export const evalRouter = createTRPCRouter({where: {id: input.id,OR: [{ projectId: input.projectId }, { projectId: null }],+ ...(isCodeEvalEnabled()+ ? {}+ : { type: { not: EvalTemplateType.CODE } }),},});@@ -633,6 +717,9 @@ export const evalRouter = createTRPCRouter({where: {OR: [{ projectId: input.projectId }, { projectId: null }],...(input.id ? { id: input.id } : undefined),+ ...(isCodeEvalEnabled()+ ? {}+ : { type: { not: EvalTemplateType.CODE } }),},...(input.limit && input.page? { take: input.limit, skip: input.page * input.limit }@@ -643,6 +730,9 @@ export const evalRouter = createTRPCRouter({where: {OR: [{ projectId: input.projectId }, { projectId: null }],...(input.id ? { id: input.id } : undefined),+ ...(isCodeEvalEnabled()+ ? {}+ : { type: { not: EvalTemplateType.CODE } }),},});return {@@ -763,6 +853,12 @@ export const evalRouter = createTRPCRouter({);throw new Error("Template not found");}+ if (evalTemplate.type === EvalTemplateType.CODE && !isCodeEvalEnabled()) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "Code evals are not enabled",+ });+ }const variableMappingForTarget = validateVariableMappingForTarget({targetObject: input.target,@@ -780,6 +876,19 @@ export const evalRouter = createTRPCRouter({}const validatedFilter = filterValidation.validatedFilters;+ if (evalTemplate.type === EvalTemplateType.CODE) {+ await assertCodeEvalJobConfigTestSucceeds({+ prisma: ctx.prisma,+ orgId: ctx.session.orgId,+ projectId: input.projectId,+ evalTemplateId: input.evalTemplateId,+ target: input.target,+ mapping: variableMappingForTarget,+ scoreName: input.scoreName,+ filter: validatedFilter ?? [],+ });+ }+const jobId = uuidv4();await auditLog({session: ctx.session,@@ -852,47 +961,51 @@ export const evalRouter = createTRPCRouter({return { id: job.id };}),- createTemplate: protectedProjectProcedure- .input(CreateEvalTemplateInputSchema)+ testRunCodeEval: protectedProjectProcedure+ .input(CodeEvalTestRunSchema).mutation(async ({ input, ctx }) => {throwIfNoProjectAccess({session: ctx.session,projectId: input.projectId,- scope: "evalTemplate:CUD",+ scope: "evalJob:CUD",});- const modelConfig = await DefaultEvalModelService.fetchValidModelConfig(- input.projectId,- input.provider ?? undefined,- input.model ?? undefined,- input.modelParams,- );-- if (!modelConfig.valid) {+ if (!isCodeEvalEnabled()) {throw new TRPCError({- code: "NOT_FOUND",- message: "No valid llm model found for this project",+ code: "FORBIDDEN",+ message: "Code evals are not enabled",});}- try {- // Make a test structured output call to validate the LLM key- await testModelCall({- provider: modelConfig.config.provider,- model: modelConfig.config.model,- apiKey: modelConfig.config.apiKey,- modelConfig: input.modelParams,- structuredOutputSchema: compilePersistedEvalOutputDefinition(- input.outputDefinition,- ).outputResultSchema,- });- } catch (err) {- const message = err instanceof Error ? err.message : "Unknown error";- throw new TRPCError({- code: "PRECONDITION_FAILED",- message: `Model configuration not valid for evaluation. ${message}`,- });- }+ validateVariableMappingForTarget({+ targetObject: input.target,+ mapping: input.mapping,+ });++ return runCodeEvalTest({+ prisma: ctx.prisma,+ orgId: ctx.session.orgId,+ projectId: input.projectId,+ evalTemplateId: input.evalTemplateId,+ target: input.target,+ mapping: input.mapping,+ scoreName: input.scoreName,+ observationId: input.observationId,+ traceId: input.traceId,+ startTime: input.startTime,+ shouldReadFromObservationsTable: input.shouldReadFromObservationsTable,+ });+ }),+ createTemplate: protectedProjectProcedure+ .input(CreateEvalTemplateInputSchema)+ .mutation(async ({ input, ctx }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "evalTemplate:CUD",+ });++ await validateEvalTemplateCreation(input);/*** CREATION OF PROJECT-LEVEL TEMPLATE@@ -913,11 +1026,13 @@ export const evalRouter = createTRPCRouter({where: {projectId: input.projectId,name: input.name,+ type: input.type,},orderBy: [{ version: "desc" }],select: {id: true,version: true,+ type: true,},});@@ -925,23 +1040,51 @@ export const evalRouter = createTRPCRouter({const latestTemplate = Boolean(templates.length)? templates[0]: undefined;+ const baseTemplateData = {+ version: (latestTemplate?.version ?? 0) + 1,+ name: input.name,+ projectId: input.projectId,+ };// Create a new project-level template either by cloning a langfuse managed template or by creating a new project-level template- const evalTemplate = await tx.evalTemplate.create({- data: {- version: (latestTemplate?.version ?? 0) + 1,- name: input.name,- projectId: input.projectId,- prompt: input.prompt,- // if using default model, leave model, provider and modelParams empty- // otherwise we will not pull the most recent default evaluation model- provider: input.provider,- model: input.model,- modelParams: input.modelParams ?? undefined,- vars: input.vars,- outputDefinition: input.outputDefinition,- },- });+ const evalTemplate = await (async () => {+ switch (input.type) {+ case EvalTemplateType.CODE:+ return tx.evalTemplate.create({+ data: {+ ...baseTemplateData,+ type: EvalTemplateType.CODE,+ prompt: null,+ provider: null,+ model: null,+ modelParams: undefined,+ vars: [...CODE_EVAL_TEMPLATE_VARIABLES],+ outputDefinition: undefined,+ sourceCode: input.sourceCode,+ sourceCodeLanguage: input.sourceCodeLanguage,+ },+ });+ case EvalTemplateType.LLM_AS_JUDGE:+ return tx.evalTemplate.create({+ data: {+ ...baseTemplateData,+ type: EvalTemplateType.LLM_AS_JUDGE,+ prompt: input.prompt,+ // if using default model, leave model, provider and modelParams empty+ // otherwise we will not pull the most recent default evaluation model+ provider: input.provider,+ model: input.model,+ modelParams: input.modelParams ?? undefined,+ vars: input.vars,+ outputDefinition: input.outputDefinition,+ sourceCode: null,+ sourceCodeLanguage: null,+ },+ });+ default:+ return assertUnreachable(input);+ }+ })();/*** END OF CREATION OF PROJECT-LEVEL TEMPLATE@@ -975,12 +1118,19 @@ export const evalRouter = createTRPCRouter({message: "Langfuse managed template not found",});}+ if (cloneSourceTemplate.type !== input.type) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Evaluator type cannot be changed.",+ });+ }// find all versions of the langfuse managed templateconst cloneSourceTemplateList = await tx.evalTemplate.findMany({where: {projectId: null,name: cloneSourceTemplate.name,+ type: cloneSourceTemplate.type,},});@@ -1138,6 +1288,9 @@ export const evalRouter = createTRPCRouter({id: evalConfigId,projectId: projectId,},+ include: {+ evalTemplate: true,+ },});if (!existingJob) {@@ -1210,6 +1363,27 @@ export const evalRouter = createTRPCRouter({}const validatedFilter = filterValidation.validatedFilters;+ if (existingJob.evalTemplate?.type === EvalTemplateType.CODE) {+ if (!isCodeEvalEnabled()) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "Code evals are not enabled",+ });+ }++ await assertCodeEvalJobConfigTestSucceeds({+ prisma: ctx.prisma,+ orgId: ctx.session.orgId,+ projectId,+ evalTemplateId: existingJob.evalTemplate.id,+ target: existingJob.targetObject as EvalTargetObject,+ mapping:+ validatedConfig.variableMapping ?? existingJob.variableMapping,+ scoreName: config.scoreName ?? existingJob.scoreName,+ filter: validatedFilter ?? [],+ });+ }+await auditLog({session: ctx.session,resourceType: JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE,diff --git a/web/src/features/evals/server/unstable-public-api/adapters.ts b/web/src/features/evals/server/unstable-public-api/adapters.tsindex 3ce17c7c66..26d5ee65ef 100644--- a/web/src/features/evals/server/unstable-public-api/adapters.ts+++ b/web/src/features/evals/server/unstable-public-api/adapters.ts@@ -112,7 +112,7 @@ export function deriveEvaluatorVariables(}export function parseStoredOutputDefinition(- template: Pick<StoredPublicEvaluatorTemplate, "outputDefinition">,+ template: Pick<StoredPublicEvaluatorTemplate, "id" | "outputDefinition">,): PublicEvaluatorOutputDefinitionType {const parsed = PersistedEvalOutputDefinitionSchema.safeParse(template.outputDefinition,diff --git a/web/src/features/evals/server/unstable-public-api/evaluation-rule-service.ts b/web/src/features/evals/server/unstable-public-api/evaluation-rule-service.tsindex 9af66d4de6..a40d5e4139 100644--- a/web/src/features/evals/server/unstable-public-api/evaluation-rule-service.ts+++ b/web/src/features/evals/server/unstable-public-api/evaluation-rule-service.ts@@ -1,5 +1,5 @@import { invalidateProjectEvalConfigCaches } from "@langfuse/shared/src/server";-import { prisma } from "@langfuse/shared/src/db";+import { EvalTemplateType, prisma } from "@langfuse/shared/src/db";import { EvalTargetObject, JobConfigState } from "@langfuse/shared";import type {PatchUnstableEvaluationRuleBodyType,@@ -79,6 +79,12 @@ export async function createPublicEvaluationRule(params: {in: [EvalTargetObject.EVENT, EvalTargetObject.EXPERIMENT],},scoreName: params.input.name,+ evalTemplate: {+ is: {+ type: EvalTemplateType.LLM_AS_JUDGE,+ OR: [{ projectId: params.projectId }, { projectId: null }],+ },+ },},select: {id: true,@@ -156,8 +162,6 @@ export async function createPublicEvaluationRule(params: {id: true,projectId: true,name: true,- vars: true,- prompt: true,},},},@@ -270,8 +274,6 @@ export async function updatePublicEvaluationRule(params: {id: true,projectId: true,name: true,- vars: true,- prompt: true,},},},diff --git a/web/src/features/evals/server/unstable-public-api/evaluator-service.ts b/web/src/features/evals/server/unstable-public-api/evaluator-service.tsindex 2d811354d2..b1fdbc585e 100644--- a/web/src/features/evals/server/unstable-public-api/evaluator-service.ts+++ b/web/src/features/evals/server/unstable-public-api/evaluator-service.ts@@ -6,7 +6,7 @@ import {variableMappingList,} from "@langfuse/shared";import { invalidateProjectEvalConfigCaches } from "@langfuse/shared/src/server";-import { Prisma, prisma } from "@langfuse/shared/src/db";+import { EvalTemplateType, Prisma, prisma } from "@langfuse/shared/src/db";import type { PostUnstableEvaluatorBodyType } from "@/src/features/public-api/types/unstable-evaluators";import {toApiEvaluator,@@ -130,6 +130,7 @@ export async function createPublicEvaluator(params: {where: {projectId: params.projectId,name: params.input.name,+ type: EvalTemplateType.LLM_AS_JUDGE,},orderBy: [{@@ -158,6 +159,11 @@ export async function createPublicEvaluator(params: {(existingTemplate) => existingTemplate.id,),},+ evalTemplate: {+ is: {+ type: EvalTemplateType.LLM_AS_JUDGE,+ },+ },},select: {id: true,diff --git a/web/src/features/evals/server/unstable-public-api/queries.ts b/web/src/features/evals/server/unstable-public-api/queries.tsindex 8476f3f542..46c353ec85 100644--- a/web/src/features/evals/server/unstable-public-api/queries.ts+++ b/web/src/features/evals/server/unstable-public-api/queries.ts@@ -3,7 +3,7 @@ import {JobConfigState,LangfuseNotFoundError,} from "@langfuse/shared";-import { Prisma, prisma } from "@langfuse/shared/src/db";+import { EvalTemplateType, Prisma, prisma } from "@langfuse/shared/src/db";import type {EvaluationRuleEvaluatorFamilyReference,PrismaClientLike,@@ -25,6 +25,7 @@ export async function findPublicEvaluatorTemplateOrThrow(params: {const template = await client.evalTemplate.findUnique({where: {id: params.evaluatorId,+ type: EvalTemplateType.LLM_AS_JUDGE,},});@@ -50,6 +51,7 @@ export async function findLatestPublicEvaluatorTemplateInFamilyOrThrow(params: {where: {name: params.evaluator.name,projectId: params.evaluator.scope === "project" ? params.projectId : null,+ type: EvalTemplateType.LLM_AS_JUDGE,},orderBy: {version: "desc",@@ -135,7 +137,8 @@ export async function listPublicEvaluatorTemplates(params: {name,updated_atFROM eval_templates- WHERE project_id = ${params.projectId} OR project_id IS NULL+ WHERE (project_id = ${params.projectId} OR project_id IS NULL)+ AND type = ${EvalTemplateType.LLM_AS_JUDGE}::"EvalTemplateType"ORDER BY project_id, name, version DESC)SELECT id@@ -155,7 +158,8 @@ export async function listPublicEvaluatorTemplates(params: {FROM (SELECT DISTINCT project_id, nameFROM eval_templates- WHERE project_id = ${params.projectId} OR project_id IS NULL+ WHERE (project_id = ${params.projectId} OR project_id IS NULL)+ AND type = ${EvalTemplateType.LLM_AS_JUDGE}::"EvalTemplateType") latest_template_families`,),@@ -214,6 +218,7 @@ export async function findPublicEvaluationRuleOrThrow(params: {},evalTemplate: {is: {+ type: EvalTemplateType.LLM_AS_JUDGE,OR: [{ projectId: params.projectId }, { projectId: null }],},},@@ -224,8 +229,6 @@ export async function findPublicEvaluationRuleOrThrow(params: {id: true,projectId: true,name: true,- vars: true,- prompt: true,},},},@@ -267,6 +270,12 @@ export async function countActiveEvaluationRules(params: {},status: JobConfigState.ACTIVE,blockedAt: null,+ evalTemplate: {+ is: {+ type: EvalTemplateType.LLM_AS_JUDGE,+ OR: [{ projectId: params.projectId }, { projectId: null }],+ },+ },},});}@@ -285,6 +294,7 @@ export async function listPublicEvaluationRuleConfigs(params: {},evalTemplate: {is: {+ type: EvalTemplateType.LLM_AS_JUDGE,OR: [{ projectId: params.projectId }, { projectId: null }],},},@@ -295,8 +305,6 @@ export async function listPublicEvaluationRuleConfigs(params: {id: true,projectId: true,name: true,- vars: true,- prompt: true,},},},@@ -314,6 +322,7 @@ export async function listPublicEvaluationRuleConfigs(params: {},evalTemplate: {is: {+ type: EvalTemplateType.LLM_AS_JUDGE,OR: [{ projectId: params.projectId }, { projectId: null }],},},diff --git a/web/src/features/evals/server/unstable-public-api/types.ts b/web/src/features/evals/server/unstable-public-api/types.tsindex 4dd4537168..20cc1f7971 100644--- a/web/src/features/evals/server/unstable-public-api/types.ts+++ b/web/src/features/evals/server/unstable-public-api/types.ts@@ -1,5 +1,5 @@+import type { EvalTemplateLlmAsAJudge } from "@langfuse/shared";import type {- EvalTemplate,JobConfiguration,Prisma as PrismaNamespace,prisma,@@ -55,7 +55,7 @@ export type EvaluationRuleEvaluatorFamilyReference =PublicEvaluationRuleEvaluatorReferenceType;export type StoredPublicEvaluatorTemplate = Pick<- EvalTemplate,+ EvalTemplateLlmAsAJudge,| "id"| "projectId"| "name"@@ -89,7 +89,7 @@ export type StoredPublicEvaluationRuleConfig = Pick<| "updatedAt"> & {evalTemplate: Pick<- EvalTemplate,- "id" | "projectId" | "name" | "vars" | "prompt"+ EvalTemplateLlmAsAJudge,+ "id" | "projectId" | "name"> | null;};diff --git a/web/src/features/evals/utils/code-eval-template-hover-docs.ts b/web/src/features/evals/utils/code-eval-template-hover-docs.tsnew file mode 100644index 0000000000..08e6e21757--- /dev/null+++ b/web/src/features/evals/utils/code-eval-template-hover-docs.ts@@ -0,0 +1,193 @@+import type { CodeEvalSourceCodeLanguage } from "@/src/features/evals/utils/code-eval-template-starter-examples";++export type CodeEvalHoverDocs = Record<string, string>;++const TYPESCRIPT_SCORE_DOC = `type Score =+ | (ScoreBase & { dataType: "NUMERIC"; value: number })+ | (ScoreBase & { dataType: "BOOLEAN"; value: boolean })+ | (ScoreBase & { dataType: "CATEGORICAL"; value: string })+ | (ScoreBase & { dataType: "TEXT"; value: string });++type ScoreBase = {+ name: string;+ comment?: string;+ configId?: string | null;+ metadata?: Record<string, unknown>;+}++A Langfuse score returned by a TypeScript evaluator. The contract is shown at the top of the editor and is locked.`;++const PYTHON_SCORE_DOC = `@dataclass+class Score:+ value: int | float | str | bool+ name: str+ data_type: str | None = None+ comment: str | None = None+ config_id: str | None = None+ metadata: dict[str, Any] | None = None++A Langfuse score returned by a Python evaluator.`;++export const TYPESCRIPT_CODE_EVAL_HOVER_DOCS = {+ evaluate: `function evaluate(ctx: EvaluationContext): EvaluationResult++The TypeScript function Langfuse executes for each matched target observation.`,+ ctx: `parameter ctx: EvaluationContext++The TypeScript value Langfuse passes to evaluate.`,+ EvaluationContext: `type EvaluationContext = {+ observation: {+ input: any;+ output: any;+ metadata: any;+ };+ experiment:+ | {+ itemExpectedOutput: any;+ itemMetadata: any;+ }+ | undefined;+}++The data Langfuse passes to a TypeScript evaluator. The definition is locked at the top of the editor.`,+ observation: `property EvaluationContext.observation: {+ input: any;+ output: any;+ metadata: any;+}++The observation selected by the evaluator target.`,+ experiment: `property EvaluationContext.experiment?: {+ itemExpectedOutput: any;+ itemMetadata: any;+}++Experiment item data. Present when the evaluator runs on an experiment.`,+ input: `property observation.input: any++The input recorded on the observation.`,+ output: `property observation.output: any++The output recorded on the observation.`,+ metadata: `property observation.metadata: any+property Score.metadata?: Record<string, unknown>++The metadata recorded on the observation, or extra metadata stored with a returned score.`,+ itemExpectedOutput: `property experiment.itemExpectedOutput: any++The expected output from the experiment item.`,+ itemMetadata: `property experiment.itemMetadata: any++The metadata from the experiment item.`,+ EvaluationResult: `type EvaluationResult = {+ scores: Score[];+}++The value returned by evaluate.`,+ Score: TYPESCRIPT_SCORE_DOC,+ scores: `property EvaluationResult.scores: Score[]++One or more Langfuse scores to create for the target observation.`,+ dataType: `property Score.dataType: "NUMERIC" | "BOOLEAN" | "CATEGORICAL" | "TEXT"++The Langfuse score data type.`,+ value: `property Score.value: number | string | boolean++The score value. The allowed value depends on dataType: NUMERIC uses number, BOOLEAN uses boolean, and CATEGORICAL or TEXT use string.`,+ name: `property Score.name: string++The score name.`,+ comment: `property Score.comment?: string++The reasoning or explanation stored with the score.`,+ configId: `property Score.configId?: string | null++The score config id to attach to the score.`,+} satisfies CodeEvalHoverDocs;++export const PYTHON_CODE_EVAL_HOVER_DOCS = {+ evaluate: `def evaluate(ctx: EvaluationContext) -> EvaluationResult++The Python function Langfuse executes for each matched target observation.`,+ ctx: `parameter ctx: EvaluationContext++The Python dataclass value Langfuse passes to evaluate.`,+ Any: `typing.Any++Use for JSON-like evaluator values whose concrete type depends on the target observation.`,+ dataclass: `dataclasses.dataclass++Use to describe the Python evaluator context and result classes.`,+ ObservationContext: `@dataclass+class ObservationContext:+ input: Any = None+ output: Any = None+ metadata: Any = None++The observation selected by the evaluator target.`,+ ExperimentContext: `@dataclass+class ExperimentContext:+ item_expected_output: Any = None+ item_metadata: Any = None++Experiment item data. Present when the evaluator runs on an experiment.`,+ EvaluationContext: `@dataclass+class EvaluationContext:+ observation: ObservationContext+ experiment: ExperimentContext | None = None++The data Langfuse passes to a Python evaluator.`,+ EvaluationResult: `@dataclass+class EvaluationResult:+ scores: list[Score]++The value returned by evaluate.`,+ Score: PYTHON_SCORE_DOC,+ observation: `property ctx.observation: ObservationContext++The observation selected by the evaluator target.`,+ experiment: `property ctx.experiment: ExperimentContext | None++Experiment item data. Present when the evaluator runs on an experiment.`,+ input: `property observation.input: Any++The input recorded on the observation.`,+ output: `property observation.output: Any++The output recorded on the observation.`,+ metadata: `property observation.metadata or score.metadata++Observation metadata is available on the evaluator context. Score metadata stores extra details on a returned score.`,+ item_expected_output: `property experiment.item_expected_output: Any++The expected output from the experiment item.`,+ item_metadata: `property experiment.item_metadata: Any++The metadata from the experiment item.`,+ scores: `property result.scores: list[Score]++One or more Langfuse scores to create for the target observation.`,+ data_type: `property score.data_type: str | None++The Langfuse score data type. Use NUMERIC, BOOLEAN, CATEGORICAL, or TEXT.`,+ value: `property score.value: int | float | str | bool++The score value. The allowed value depends on data_type: NUMERIC uses a number, BOOLEAN uses a boolean, and CATEGORICAL or TEXT use a string.`,+ name: `property score.name: str++The score name.`,+ comment: `property score.comment: str | None++The reasoning or explanation stored with the score.`,+ config_id: `property score.config_id: str | None++The score config id to attach to the score.`,+} satisfies CodeEvalHoverDocs;++export function getCodeEvalHoverDocs(+ sourceCodeLanguage: CodeEvalSourceCodeLanguage,+): CodeEvalHoverDocs {+ return sourceCodeLanguage === "PYTHON"+ ? PYTHON_CODE_EVAL_HOVER_DOCS+ : TYPESCRIPT_CODE_EVAL_HOVER_DOCS;+}diff --git a/web/src/features/evals/utils/code-eval-template-starter-examples.ts b/web/src/features/evals/utils/code-eval-template-starter-examples.tsnew file mode 100644index 0000000000..dd68df318d--- /dev/null+++ b/web/src/features/evals/utils/code-eval-template-starter-examples.ts@@ -0,0 +1,310 @@+export const TYPESCRIPT_CODE_EVAL_CONTRACT = `/**+ * The data Langfuse passes to a code evaluator.+ */+type EvaluationContext = {+ /**+ * The observation selected by the evaluator target.+ */+ observation: {+ /**+ * The input recorded on the observation.+ */+ input: any;+ /**+ * The output recorded on the observation.+ */+ output: any;+ /**+ * The metadata recorded on the observation.+ */+ metadata: any;+ };+ /**+ * Experiment item data. Present when the evaluator runs on an experiment.+ */+ experiment:+ | {+ /**+ * The expected output from the experiment item.+ */+ itemExpectedOutput: any;+ /**+ * The metadata from the experiment item.+ */+ itemMetadata: any;+ }+ | undefined;+};++/**+ * A Langfuse score returned by a code evaluator.+ */+type ScoreBase = {+ /**+ * The score name.+ */+ name: string;+ /**+ * The reasoning or explanation stored with the score.+ */+ comment?: string;+ /**+ * The score config id to attach to the score.+ */+ configId?: string | null;+ /**+ * Extra metadata stored with the score.+ */+ metadata?: Record<string, unknown>;+};++type NumericScore = ScoreBase & {+ /**+ * The Langfuse score data type.+ */+ dataType: "NUMERIC";+ /**+ * The score value.+ */+ value: number;+};++type BooleanScore = ScoreBase & {+ /**+ * The Langfuse score data type.+ */+ dataType: "BOOLEAN";+ /**+ * The score value.+ */+ value: boolean;+};++type CategoricalScore = ScoreBase & {+ /**+ * The Langfuse score data type.+ */+ dataType: "CATEGORICAL";+ /**+ * The score value.+ */+ value: string;+};++type TextScore = ScoreBase & {+ /**+ * The Langfuse score data type.+ */+ dataType: "TEXT";+ /**+ * The score value.+ */+ value: string;+};++type Score = NumericScore | BooleanScore | CategoricalScore | TextScore;++/**+ * The value returned by evaluate.+ */+type EvaluationResult = {+ /**+ * One or more Langfuse scores to create for the target observation.+ */+ scores: Score[];+};+`;++export const DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE = `${TYPESCRIPT_CODE_EVAL_CONTRACT}++/**+ * Evaluates one observation and returns one or more Langfuse scores.+ */+function evaluate(ctx: EvaluationContext): EvaluationResult {+ const input = ctx.observation.input;+ const matchesOutput =+ input !== undefined && ctx.observation.output === input;++ return {+ scores: [+ {+ name: "Exact match",+ value: matchesOutput,+ dataType: "BOOLEAN",+ comment: matchesOutput+ ? "Output exactly matches the input."+ : "Output does not match the input.",+ },+ ],+ };+}+`;++export const PYTHON_CODE_EVAL_CONTRACT = `from dataclasses import dataclass+from typing import Any+++@dataclass+class ObservationContext:+ input: Any = None+ output: Any = None+ metadata: Any = None+++@dataclass+class ExperimentContext:+ item_expected_output: Any = None+ item_metadata: Any = None+++@dataclass+class EvaluationContext:+ observation: ObservationContext+ experiment: ExperimentContext | None = None+++@dataclass+class Score:+ value: int | float | str | bool+ name: str+ data_type: str | None = None+ comment: str | None = None+ config_id: str | None = None+ metadata: dict[str, Any] | None = None+++@dataclass+class EvaluationResult:+ scores: list[Score]+`;++export const DEFAULT_PYTHON_CODE_EVAL_SOURCE = `${PYTHON_CODE_EVAL_CONTRACT}+++def evaluate(ctx: EvaluationContext) -> EvaluationResult:+ """Evaluates one observation and returns one or more Langfuse scores."""+ input = ctx.observation.input+ matches_output = input is not None and ctx.observation.output == input++ return EvaluationResult(+ scores=[+ Score(+ name="Exact match",+ value=matches_output,+ data_type="BOOLEAN",+ comment=(+ "Output exactly matches the input."+ if matches_output+ else "Output does not match the input."+ ),+ )+ ]+ )+`;++export type CodeEvalSourceCodeLanguage = "PYTHON" | "TYPESCRIPT";++export function getDefaultCodeEvalSource(+ sourceCodeLanguage: CodeEvalSourceCodeLanguage,+) {+ return sourceCodeLanguage === "PYTHON"+ ? DEFAULT_PYTHON_CODE_EVAL_SOURCE+ : DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE;+}++export function isDefaultCodeEvalSource(sourceCode: string) {+ return (+ sourceCode === DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE ||+ sourceCode === DEFAULT_PYTHON_CODE_EVAL_SOURCE+ );+}++export function getCodeEvalSourceForEditor({+ sourceCode,+ sourceCodeLanguage,+}: {+ sourceCode?: string | null;+ sourceCodeLanguage: CodeEvalSourceCodeLanguage;+}) {+ if (!sourceCode?.trim()) return getDefaultCodeEvalSource(sourceCodeLanguage);++ if (sourceCodeLanguage === "PYTHON") {+ return sourceCode.trimStart().startsWith(PYTHON_CODE_EVAL_CONTRACT)+ ? sourceCode+ : `${PYTHON_CODE_EVAL_CONTRACT}\n\n${sourceCode.trimStart()}`;+ }++ return sourceCode.startsWith(TYPESCRIPT_CODE_EVAL_CONTRACT)+ ? sourceCode+ : `${TYPESCRIPT_CODE_EVAL_CONTRACT}\n\n${sourceCode.trimStart()}`;+}++async function formatTypeScriptSource(source: string): Promise<string> {+ const [{ format }, typescriptPlugin, estreePlugin] = await Promise.all([+ import("prettier/standalone"),+ import("prettier/plugins/typescript"),+ import("prettier/plugins/estree"),+ ]);++ return format(source, {+ parser: "typescript",+ plugins: [typescriptPlugin, estreePlugin],+ });+}++async function formatPythonSource(source: string): Promise<string> {+ const ruffModule = await import("@astral-sh/ruff-wasm-web");+ await ruffModule.default();++ const workspace = new ruffModule.Workspace(+ {+ "line-length": 88,+ "indent-width": 4,+ },+ ruffModule.PositionEncoding.Utf16,+ );++ return workspace.format(source);+}++/**+ * Formats the source code and strips the contract types for submission.+ * For Python: Formats with Ruff, then extracts starting from `def evaluate(`.+ * For TypeScript: Strips contract types, formats with prettier, then returns.+ */+export async function formatAndStripCodeEvalSourceForSubmit({+ sourceCode,+ sourceCodeLanguage,+}: {+ sourceCode: string;+ sourceCodeLanguage: CodeEvalSourceCodeLanguage;+}): Promise<string> {+ if (sourceCodeLanguage === "PYTHON") {+ const evaluateMatch = sourceCode.match(/(?:^|\n)\s*def\s+evaluate\s*\(/);+ if (!evaluateMatch || evaluateMatch.index === undefined) {+ return sourceCode.trim();+ }++ const strippedSource = sourceCode+ .slice(evaluateMatch.index)+ .trimStart()+ .trimEnd();++ try {+ return (await formatPythonSource(strippedSource)).trimEnd();+ } catch {+ return strippedSource;+ }+ }++ // TypeScript: strip contract types first, then format+ const strippedSource = sourceCode.startsWith(TYPESCRIPT_CODE_EVAL_CONTRACT)+ ? sourceCode.slice(TYPESCRIPT_CODE_EVAL_CONTRACT.length).trim()+ : sourceCode.trim();++ try {+ return (await formatTypeScriptSource(strippedSource)).trimEnd();+ } catch {+ return strippedSource;+ }+}diff --git a/web/src/features/evals/utils/code-eval-template-utils.ts b/web/src/features/evals/utils/code-eval-template-utils.tsnew file mode 100644index 0000000000..32f02bcb8d--- /dev/null+++ b/web/src/features/evals/utils/code-eval-template-utils.ts@@ -0,0 +1,54 @@+import {+ EvalTargetObject,+ EvalTemplateType,+ type EvalTemplate,+ type ObservationVariableMapping,+} from "@langfuse/shared";++export const isCodeEvalTemplate = (+ template: Partial<Pick<EvalTemplate, "type">> | null | undefined,+) => template?.type === EvalTemplateType.CODE;++export const shouldShowEvalTemplate = (+ template: Pick<EvalTemplate, "type">,+ codeEvalEnabled: boolean,+) => !isCodeEvalTemplate(template) || codeEvalEnabled;++export const CODE_EVAL_ESCAPE_CONFIRM_MESSAGE =+ "Close code editor? Unsaved changes will be lost.";++export function getCodeEvalVariableMapping(): ObservationVariableMapping[] {+ return [+ {+ templateVariable: "input",+ selectedColumnId: "input",+ jsonSelector: null,+ },+ {+ templateVariable: "output",+ selectedColumnId: "output",+ jsonSelector: null,+ },+ {+ templateVariable: "metadata",+ selectedColumnId: "metadata",+ jsonSelector: null,+ },+ {+ templateVariable: "experimentItemExpectedOutput",+ selectedColumnId: "experimentItemExpectedOutput",+ jsonSelector: null,+ },+ {+ templateVariable: "experimentItemMetadata",+ selectedColumnId: "experimentItemMetadata",+ jsonSelector: null,+ },+ ];+}++export function resolveCodeEvalTarget(target: EvalTargetObject) {+ if (target === EvalTargetObject.TRACE) return EvalTargetObject.EVENT;+ if (target === EvalTargetObject.DATASET) return EvalTargetObject.EXPERIMENT;+ return target;+}diff --git a/web/src/features/evals/utils/code-eval-template-validation.clienttest.ts b/web/src/features/evals/utils/code-eval-template-validation.clienttest.tsnew file mode 100644index 0000000000..b6993cb81c--- /dev/null+++ b/web/src/features/evals/utils/code-eval-template-validation.clienttest.ts@@ -0,0 +1,180 @@+import { describe, expect, it, vi } from "vitest";+import {+ DEFAULT_PYTHON_CODE_EVAL_SOURCE,+ DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE,+ TYPESCRIPT_CODE_EVAL_CONTRACT,+ formatAndStripCodeEvalSourceForSubmit,+ formatPythonCodeEvalSourceWithRuff,+ getCodeEvalSourceForEditor,+ getDefaultCodeEvalSource,+ isDefaultCodeEvalSource,+ validateCodeEvalSourceWithLanguage,+} from "@/src/features/evals/utils/code-eval-template-validation";++vi.mock("@astral-sh/ruff-wasm-web", () => ({+ default: async () => ({}),+ PositionEncoding: { Utf16: 1 },+ Workspace: class {+ check(contents: string) {+ if (!contents.includes("missing_name")) return [];++ return [+ {+ code: "F821",+ message: "Undefined name `missing_name`",+ start_location: { row: 2, column: 12 },+ end_location: { row: 2, column: 24 },+ fix: null,+ },+ ];+ }++ format(contents: string) {+ return contents+ .replace(" return", " return")+ .replace("{'scores':[]}", '{"scores": []}');+ }+ },+}));++describe("code eval template validation", () => {+ it("keeps language defaults distinct", () => {+ expect(getDefaultCodeEvalSource("TYPESCRIPT")).toBe(+ DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE,+ );+ expect(getDefaultCodeEvalSource("PYTHON")).toBe(+ DEFAULT_PYTHON_CODE_EVAL_SOURCE,+ );+ expect(isDefaultCodeEvalSource(DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE)).toBe(+ true,+ );+ expect(isDefaultCodeEvalSource(DEFAULT_PYTHON_CODE_EVAL_SOURCE)).toBe(true);+ expect(DEFAULT_PYTHON_CODE_EVAL_SOURCE).toMatch(+ /^from dataclasses import dataclass/,+ );+ expect(DEFAULT_PYTHON_CODE_EVAL_SOURCE).toContain(+ "def evaluate(ctx: EvaluationContext) -> EvaluationResult:",+ );+ expect(+ DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE.startsWith(+ TYPESCRIPT_CODE_EVAL_CONTRACT,+ ),+ ).toBe(true);+ expect(DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE).toContain(+ "type EvaluationContext =",+ );+ expect(DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE).toContain(+ "type EvaluationResult =",+ );+ expect(DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE).toContain(+ "function evaluate(ctx: EvaluationContext): EvaluationResult",+ );+ });++ it("strips editor-only contracts before submit", async () => {+ expect(+ await formatAndStripCodeEvalSourceForSubmit({+ sourceCode: DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE,+ sourceCodeLanguage: "TYPESCRIPT",+ }),+ ).toContain("function evaluate(ctx: EvaluationContext): EvaluationResult");+ expect(+ await formatAndStripCodeEvalSourceForSubmit({+ sourceCode: DEFAULT_PYTHON_CODE_EVAL_SOURCE,+ sourceCodeLanguage: "PYTHON",+ }),+ ).toMatch(/^def evaluate\(ctx: EvaluationContext\)/);+ });++ it("rehydrates stored evaluator functions for the editor", () => {+ const source =+ "function evaluate(ctx: EvaluationContext): EvaluationResult { return { scores: [] }; }";++ expect(+ getCodeEvalSourceForEditor({+ sourceCode: source,+ sourceCodeLanguage: "TYPESCRIPT",+ }),+ ).toContain(TYPESCRIPT_CODE_EVAL_CONTRACT);+ });++ it("accepts the default TypeScript source", async () => {+ const result = await validateCodeEvalSourceWithLanguage({+ source: DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE,+ sourceCodeLanguage: "TYPESCRIPT",+ });++ expect(result.hasErrors).toBe(false);+ });++ it("rejects async TypeScript evaluate functions", async () => {+ const result = await validateCodeEvalSourceWithLanguage({+ source: `${TYPESCRIPT_CODE_EVAL_CONTRACT}+async function evaluate(ctx: EvaluationContext): Promise<EvaluationResult> {+ return { scores: [] };+}+`,+ sourceCodeLanguage: "TYPESCRIPT",+ });++ expect(result.hasErrors).toBe(true);+ });++ it("rejects exported TypeScript evaluate functions", async () => {+ const result = await validateCodeEvalSourceWithLanguage({+ source: `${TYPESCRIPT_CODE_EVAL_CONTRACT}+export function evaluate(ctx: EvaluationContext): EvaluationResult {+ return { scores: [] };+}+`,+ sourceCodeLanguage: "TYPESCRIPT",+ });++ expect(result.hasErrors).toBe(true);+ expect(+ result.diagnostics.some((diagnostic) =>+ diagnostic.message.includes("Exports are not supported"),+ ),+ ).toBe(true);+ });++ it("uses Ruff diagnostics for Python source", async () => {+ const result = await validateCodeEvalSourceWithLanguage({+ source: "def evaluate(ctx):\n return missing_name\n",+ sourceCodeLanguage: "PYTHON",+ });++ expect(result.hasErrors).toBe(true);+ expect(+ result.diagnostics.some((diagnostic) =>+ diagnostic.message.includes("F821"),+ ),+ ).toBe(true);+ });++ it("rejects default exported TypeScript evaluate functions", async () => {+ const result = await validateCodeEvalSourceWithLanguage({+ source: `${TYPESCRIPT_CODE_EVAL_CONTRACT}+export default function evaluate(): EvaluationResult {+ return { scores: [] };+}+`,+ sourceCodeLanguage: "TYPESCRIPT",+ });++ expect(result.hasErrors).toBe(true);+ expect(+ result.diagnostics.some((diagnostic) =>+ diagnostic.message.includes("Exports are not supported"),+ ),+ ).toBe(true);+ });++ it("formats Python source with Ruff", async () => {+ await expect(+ formatPythonCodeEvalSourceWithRuff(+ "def evaluate(ctx):\n return {'scores':[]}\n",+ ),+ ).resolves.toContain('"scores": []');+ });+});diff --git a/web/src/features/evals/utils/code-eval-template-validation.ts b/web/src/features/evals/utils/code-eval-template-validation.tsnew file mode 100644index 0000000000..6d9e8be7cc--- /dev/null+++ b/web/src/features/evals/utils/code-eval-template-validation.ts@@ -0,0 +1,682 @@+import type * as ts from "typescript";+import type { Diagnostic as RuffDiagnostic } from "@astral-sh/ruff-wasm-web";+import {+ PYTHON_CODE_EVAL_CONTRACT,+ TYPESCRIPT_CODE_EVAL_CONTRACT,+ type CodeEvalSourceCodeLanguage,+} from "@/src/features/evals/utils/code-eval-template-starter-examples";++export {+ DEFAULT_PYTHON_CODE_EVAL_SOURCE,+ DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE,+ PYTHON_CODE_EVAL_CONTRACT,+ TYPESCRIPT_CODE_EVAL_CONTRACT,+ formatAndStripCodeEvalSourceForSubmit,+ getCodeEvalSourceForEditor,+ getDefaultCodeEvalSource,+ isDefaultCodeEvalSource,+ type CodeEvalSourceCodeLanguage,+} from "@/src/features/evals/utils/code-eval-template-starter-examples";++export const CODE_EVAL_SOURCE_MAX_BYTES = 256 * 1024;++export type CodeEvalDiagnosticSeverity = "error" | "warning";++export type CodeEvalDiagnostic = {+ from: number;+ to: number;+ severity: CodeEvalDiagnosticSeverity;+ message: string;+};++export type CodeEvalValidationResult = {+ diagnostics: CodeEvalDiagnostic[];+ hasErrors: boolean;+ sourceBytes: number;+};++type TypeScriptModule = typeof ts;+type RuffWorkspace = {+ check(contents: string): RuffDiagnostic[];+ format(contents: string): string;+};++const SYNTHETIC_ASSERTION_PREFIX = `+type __LangfuseExpectedEvaluate = (+ ctx: EvaluationContext,+) => EvaluationResult;+const __langfuseEvaluateCheck: __LangfuseExpectedEvaluate = evaluate;+`;++const CONTRACT_DECLARATIONS = `+interface Array<T> {+ length: number;+ [n: number]: T;+ map<U>(callbackfn: (value: T, index: number, array: T[]) => U): U[];+ filter(callbackfn: (value: T, index: number, array: T[]) => unknown): T[];+ includes(searchElement: T, fromIndex?: number): boolean;+ join(separator?: string): string;+}++interface Boolean {}++interface Number {}++interface Promise<T> {+ then<TResult1 = T, TResult2 = never>(+ onfulfilled?:+ | ((value: T) => TResult1 | PromiseLike<TResult1>)+ | null,+ onrejected?:+ | ((reason: any) => TResult2 | PromiseLike<TResult2>)+ | null,+ ): Promise<TResult1 | TResult2>;+}++interface PromiseLike<T> {+ then<TResult1 = T, TResult2 = never>(+ onfulfilled?:+ | ((value: T) => TResult1 | PromiseLike<TResult1>)+ | null,+ onrejected?:+ | ((reason: any) => TResult2 | PromiseLike<TResult2>)+ | null,+ ): PromiseLike<TResult1 | TResult2>;+}++interface String {+ includes(searchString: string, position?: number): boolean;+ trim(): string;+ toLowerCase(): string;+ toString(): string;+}++type Record<K extends string, T> = { [P in K]: T };++declare const String: (value?: unknown) => string;+declare const Number: (value?: unknown) => number;+declare const Boolean: (value?: unknown) => boolean;+declare const JSON: {+ parse(text: string): unknown;+ stringify(value: unknown): string;+};+declare const Math: {+ abs(value: number): number;+ max(...values: number[]): number;+ min(...values: number[]): number;+ round(value: number): number;+};+declare const Date: any;+declare const console: {+ log(...args: unknown[]): void;+ warn(...args: unknown[]): void;+ error(...args: unknown[]): void;+};+`;++const IGNORED_DIAGNOSTIC_CODES = new Set([2318]);+const PYTHON_RUFF_SETTINGS = {+ "line-length": 88,+ "indent-width": 4,+ lint: {+ select: ["E4", "E7", "E9", "F"],+ },+};+const PYTHON_ERROR_DIAGNOSTIC_CODES = new Set([+ "invalid-syntax",+ "F821",+ "F822",+ "F823",+]);+const PYTHON_CONTRACT_PREFIX = "from dataclasses import dataclass";+const PYTHON_EVALUATE_SIGNATURE_PATTERN =+ /(?:^|\n)\s*def\s+evaluate\s*\(\s*ctx\s*:\s*EvaluationContext\s*\)\s*->\s*EvaluationResult\s*:/;+let ruffWorkspacePromise: Promise<RuffWorkspace> | null = null;++export async function validateCodeEvalSourceWithLanguage({+ source,+ sourceCodeLanguage,+}: {+ source: string;+ sourceCodeLanguage: CodeEvalSourceCodeLanguage;+}): Promise<CodeEvalValidationResult> {+ if (sourceCodeLanguage === "PYTHON") {+ return validateCodeEvalSourceWithPython(source);+ }++ return validateCodeEvalSourceWithTypescript(source);+}++export async function validateCodeEvalSourceWithTypescript(+ source: string,+): Promise<CodeEvalValidationResult> {+ const tsModule = await import("typescript");+ return validateCodeEvalSource(source, tsModule);+}++export async function validateCodeEvalSourceWithPython(+ source: string,+): Promise<CodeEvalValidationResult> {+ const sourceBytes = getUtf8ByteLength(source);+ const diagnostics: CodeEvalDiagnostic[] = [];+ const validationSource = source.trimStart().startsWith(PYTHON_CONTRACT_PREFIX)+ ? source+ : `${PYTHON_CODE_EVAL_CONTRACT}\n\n${source}`;++ collectBasicSourceDiagnostics({+ source,+ sourceBytes,+ languageLabel: "Python",+ diagnostics,+ });++ if (!hasPythonEvaluateFunction(source)) {+ const evaluatePosition = findPythonEvaluatePosition(source) ?? 0;+ diagnostics.push({+ from: evaluatePosition,+ to: clampToSourceRange(source, evaluatePosition + "evaluate".length),+ severity: "error",+ message: "Evaluator source must define an evaluate function.",+ });+ }++ collectPythonContractDiagnostics(source, diagnostics);++ try {+ const ruffWorkspace = await getPythonRuffWorkspace();+ diagnostics.push(+ ...ruffWorkspace.check(validationSource).map((diagnostic) =>+ mapRuffDiagnosticToCodeEvalDiagnostic({+ source,+ locationSource: validationSource,+ diagnostic,+ offset: validationSource === source ? 0 : -getValidationOffset(),+ }),+ ),+ );+ } catch (error) {+ diagnostics.push({+ from: 0,+ to: Math.max(1, source.length),+ severity: "error",+ message:+ error instanceof Error+ ? `Failed to lint Python source with Ruff: ${error.message}`+ : "Failed to lint Python source with Ruff.",+ });+ }++ return {+ diagnostics: sortDiagnostics(diagnostics),+ hasErrors: diagnostics.some(+ (diagnostic) => diagnostic.severity === "error",+ ),+ sourceBytes,+ };+}++export async function formatPythonCodeEvalSourceWithRuff(source: string) {+ const ruffWorkspace = await getPythonRuffWorkspace();+ return ruffWorkspace.format(source);+}++export function validateCodeEvalSource(+ source: string,+ tsModule: TypeScriptModule,+): CodeEvalValidationResult {+ const sourceBytes = getUtf8ByteLength(source);+ const diagnostics: CodeEvalDiagnostic[] = [];++ collectBasicSourceDiagnostics({+ source,+ sourceBytes,+ languageLabel: "TypeScript",+ diagnostics,+ });++ const sourceFile = tsModule.createSourceFile(+ "code-eval-template.ts",+ source,+ tsModule.ScriptTarget.Latest,+ true,+ tsModule.ScriptKind.TS,+ );++ const evaluatePosition = findEvaluatePosition(sourceFile, tsModule) ?? 0;+ const hasEvaluate = hasEvaluateFunction(sourceFile, tsModule);++ collectUnsupportedModuleSyntaxDiagnostics(sourceFile, diagnostics, tsModule);++ if (!hasEvaluate) {+ diagnostics.push({+ from: evaluatePosition,+ to: clampToSourceRange(source, evaluatePosition + "evaluate".length),+ severity: "error",+ message: "Evaluator source must define an evaluate function.",+ });+ }++ diagnostics.push(+ ...getTypeScriptDiagnostics({+ source,+ evaluatePosition,+ tsModule,+ }),+ );++ return {+ diagnostics: sortDiagnostics(diagnostics),+ hasErrors: diagnostics.some(+ (diagnostic) => diagnostic.severity === "error",+ ),+ sourceBytes,+ };+}++function getTypeScriptDiagnostics({+ source,+ evaluatePosition,+ tsModule,+}: {+ source: string;+ evaluatePosition: number;+ tsModule: TypeScriptModule;+}): CodeEvalDiagnostic[] {+ const validationPrelude = [+ CONTRACT_DECLARATIONS,+ getTypeScriptContractForValidation(source),+ ]+ .filter(Boolean)+ .join("\n");+ const contractOffset = validationPrelude.length;+ const validationSource = `${validationPrelude}\n${source}\n${SYNTHETIC_ASSERTION_PREFIX}`;+ const fileName = "code-eval-template.ts";+ const compilerOptions: ts.CompilerOptions = {+ target: tsModule.ScriptTarget.ES2022,+ module: tsModule.ModuleKind.ESNext,+ strict: true,+ noEmit: true,+ skipLibCheck: true,+ noLib: true,+ erasableSyntaxOnly: true,+ };+ const host: ts.CompilerHost = {+ getSourceFile: (requestedFileName, languageVersion) =>+ requestedFileName === fileName+ ? tsModule.createSourceFile(+ requestedFileName,+ validationSource,+ languageVersion,+ true,+ tsModule.ScriptKind.TS,+ )+ : undefined,+ getDefaultLibFileName: () => "lib.d.ts",+ writeFile: () => {},+ getCurrentDirectory: () => "",+ getDirectories: () => [],+ fileExists: (requestedFileName) => requestedFileName === fileName,+ readFile: (requestedFileName) =>+ requestedFileName === fileName ? validationSource : undefined,+ getCanonicalFileName: (file) => file,+ useCaseSensitiveFileNames: () => true,+ getNewLine: () => "\n",+ };++ const program = tsModule.createProgram([fileName], compilerOptions, host);+ const allDiagnostics = tsModule+ .getPreEmitDiagnostics(program)+ .filter((diagnostic) => !IGNORED_DIAGNOSTIC_CODES.has(diagnostic.code));++ return allDiagnostics.flatMap((diagnostic) => {+ const message = tsModule.flattenDiagnosticMessageText(+ diagnostic.messageText,+ "\n",+ );+ const start = diagnostic.start ?? contractOffset + evaluatePosition;+ const length = diagnostic.length ?? 1;+ const sourceStart = mapValidationOffsetToSourceOffset({+ offset: start,+ contractOffset,+ sourceLength: source.length,+ fallbackOffset: evaluatePosition,+ });++ if (sourceStart === null) return [];++ return [+ {+ from: clampToSourceRange(source, sourceStart),+ to: clampToSourceRange(source, sourceStart + length),+ severity: "error" as const,+ message,+ },+ ];+ });+}++function getTypeScriptContractForValidation(source: string) {+ return hasTypeScriptContractDeclarations(source)+ ? ""+ : TYPESCRIPT_CODE_EVAL_CONTRACT;+}++function hasTypeScriptContractDeclarations(source: string) {+ return (+ /\btype\s+EvaluationContext\s*=/.test(source) &&+ /\btype\s+Score\s*=/.test(source) &&+ /\btype\s+EvaluationResult\s*=/.test(source)+ );+}++function mapValidationOffsetToSourceOffset({+ offset,+ contractOffset,+ sourceLength,+ fallbackOffset,+}: {+ offset: number;+ contractOffset: number;+ sourceLength: number;+ fallbackOffset: number;+}) {+ if (offset < contractOffset) return null;++ const sourceOffset = offset - contractOffset - 1;+ if (sourceOffset >= 0 && sourceOffset <= sourceLength) return sourceOffset;++ return fallbackOffset;+}++function collectUnsupportedModuleSyntaxDiagnostics(+ sourceFile: ts.SourceFile,+ diagnostics: CodeEvalDiagnostic[],+ tsModule: TypeScriptModule,+) {+ const visit = (node: ts.Node) => {+ if (+ tsModule.isImportDeclaration(node) ||+ tsModule.isExportDeclaration(node)+ ) {+ diagnostics.push({+ from: node.getStart(sourceFile),+ to: node.getEnd(),+ severity: "error",+ message: "Imports and exports are not supported in code evaluators.",+ });+ }++ const modifiers = tsModule.canHaveModifiers(node)+ ? tsModule.getModifiers(node)+ : undefined;++ if (+ modifiers?.some(+ (modifier) => modifier.kind === tsModule.SyntaxKind.ExportKeyword,+ )+ ) {+ diagnostics.push({+ from: node.getStart(sourceFile),+ to: node.getEnd(),+ severity: "error",+ message:+ "Exports are not supported. Define `function evaluate(ctx: EvaluationContext): EvaluationResult` instead.",+ });+ }++ node.forEachChild(visit);+ };++ sourceFile.forEachChild(visit);+}++function hasEvaluateFunction(+ sourceFile: ts.SourceFile,+ tsModule: TypeScriptModule,+) {+ let hasEvaluate = false;++ const visit = (node: ts.Node) => {+ if (+ tsModule.isFunctionDeclaration(node) &&+ node.name?.text === "evaluate"+ ) {+ hasEvaluate = true;+ }++ if (+ tsModule.isVariableStatement(node) &&+ node.declarationList.declarations.some(+ (declaration) =>+ tsModule.isIdentifier(declaration.name) &&+ declaration.name.text === "evaluate",+ )+ ) {+ hasEvaluate = true;+ }++ if (tsModule.isExportDeclaration(node) && !node.moduleSpecifier) {+ const exportClause = node.exportClause;+ if (exportClause && tsModule.isNamedExports(exportClause)) {+ hasEvaluate ||= exportClause.elements.some(+ (element) => element.name.text === "evaluate",+ );+ }+ }++ node.forEachChild(visit);+ };++ sourceFile.forEachChild(visit);++ return hasEvaluate;+}++function findEvaluatePosition(+ sourceFile: ts.SourceFile,+ tsModule: TypeScriptModule,+) {+ let position: number | undefined;++ const visit = (node: ts.Node) => {+ if (+ position === undefined &&+ tsModule.isFunctionDeclaration(node) &&+ node.name?.text === "evaluate"+ ) {+ position = node.name.getStart(sourceFile);+ return;+ }++ if (+ position === undefined &&+ tsModule.isVariableDeclaration(node) &&+ tsModule.isIdentifier(node.name) &&+ node.name.text === "evaluate"+ ) {+ position = node.name.getStart(sourceFile);+ return;+ }++ node.forEachChild(visit);+ };++ sourceFile.forEachChild(visit);++ return position;+}++function collectBasicSourceDiagnostics({+ source,+ sourceBytes,+ languageLabel,+ diagnostics,+}: {+ source: string;+ sourceBytes: number;+ languageLabel: string;+ diagnostics: CodeEvalDiagnostic[];+}) {+ if (source.trim().length === 0) {+ diagnostics.push({+ from: 0,+ to: Math.max(1, source.length),+ severity: "error",+ message: `Enter ${languageLabel} source code for the evaluator.`,+ });+ }++ if (sourceBytes > CODE_EVAL_SOURCE_MAX_BYTES) {+ diagnostics.push({+ from: 0,+ to: Math.max(1, source.length),+ severity: "error",+ message: `Source code must be ${CODE_EVAL_SOURCE_MAX_BYTES} bytes or less.`,+ });+ }+}++function collectPythonContractDiagnostics(+ source: string,+ diagnostics: CodeEvalDiagnostic[],+) {+ if (source.trim().length === 0) return;++ if (!source.trimStart().startsWith(PYTHON_CONTRACT_PREFIX)) {+ diagnostics.push({+ from: 0,+ to: Math.min(source.length, PYTHON_CONTRACT_PREFIX.length),+ severity: "warning",+ message: `Python evaluators should start with \`${PYTHON_CONTRACT_PREFIX}\`.`,+ });+ }++ if (+ hasPythonEvaluateFunction(source) &&+ !PYTHON_EVALUATE_SIGNATURE_PATTERN.test(source)+ ) {+ const evaluatePosition = findPythonEvaluatePosition(source) ?? 0;+ diagnostics.push({+ from: evaluatePosition,+ to: clampToSourceRange(source, evaluatePosition + "evaluate".length),+ severity: "warning",+ message:+ "Python evaluators should use `def evaluate(ctx: EvaluationContext) -> EvaluationResult:`.",+ });+ }+}++async function getPythonRuffWorkspace(): Promise<RuffWorkspace> {+ ruffWorkspacePromise ??= import("@astral-sh/ruff-wasm-web").then(+ async (ruffModule) => {+ await ruffModule.default();+ return new ruffModule.Workspace(+ PYTHON_RUFF_SETTINGS,+ ruffModule.PositionEncoding.Utf16,+ ) as RuffWorkspace;+ },+ );++ return ruffWorkspacePromise;+}++function hasPythonEvaluateFunction(source: string) {+ return /(?:^|\n)\s*(?:async\s+)?def\s+evaluate\s*\(/.test(source);+}++function findPythonEvaluatePosition(source: string) {+ const match = source.match(/(?:^|\n)(\s*(?:async\s+)?def\s+)(evaluate)\s*\(/);+ if (!match || match.index === undefined) return undefined;++ return match.index + match[0].indexOf("evaluate");+}++function mapRuffDiagnosticToCodeEvalDiagnostic({+ source,+ locationSource,+ diagnostic,+ offset,+}: {+ source: string;+ locationSource: string;+ diagnostic: RuffDiagnostic;+ offset: number;+}): CodeEvalDiagnostic {+ const from = clampToSourceRange(+ source,+ mapRuffLocationToSourceOffset(locationSource, diagnostic.start_location) ++ offset,+ );+ const to = Math.max(+ from + 1,+ clampToSourceRange(+ source,+ mapRuffLocationToSourceOffset(locationSource, diagnostic.end_location) ++ offset,+ ),+ );++ return {+ from,+ to,+ severity: getRuffDiagnosticSeverity(diagnostic),+ message: diagnostic.code+ ? `${diagnostic.code}: ${diagnostic.message}`+ : diagnostic.message,+ };+}++function getValidationOffset() {+ return `${PYTHON_CODE_EVAL_CONTRACT}\n\n`.length;+}++function getRuffDiagnosticSeverity(+ diagnostic: RuffDiagnostic,+): CodeEvalDiagnosticSeverity {+ const code = diagnostic.code ?? "";+ return code.startsWith("E9") || PYTHON_ERROR_DIAGNOSTIC_CODES.has(code)+ ? "error"+ : "warning";+}++function mapRuffLocationToSourceOffset(+ source: string,+ location: RuffDiagnostic["start_location"],+) {+ const lineStartOffsets = getLineStartOffsets(source);+ const rowIndex = Math.max(0, location.row - 1);+ const lineStart = lineStartOffsets[rowIndex] ?? source.length;+ const lineEnd =+ rowIndex + 1 < lineStartOffsets.length+ ? lineStartOffsets[rowIndex + 1] - 1+ : source.length;++ return clampToSourceRange(+ source,+ Math.min(lineEnd, lineStart + Math.max(0, location.column - 1)),+ );+}++function getLineStartOffsets(source: string) {+ const offsets = [0];++ for (let index = 0; index < source.length; index += 1) {+ if (source[index] === "\n") {+ offsets.push(index + 1);+ }+ }++ return offsets;+}++function clampToSourceRange(source: string, offset: number) {+ return Math.max(0, Math.min(source.length, offset));+}++function sortDiagnostics(diagnostics: CodeEvalDiagnostic[]) {+ return [...diagnostics].sort((a, b) => a.from - b.from || a.to - b.to);+}++export function getUtf8ByteLength(value: string) {+ return new TextEncoder().encode(value).length;+}diff --git a/web/src/features/evals/utils/evaluator-constants.ts b/web/src/features/evals/utils/evaluator-constants.tsindex 57e716216b..9369dad126 100644--- a/web/src/features/evals/utils/evaluator-constants.ts+++ b/web/src/features/evals/utils/evaluator-constants.ts@@ -40,6 +40,7 @@ export const OUTPUT_MAPPING = [export const INTERNAL_ENVIRONMENTS = [LangfuseInternalTraceEnvironment.LLMJudge,+ LangfuseInternalTraceEnvironment.CodeEval,"langfuse-prompt-experiment","langfuse-evaluation","sdk-experiment",diff --git a/web/src/features/evals/utils/experiment-eval-preview-utils.ts b/web/src/features/evals/utils/experiment-eval-preview-utils.tsnew file mode 100644index 0000000000..ba495c2279--- /dev/null+++ b/web/src/features/evals/utils/experiment-eval-preview-utils.ts@@ -0,0 +1,14 @@+import { type FilterCondition, type FilterState } from "@langfuse/shared";++export const EXPERIMENT_ROOT_OBSERVATION_FILTER = {+ type: "boolean",+ column: "isExperimentItemRootSpan",+ operator: "=",+ value: true,+} satisfies FilterCondition;++export function getExperimentEvalPreviewFilters(+ filter: FilterState | null | undefined,+): FilterState {+ return [...(filter ?? []), { ...EXPERIMENT_ROOT_OBSERVATION_FILTER }];+}diff --git a/web/src/features/evals/utils/template-form-schema.ts b/web/src/features/evals/utils/template-form-schema.tsnew file mode 100644index 0000000000..3af4b85881--- /dev/null+++ b/web/src/features/evals/utils/template-form-schema.ts@@ -0,0 +1,136 @@+import { z } from "zod";+import {+ EvalOutputDataTypeSchema,+ EvalTemplateSourceCodeLanguage,+ EvalTemplateType,+ extractVariables,+ getCategoricalCategoryRuleViolations,+ getMinimumCategoricalCategoriesMessage,+ ScoreDataTypeEnum,+ ZodModelConfig,+} from "@langfuse/shared";+import { EvalReferencedEvaluators } from "@/src/features/evals/types";++const selectedModelSchema = z.object({+ provider: z.string().min(1, "Select a provider"),+ model: z.string().min(1, "Select a model"),+ modelParams: ZodModelConfig,+});++const categoricalOptionSchema = z.object({+ value: z.string().trim().min(1, "Enter a category value"),+});++export const templateFormSchema = z+ .object({+ name: z.string().min(1, "Enter a name"),+ type: z+ .enum([EvalTemplateType.LLM_AS_JUDGE, EvalTemplateType.CODE])+ .default(EvalTemplateType.LLM_AS_JUDGE),+ prompt: z+ .string()+ .optional()+ .refine((val) => {+ if (!val) return true;+ const variables = extractVariables(val);+ const matches = variables.map((variable) => {+ // check regex here+ if (variable.match(/^[A-Za-z_]+$/)) {+ return true;+ }+ return false;+ });+ return !matches.includes(false);+ }, "Variables must only contain letters and underscores (_)"),++ variables: z.array(+ z.string().min(1, "Variables must have at least one character"),+ ),+ sourceCode: z.string().optional(),+ sourceCodeLanguage: z+ .enum([+ EvalTemplateSourceCodeLanguage.PYTHON,+ EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ ])+ .default(EvalTemplateSourceCodeLanguage.TYPESCRIPT),+ scoreDataType: EvalOutputDataTypeSchema.default(ScoreDataTypeEnum.NUMERIC),+ scoreDescription: z.string().optional(),+ reasoningDescription: z.string().optional(),+ categories: z.array(categoricalOptionSchema).default([]),+ shouldAllowMultipleMatches: z.boolean().default(false),+ referencedEvaluators: z+ .enum(EvalReferencedEvaluators)+ .optional()+ .default(EvalReferencedEvaluators.PERSIST),+ shouldUseDefaultModel: z.boolean().default(true),+ })+ .superRefine((value, ctx) => {+ const isCodeType = value.type === EvalTemplateType.CODE;+ const isLlmType = value.type === EvalTemplateType.LLM_AS_JUDGE;+ const isCategorical = value.scoreDataType === ScoreDataTypeEnum.CATEGORICAL;++ // ═══════════════════════════════════════════════════════════+ // CODE type: requires source code+ // ═══════════════════════════════════════════════════════════+ if (isCodeType && !value.sourceCode?.trim()) {+ const languageLabel =+ value.sourceCodeLanguage === EvalTemplateSourceCodeLanguage.PYTHON+ ? "Python"+ : "TypeScript";+ ctx.addIssue({+ code: "custom",+ message: `Enter ${languageLabel} source code`,+ path: ["sourceCode"],+ });+ }++ // ═══════════════════════════════════════════════════════════+ // LLM type: requires prompt and output definitions+ // ═══════════════════════════════════════════════════════════+ if (isLlmType) {+ if (!value.prompt?.trim()) {+ ctx.addIssue({+ code: "custom",+ message: "Enter a prompt",+ path: ["prompt"],+ });+ }+ if (!value.reasoningDescription?.trim()) {+ ctx.addIssue({+ code: "custom",+ message: "Enter a reasoning function",+ path: ["reasoningDescription"],+ });+ }+ if (!value.scoreDescription?.trim()) {+ ctx.addIssue({+ code: "custom",+ message: "Enter a score function",+ path: ["scoreDescription"],+ });+ }++ if (isCategorical) {+ const violations = getCategoricalCategoryRuleViolations(+ value.categories.map((c) => c.value),+ );+ for (const violation of violations) {+ ctx.addIssue({+ code: "custom",+ message:+ violation.type === "minimum_count"+ ? getMinimumCategoricalCategoriesMessage()+ : "Categories must be unique",+ path:+ violation.type === "minimum_count"+ ? ["categories"]+ : ["categories", violation.index, "value"],+ });+ }+ }+ }+ });++export type TemplateFormSchema = z.infer<typeof templateFormSchema>;++export { selectedModelSchema, categoricalOptionSchema };diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsxindex 44fe5fd2fd..38e8eb4032 100644--- a/web/src/features/events/components/EventsTable.tsx+++ b/web/src/features/events/components/EventsTable.tsx@@ -60,7 +60,10 @@ import TableIdOrName from "@/src/components/table/table-id";import { ItemBadge } from "@/src/components/ItemBadge";import { TablePeekViewObservationDetail } from "@/src/components/table/peek/peek-observation-detail";import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";-import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";+import {+ detailPageListKeys,+ useDetailPageLists,+} from "@/src/features/navigate-detail-pages/context";import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";import { useRouter } from "next/router";import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextSearch";@@ -482,7 +485,7 @@ export default function ObservationsEventsTable({useEffect(() => {if (observations.status === "success") {setDetailPageList(- "observations",+ detailPageListKeys.events,observations?.rows?.map((o) => ({id: o?.id,params: {@@ -1242,7 +1245,7 @@ export default function ObservationsEventsTable({if (hideControls) return undefined;return {itemType: "TRACE",- detailNavigationKey: "observations",+ detailNavigationKey: detailPageListKeys.events,...peekNavigationProps,};}, [peekNavigationProps, hideControls]);diff --git a/web/src/features/events/server/eventsRouter.ts b/web/src/features/events/server/eventsRouter.tsindex bdbf0e2319..0dd9e332ca 100644--- a/web/src/features/events/server/eventsRouter.ts+++ b/web/src/features/events/server/eventsRouter.ts@@ -189,6 +189,28 @@ export const eventsRouter = createTRPCRouter({truncated: input.truncated,});+ return batchIO.map(toDomainWithStringifiedMetadata);+ },+ );+ }),+ experimentBatchIO: protectedProjectProcedure+ .input(BatchIOInput)+ .query(async ({ input, ctx }) => {+ return instrumentAsync(+ { name: "get-experiment-batch-io-trpc" },+ async (span) => {+ span.setAttribute("project_id", input.projectId);+ span.setAttribute("observation_count", input.observations.length);++ const batchIO = await getEventBatchIO({+ projectId: ctx.session.projectId,+ observations: input.observations,+ minStartTime: input.minStartTime,+ maxStartTime: input.maxStartTime,+ truncated: input.truncated,+ includeExperimentFields: true,+ });+return batchIO.map(toDomainWithStringifiedMetadata);},);diff --git a/web/src/features/events/server/eventsService.ts b/web/src/features/events/server/eventsService.tsindex 6cf7ebe3a0..928331b91e 100644--- a/web/src/features/events/server/eventsService.ts+++ b/web/src/features/events/server/eventsService.ts@@ -564,7 +564,7 @@ export async function getEventFilterOptions(};}-interface GetEventBatchIOParams {+interface GetEventBatchIOParams<TIncludeExperiment extends boolean = false> {projectId: string;observations: Array<{id: string;@@ -573,17 +573,46 @@ interface GetEventBatchIOParams {minStartTime: Date;maxStartTime: Date;truncated?: boolean;+ includeExperimentFields?: TIncludeExperiment;}+type EventBatchIOStringOutput = Awaited<+ ReturnType<typeof getObservationsBatchIOFromEventsTable>+>[number];++type EventBatchIOWithExperimentOutput = EventBatchIOStringOutput & {+ experimentItemExpectedOutput: string | null;+ experimentItemMetadata: unknown;+};+/*** Batch fetch input/output and metadata for multiple observations*/-export async function getEventBatchIO(params: GetEventBatchIOParams) {+export async function getEventBatchIO<+ TIncludeExperiment extends boolean = false,+>(+ params: GetEventBatchIOParams<TIncludeExperiment>,+): Promise<+ Array<+ TIncludeExperiment extends true+ ? EventBatchIOWithExperimentOutput+ : EventBatchIOStringOutput+ >+> {return getObservationsBatchIOFromEventsTable({projectId: params.projectId,observations: params.observations,minStartTime: params.minStartTime,maxStartTime: params.maxStartTime,truncated: params.truncated,- });+ includeExperimentFields: params.includeExperimentFields,+ } as Parameters<typeof getObservationsBatchIOFromEventsTable>[0] & {+ includeExperimentFields?: TIncludeExperiment;+ }) as Promise<+ Array<+ TIncludeExperiment extends true+ ? EventBatchIOWithExperimentOutput+ : EventBatchIOStringOutput+ >+ >;}diff --git a/web/src/features/experiments/hooks/useExperimentEvaluatorData.ts b/web/src/features/experiments/hooks/useExperimentEvaluatorData.tsindex 7026910dab..ecf4121eab 100644--- a/web/src/features/experiments/hooks/useExperimentEvaluatorData.ts+++ b/web/src/features/experiments/hooks/useExperimentEvaluatorData.ts@@ -1,6 +1,7 @@import { useState, useCallback, useMemo } from "react";import {type EvalTemplate,+ EvalTemplateType,isJobConfigExecutable,JobConfigState,} from "@langfuse/shared";@@ -104,6 +105,9 @@ export function useExperimentEvaluatorData({...config,evalTemplate: {...config.evalTemplate,+ type: EvalTemplateType.LLM_AS_JUDGE,+ sourceCode: null,+ sourceCodeLanguage: null,outputDefinition: config.evalTemplate.outputDefinition as EvalTemplate["outputDefinition"],},diff --git a/web/src/features/filters/constants/internal-environments.ts b/web/src/features/filters/constants/internal-environments.tsindex 4bb3504e35..1a0d9705bc 100644--- a/web/src/features/filters/constants/internal-environments.ts+++ b/web/src/features/filters/constants/internal-environments.ts@@ -3,6 +3,7 @@ import { LangfuseInternalTraceEnvironment } from "@langfuse/shared";export const DEFAULT_SIDEBAR_HIDDEN_ENVIRONMENTS = [LangfuseInternalTraceEnvironment.PromptExperiments,LangfuseInternalTraceEnvironment.LLMJudge,+ LangfuseInternalTraceEnvironment.CodeEval,"langfuse-evaluation","sdk-experiment",] as const;diff --git a/web/src/features/llm-api-key/server/router.ts b/web/src/features/llm-api-key/server/router.tsindex 01475cdf21..f0ffdb89b0 100644--- a/web/src/features/llm-api-key/server/router.ts+++ b/web/src/features/llm-api-key/server/router.ts@@ -26,6 +26,7 @@ import {EvaluatorBlockReason,getEvaluatorBlockMetadata,} from "@langfuse/shared";+import { findDefaultModelEvalTemplateIds } from "@/src/features/evals/server/defaultModelEvalTemplateRepository";import { encrypt, decrypt } from "@langfuse/shared/encryption";import {ChatMessageType,@@ -351,15 +352,9 @@ export const llmApiKeyRouter = createTRPCRouter({}if (!!defaultModel && defaultModel.llmApiKeyId === llmApiKey?.id) {- const evalTemplates = await tx.evalTemplate.findMany({- where: {- OR: [{ projectId: input.projectId }, { projectId: null }],- provider: null,- model: null,- },- select: {- id: true,- },+ const evalTemplateIds = await findDefaultModelEvalTemplateIds({+ tx,+ projectId: input.projectId,});const defaultModelBlockResult = await blockEvaluatorConfigsInTx({@@ -367,7 +362,7 @@ export const llmApiKeyRouter = createTRPCRouter({projectId: input.projectId,where: {evalTemplateId: {- in: evalTemplates.map((template) => template.id),+ in: evalTemplateIds,},},blockReason: EvaluatorBlockReason.DEFAULT_EVAL_MODEL_MISSING,diff --git a/web/src/features/navigate-detail-pages/context.tsx b/web/src/features/navigate-detail-pages/context.tsxindex eacc4043c8..dfd720ea05 100644--- a/web/src/features/navigate-detail-pages/context.tsx+++ b/web/src/features/navigate-detail-pages/context.tsx@@ -5,14 +5,42 @@ import React, {useState,} from "react";-export type ListEntry = {+export const detailPageListKeys = {+ traces: "traces",+ observations: "observations",+ events: "events",+ sessions: "sessions",+ evalTemplates: "eval-templates",+} as const;++export type DetailPageListKey =+ (typeof detailPageListKeys)[keyof typeof detailPageListKeys];++export type ListEntry<+ TParams extends Partial<Record<string, string>> = Record<string, string>,+> = {id: string;- params?: Record<string, string>;+ params?: TParams;};+export type TraceDetailPageListEntry = ListEntry<{+ timestamp?: string;+}>;++export type ObservationDetailPageListEntry = ListEntry<{+ traceId: string;+ timestamp?: string;+ startTime?: string;+}>;++export type EventDetailPageListEntry = ObservationDetailPageListEntry;+interface ListContextType {detailPagelists: Record<string, Array<ListEntry>>;- setDetailPageList: (key: string, list: Array<ListEntry>) => void;+ setDetailPageList: <TEntry extends ListEntry>(+ key: string,+ list: Array<TEntry>,+ ) => void;}const DetailPageLists = createContext<ListContextType | undefined>(undefined);@@ -27,12 +55,23 @@ export function useDetailPageLists(): ListContextType {return context;}+export function useFirstDetailPageListEntry<+ TEntry extends ListEntry = ListEntry,+>(key: string | undefined): TEntry | undefined {+ const { detailPagelists } = useDetailPageLists();+ if (!key) return undefined;+ return detailPagelists[key]?.[0] as TEntry | undefined;+}+export function DetailPageListsProvider(props: PropsWithChildren) {const [detailPagelists, setLists] = useState<Record<string, Array<ListEntry>>>({});- const setDetailPageList = (key: string, list: Array<ListEntry>) => {+ const setDetailPageList = <TEntry extends ListEntry>(+ key: string,+ list: Array<TEntry>,+ ) => {setLists((prevLists) => ({ ...prevLists, [key]: list }));};diff --git a/web/src/pages/api/admin/bullmq/index.ts b/web/src/pages/api/admin/bullmq/index.tsindex ceda3c02cd..15d69377e9 100644--- a/web/src/pages/api/admin/bullmq/index.ts+++ b/web/src/pages/api/admin/bullmq/index.ts@@ -1,6 +1,7 @@import { type NextApiRequest, type NextApiResponse } from "next";import { z } from "zod";import {+ CodeEvalExecutionQueue,EvalExecutionQueue,LLMAsJudgeExecutionQueue,SecondaryEvalExecutionQueue,@@ -75,6 +76,7 @@ export default async function handler(...EvalExecutionQueue.getShardNames(),...SecondaryEvalExecutionQueue.getShardNames(),...LLMAsJudgeExecutionQueue.getShardNames(),+ ...CodeEvalExecutionQueue.getShardNames(),...TraceUpsertQueue.getShardNames(),...OtelIngestionQueue.getShardNames(),...SecondaryOtelIngestionQueue.getShardNames(),@@ -104,6 +106,10 @@ export default async function handler(queue = LLMAsJudgeExecutionQueue.getInstance({shardName: queueName,});+ } else if (queueName.startsWith(QueueName.CodeEvalExecution)) {+ queue = CodeEvalExecutionQueue.getInstance({+ shardName: queueName,+ });} else if (queueName.startsWith(QueueName.TraceUpsert)) {queue = TraceUpsertQueue.getInstance({ shardName: queueName });} else if (@@ -123,6 +129,7 @@ export default async function handler(| QueueName.EvaluationExecution| QueueName.EvaluationExecutionSecondaryQueue| QueueName.LLMAsJudgeExecution+ | QueueName.CodeEvalExecution| QueueName.TraceUpsert| QueueName.OtelIngestionQueue| QueueName.OtelIngestionSecondaryQueue@@ -170,6 +177,10 @@ export default async function handler(queue = LLMAsJudgeExecutionQueue.getInstance({shardName: queueName,});+ } else if (queueName.startsWith(QueueName.CodeEvalExecution)) {+ queue = CodeEvalExecutionQueue.getInstance({+ shardName: queueName,+ });} else if (queueName.startsWith(QueueName.TraceUpsert)) {queue = TraceUpsertQueue.getInstance({ shardName: queueName });} else if (@@ -189,6 +200,7 @@ export default async function handler(| QueueName.EvaluationExecution| QueueName.EvaluationExecutionSecondaryQueue| QueueName.LLMAsJudgeExecution+ | QueueName.CodeEvalExecution| QueueName.TraceUpsert| QueueName.OtelIngestionQueue| QueueName.OtelIngestionSecondaryQueue@@ -246,6 +258,10 @@ export default async function handler(queue = LLMAsJudgeExecutionQueue.getInstance({shardName: queueName,});+ } else if (queueName.startsWith(QueueName.CodeEvalExecution)) {+ queue = CodeEvalExecutionQueue.getInstance({+ shardName: queueName,+ });} else if (queueName.startsWith(QueueName.TraceUpsert)) {queue = TraceUpsertQueue.getInstance({ shardName: queueName });} else if (@@ -265,6 +281,7 @@ export default async function handler(| QueueName.EvaluationExecution| QueueName.EvaluationExecutionSecondaryQueue| QueueName.LLMAsJudgeExecution+ | QueueName.CodeEvalExecution| QueueName.TraceUpsert| QueueName.OtelIngestionQueue| QueueName.OtelIngestionSecondaryQueuediff --git a/web/src/pages/api/public/llm-connections/[id].ts b/web/src/pages/api/public/llm-connections/[id].tsindex a2c17f7787..cd9e36ae0f 100644--- a/web/src/pages/api/public/llm-connections/[id].ts+++ b/web/src/pages/api/public/llm-connections/[id].ts@@ -16,6 +16,7 @@ import {EvaluatorBlockSource,finalizeBlockedEvaluatorConfigBlocks,} from "@langfuse/shared/src/server";+import { findDefaultModelEvalTemplateIds } from "@/src/features/evals/server/defaultModelEvalTemplateRepository";export default withMiddlewares({DELETE: createAuthedProjectAPIRoute({@@ -75,13 +76,9 @@ export default withMiddlewares({}if (defaultModel && defaultModel.llmApiKeyId === llmApiKey.id) {- const evalTemplates = await tx.evalTemplate.findMany({- where: {- OR: [{ projectId }, { projectId: null }],- provider: null,- model: null,- },- select: { id: true },+ const evalTemplateIds = await findDefaultModelEvalTemplateIds({+ tx,+ projectId,});const defaultModelBlockResult = await blockEvaluatorConfigsInTx({@@ -89,7 +86,7 @@ export default withMiddlewares({projectId,where: {evalTemplateId: {- in: evalTemplates.map((template) => template.id),+ in: evalTemplateIds,},},blockReason: EvaluatorBlockReason.DEFAULT_EVAL_MODEL_MISSING,diff --git a/worker/src/__tests__/batchAction.test.ts b/worker/src/__tests__/batchAction.test.tsindex 9e863cbd4a..2f74a48f27 100644--- a/worker/src/__tests__/batchAction.test.ts+++ b/worker/src/__tests__/batchAction.test.ts@@ -4,6 +4,7 @@ import {BatchTableNames,BatchActionStatus,EvalTargetObject,+ EvalTemplateType,} from "@langfuse/shared";import { expect, describe, it } from "vitest";import { v4 as uuidv4 } from "uuid";@@ -673,6 +674,80 @@ describe("select all test suite", () => {});});+ it("should skip legacy eval-create for code eval templates", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ const traceId = uuidv4();+ const traceTimestamp = new Date("2024-01-01T00:00:00.000Z");+ await createTracesCh([+ createTrace({+ project_id: projectId,+ id: traceId,+ timestamp: traceTimestamp.getTime(),+ }),+ ]);++ const templateId = uuidv4();+ await prisma.evalTemplate.create({+ data: {+ id: templateId,+ projectId,+ name: "test-code-template",+ version: 1,+ type: EvalTemplateType.CODE,+ sourceCode: "return { score: 1 };",+ modelParams: {},+ },+ });++ const configId = uuidv4();+ await prisma.jobConfiguration.create({+ data: {+ id: configId,+ projectId,+ filter: [],+ jobType: "EVAL",+ delay: 0,+ sampling: new Decimal("1"),+ targetObject: EvalTargetObject.TRACE,+ scoreName: "score",+ variableMapping: JSON.parse("[]"),+ evalTemplateId: templateId,+ },+ });++ const payload = {+ id: uuidv4(),+ timestamp: new Date(),+ name: QueueJobs.BatchActionProcessingJob as const,+ payload: {+ projectId,+ actionId: "eval-create" as const,+ targetObject: EvalTargetObject.TRACE,+ configId,+ cutoffCreatedAt: new Date("2024-01-02T00:00:00.000Z"),+ query: {+ filter: [],+ orderBy: {+ column: "timestamp",+ order: "DESC" as const,+ },+ },+ },+ };++ await withIsolatedCreateEvalQueue(projectId, async (queue) => {+ await handleBatchActionJob(payload, { evalCreatorQueue: queue });++ const jobs = await waitForCreateEvalQueueJobs({+ queue,+ expectedLength: 0,+ });++ expect(jobs).toHaveLength(0);+ });+ });+it("should add traces to annotation queue", async () => {const { projectId } = await createOrgProjectAndApiKey();diff --git a/worker/src/__tests__/evalService.test.ts b/worker/src/__tests__/evalService.test.tsindex 0e2c4c5e8c..f17aa3f53b 100644--- a/worker/src/__tests__/evalService.test.ts+++ b/worker/src/__tests__/evalService.test.ts@@ -2403,11 +2403,11 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;expect(result).toEqual([{- value: '{"input":"This is a great prompt"}',+ value: { input: "This is a great prompt" },var: "input",},{- value: '{"expected_output":"This is a great response"}',+ value: { expected_output: "This is a great response" },var: "output",},]);@@ -2451,12 +2451,12 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;expect(result).toEqual([{- value: '{"input":"This is a great prompt"}',+ value: { input: "This is a great prompt" },var: "input",environment: "production",},{- value: '{"output":"This is a great response"}',+ value: { output: "This is a great response" },var: "output",environment: "production",},@@ -2516,12 +2516,12 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;expect(result).toEqual([{- value: '{"huhu":"This is a great prompt"}',+ value: { huhu: "This is a great prompt" },var: "input",environment: "production",},{- value: '{"haha":"This is a great response"}',+ value: { haha: "This is a great response" },var: "output",environment: "production",},@@ -2613,12 +2613,12 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;expect(result).toEqual([{environment: "default",- value: "",+ value: null,var: "input",},{environment: "default",- value: "",+ value: null,var: "output",},]);@@ -2694,12 +2694,12 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;expect(result).toEqual([{environment: "default",- value: '{"huhu":"This is a great prompt again"}',+ value: { huhu: "This is a great prompt again" },var: "input",},{environment: "default",- value: '{"haha":"This is a great response again"}',+ value: { haha: "This is a great response again" },var: "output",},]);@@ -2764,12 +2764,12 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;expect(result).toEqual([{- value: '{"huhu":"This is a great prompt"}',+ value: { huhu: "This is a great prompt" },var: "input",environment: "production",},{- value: '{"haha":"This is a great response"}',+ value: { haha: "This is a great response" },var: "output",environment: "production",},@@ -2852,7 +2852,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;expect(resultV1).toEqual([{- value: '{"expected_output":"v1 expected output"}',+ value: { expected_output: "v1 expected output" },var: "output",},]);@@ -2868,7 +2868,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;expect(resultLatest).toEqual([{- value: '{"expected_output":"v2 expected output"}',+ value: { expected_output: "v2 expected output" },var: "output",},]);@@ -3181,9 +3181,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;job_execution_id: jobExecutionId,job_configuration_id: configId,target_trace_id: traceId,- score_id: capturedTraceSinkParams.metadata.score_id,});- expect(capturedTraceSinkParams.metadata.score_id).toBeDefined();}, 15_000);});diff --git a/worker/src/app.ts b/worker/src/app.tsindex 2d6c5b71d2..940424f895 100644--- a/worker/src/app.ts+++ b/worker/src/app.ts@@ -15,6 +15,7 @@ import {evalJobTraceCreatorQueueProcessor,llmAsJudgeExecutionQueueProcessorBuilder,} from "./queues/evalQueue";+import { codeEvalExecutionQueueProcessorBuilder } from "./queues/codeEvalQueue";import { batchExportQueueProcessor } from "./queues/batchExportQueue";import { onShutdown } from "./utils/shutdown";import helmet from "helmet";@@ -43,6 +44,7 @@ import {EvalExecutionQueue,SecondaryEvalExecutionQueue,LLMAsJudgeExecutionQueue,+ CodeEvalExecutionQueue,} from "@langfuse/shared/src/server";import { env } from "./env";import { ingestionQueueProcessorBuilder } from "./queues/ingestionQueue";@@ -271,6 +273,22 @@ if (env.QUEUE_CONSUMER_EVAL_EXECUTION_QUEUE_IS_ENABLED === "true") {});}+if (env.QUEUE_CONSUMER_CODE_EVAL_EXECUTION_QUEUE_IS_ENABLED === "true") {+ const codeEvalShardNames = CodeEvalExecutionQueue.getShardNames();+ codeEvalShardNames.forEach((shardName) => {+ WorkerManager.register(+ shardName as QueueName,+ codeEvalExecutionQueueProcessorBuilder(shardName),+ {+ concurrency: env.LANGFUSE_CODE_EVAL_EXECUTION_WORKER_CONCURRENCY,+ lockDuration: 60000,+ stalledInterval: 120000,+ maxStalledCount: 3,+ },+ );+ });+}+if (env.QUEUE_CONSUMER_EVAL_EXECUTION_SECONDARY_QUEUE_IS_ENABLED === "true") {const shardNames = SecondaryEvalExecutionQueue.getShardNames();shardNames.forEach((shardName) => {diff --git a/worker/src/env.ts b/worker/src/env.tsindex 3cdab3b60b..f4883ff0f8 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -132,6 +132,10 @@ const EnvSchema = z.object({.number().positive().default(5),+ LANGFUSE_CODE_EVAL_EXECUTION_WORKER_CONCURRENCY: z.coerce+ .number()+ .positive()+ .default(5),LANGFUSE_EVAL_EXECUTION_SECONDARY_QUEUE_PROCESSING_CONCURRENCY: z.coerce.number().positive()@@ -206,6 +210,9 @@ const EnvSchema = z.object({QUEUE_CONSUMER_EVAL_EXECUTION_SECONDARY_QUEUE_IS_ENABLED: z.enum(["true", "false"]).default("true"),+ QUEUE_CONSUMER_CODE_EVAL_EXECUTION_QUEUE_IS_ENABLED: z+ .enum(["true", "false"])+ .default("true"),QUEUE_CONSUMER_TRACE_UPSERT_QUEUE_IS_ENABLED: z.enum(["true", "false"]).default("true"),diff --git a/worker/src/features/batchAction/handleBatchActionJob.ts b/worker/src/features/batchAction/handleBatchActionJob.tsindex faeb54d801..58d349dc8d 100644--- a/worker/src/features/batchAction/handleBatchActionJob.ts+++ b/worker/src/features/batchAction/handleBatchActionJob.ts@@ -1,6 +1,7 @@import {BatchActionProcessingEventType,CreateEvalQueue,+ getEventsStreamForEval,getCurrentSpan,logger,QueueJobs,@@ -14,6 +15,7 @@ import {BatchTableNames,FilterCondition,EvalTargetObject,+ EvalTemplateType,} from "@langfuse/shared";import Decimal from "decimal.js";import {@@ -32,7 +34,6 @@ import { randomUUID } from "node:crypto";import { processClickhouseScoreDelete } from "../scores/processClickhouseScoreDelete";import { getObservationStream } from "../database-read-stream/observation-stream";import {- getEventsStreamForEval,getEventsStreamForDataset,getEventsStreamForAnnotationQueue,} from "../database-read-stream/event-stream";@@ -229,6 +230,14 @@ export const handleBatchActionJob = async (id: configId,projectId: projectId,},+ select: {+ delay: true,+ evalTemplate: {+ select: {+ type: true,+ },+ },+ },});if (!config) {@@ -238,6 +247,15 @@ export const handleBatchActionJob = async (return;}+ if (config.evalTemplate?.type !== EvalTemplateType.LLM_AS_JUDGE) {+ logger.info(`Skipping legacy eval-create for non-LLM eval template`, {+ projectId,+ configId,+ evalTemplateType: config.evalTemplate?.type ?? null,+ });+ return;+ }+const dbReadStream =targetObject === EvalTargetObject.TRACE? await getTraceIdentifierStream({@@ -393,6 +411,7 @@ export const handleBatchActionJob = async (where: {id: { in: selectedEvaluatorIds },projectId,+ evalTemplateId: { not: null },// Preserve the selected evaluators as-is. Executability is checked// later when each scheduling attempt runs.},@@ -400,6 +419,11 @@ export const handleBatchActionJob = async (id: true,projectId: true,evalTemplateId: true,+ evalTemplate: {+ select: {+ type: true,+ },+ },scoreName: true,targetObject: true,variableMapping: true,@@ -413,6 +437,7 @@ export const handleBatchActionJob = async (// sampling=1 to ensure every streamed observation is evaluated.evaluators = rawEvaluators.map((e) => ({...e,+ evalTemplate: e.evalTemplate!,filter: [] as [],sampling: new Decimal(1),}));diff --git a/worker/src/features/batchAction/processBatchedObservationEval.test.ts b/worker/src/features/batchAction/processBatchedObservationEval.test.tsindex dbb3aac6f8..2e9dbb702e 100644--- a/worker/src/features/batchAction/processBatchedObservationEval.test.ts+++ b/worker/src/features/batchAction/processBatchedObservationEval.test.ts@@ -1,5 +1,9 @@import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";-import { EvalTargetObject, JobConfigState } from "@langfuse/shared";+import {+ EvalTargetObject,+ EvalTemplateType,+ JobConfigState,+} from "@langfuse/shared";import { type ObservationEvalConfig } from "../evaluation/observationEval";vi.mock("@langfuse/shared/src/db", () => ({@@ -38,6 +42,7 @@ describe("processBatchedObservationEval", () => {filter: [],sampling: { toNumber: () => 1 } as ObservationEvalConfig["sampling"],evalTemplateId: "template-1",+ evalTemplate: { type: EvalTemplateType.LLM_AS_JUDGE },scoreName: "quality",targetObject: EvalTargetObject.EVENT,variableMapping: [],@@ -97,6 +102,7 @@ describe("processBatchedObservationEval", () => {filter: [],sampling: { toNumber: () => 1 } as ObservationEvalConfig["sampling"],evalTemplateId: "template-1",+ evalTemplate: { type: EvalTemplateType.LLM_AS_JUDGE },scoreName: "quality",targetObject: EvalTargetObject.EVENT,variableMapping: [],diff --git a/worker/src/features/database-read-stream/event-stream.ts b/worker/src/features/database-read-stream/event-stream.tsindex 1cf53f87d0..d15aa693fe 100644--- a/worker/src/features/database-read-stream/event-stream.ts+++ b/worker/src/features/database-read-stream/event-stream.ts@@ -360,152 +360,6 @@ export const getEventsStream = async (props: {);};-/**- * Lightweight event stream for batch observation evaluation.- * Unlike getEventsStream, this:- * - Uses the "eval" field set (no time/latency/modelId columns)- * - Skips scores CTE and JOIN- * - Skips comment fetching- * - Maps ClickHouse rows to ObservationForEval at the stream boundary- */-export const getEventsStreamForEval = async (props: {- projectId: string;- cutoffCreatedAt: Date;- filter: FilterCondition[] | null;- searchQuery?: string;- searchType?: TracingSearchType[];- rowLimit?: number;-}): Promise<Readable> => {- const {- projectId,- cutoffCreatedAt,- filter = [],- searchQuery,- searchType,- rowLimit = env.LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT,- } = props;-- // Filter out score and comment filters since they're not relevant for eval- const eventOnlyFilters = (filter ?? []).filter((f) => {- const columnDef = eventsTableUiColumnDefinitions.find(- (col) => col.uiTableName === f.column || col.uiTableId === f.column,- );-- return (- columnDef?.clickhouseTableName !== "scores" &&- columnDef?.clickhouseTableName !== "comments"- );- });-- const eventsFilter = new FilterList(- createFilterFromFilterState(- [- ...eventOnlyFilters,- {- column: "startTime",- operator: "<" as const,- value: cutoffCreatedAt,- type: "datetime" as const,- },- ],- eventsTableUiColumnDefinitions,- eventsTableCols,- ),- );-- const appliedEventsFilter = eventsFilter.apply();-- const search = eventSearchCondition({- query: searchQuery,- searchType,- });-- const eventsQuery = new EventsQueryBuilder({ projectId })- .selectFieldSet("eval")- .selectIO(false)- .selectFieldSet("metadata")- .when(search.requiresEventsFull, (b) => b.forceFullTable())- .where(appliedEventsFilter)- .where(search)- .whereRaw("e.is_deleted = 0")- .orderByDefault()- .limitBy("e.span_id", "e.project_id")- .limit(rowLimit);-- const { query, params: queryParams } = eventsQuery.buildWithParams();-- // Matches the aliased columns from the "eval" field set + selectIO + selectFieldSet("metadata")- type EvalEventRow = {- id: string; // aliased from span_id- trace_id: string;- project_id: string;- parent_observation_id: string | null; // aliased from parent_span_id- type: string;- name: string | null;- environment: string | null;- version: string | null;- level: string;- status_message: string | null;- trace_name: string | null;- user_id: string | null;- session_id: string | null;- tags: string[];- release: string | null;- provided_model_name: string | null;- model_parameters: unknown;- prompt_id: string | null;- prompt_name: string | null;- prompt_version: number | null;- provided_usage_details: Record<string, number>;- usage_details: Record<string, number>;- provided_cost_details: Record<string, number>;- cost_details: Record<string, number>;- tool_definitions: Record<string, unknown>;- tool_calls: unknown[];- tool_call_names: string[];- input: unknown;- output: unknown;- metadata: Record<string, unknown> | null;- experiment_id: string | null;- experiment_item_root_span_id: string | null;- experiment_item_expected_output: string | null;- experiment_item_metadata: Record<string, unknown> | null;- };-- const asyncGenerator = queryClickhouseStream<EvalEventRow>({- query,- params: queryParams,- clickhouseConfigs: {- request_timeout: 180_000,- clickhouse_settings: {- http_send_timeout: 300,- http_receive_timeout: 300,- },- },- tags: {- feature: "batch-eval",- type: "event",- kind: "eval",- projectId,- },- preferredClickhouseService: "EventsReadOnly",- });-- // Remap ClickHouse aliases to schema field names.- // Schema validation is left to the consumer so per-row errors can be handled gracefully.- return Readable.from(- (async function* () {- for await (const row of asyncGenerator) {- yield {- ...row,- span_id: row.id,- parent_span_id: row.parent_observation_id,- };- }- })(),- );-};-/*** Lightweight event stream for batch add-to-dataset.* Only fetches the fields needed for dataset item creation:diff --git a/worker/src/features/evaluation/__tests__/extractValueFromObject.test.ts b/worker/src/features/evaluation/__tests__/extractValueFromObject.test.tsindex dfaf1dc9a8..979005e7c1 100644--- a/worker/src/features/evaluation/__tests__/extractValueFromObject.test.ts+++ b/worker/src/features/evaluation/__tests__/extractValueFromObject.test.ts@@ -1,5 +1,8 @@import { describe, it, expect } from "vitest";-import { extractValueFromObject } from "@langfuse/shared";+import {+ extractValueFromObjectAsString,+ extractValueFromObject,+} from "@langfuse/shared";describe("extractValueFromObject", () => {describe("JSONPath slice expressions returning multiple elements", () => {@@ -13,9 +16,7 @@ describe("extractValueFromObject", () => {};const result = extractValueFromObject(obj, "data", "$[1:]");- expect(result.value).toBe(- JSON.stringify([{ role: "ai" }, { role: "human" }]),- );+ expect(result.value).toEqual([{ role: "ai" }, { role: "human" }]);expect(result.error).toBeNull();});@@ -29,7 +30,7 @@ describe("extractValueFromObject", () => {};const result = extractValueFromObject(obj, "data", "$[*].role");- expect(result.value).toBe(JSON.stringify(["human", "ai", "human"]));+ expect(result.value).toEqual(["human", "ai", "human"]);expect(result.error).toBeNull();});@@ -39,7 +40,7 @@ describe("extractValueFromObject", () => {};const result = extractValueFromObject(obj, "data", "$[0:2]");- expect(result.value).toBe(JSON.stringify(["a", "b"]));+ expect(result.value).toEqual(["a", "b"]);expect(result.error).toBeNull();});});@@ -71,27 +72,27 @@ describe("extractValueFromObject", () => {};const result = extractValueFromObject(obj, "data", "$.nested");- expect(result.value).toBe(JSON.stringify({ key: "value" }));+ expect(result.value).toEqual({ key: "value" });expect(result.error).toBeNull();});});describe("empty result handling", () => {- it("should return empty string for non-matching JSONPath", () => {+ it("should return undefined for non-matching JSONPath", () => {const obj = {data: JSON.stringify({ name: "Alice" }),};const result = extractValueFromObject(obj, "data", "$.nonexistent");- expect(result.value).toBe("");+ expect(result.value).toBeUndefined();expect(result.error).toBeNull();});- it("should return empty string when column does not exist", () => {+ it("should return undefined when column does not exist", () => {const obj = { other: "value" };const result = extractValueFromObject(obj, "missing");- expect(result.value).toBe("");+ expect(result.value).toBeUndefined();expect(result.error).toBeNull();});});@@ -111,19 +112,19 @@ describe("extractValueFromObject", () => {const obj = { data: 42 };const result = extractValueFromObject(obj, "data", "$.field");- expect(result.value).toBe("42");+ expect(result.value).toBe(42);expect(result.error).toBeNull();});});describe("no JSON selector", () => {- it("should return stringified object when no selector is provided", () => {+ it("should return object as-is when no selector is provided", () => {const obj = {data: { key: "value" },};const result = extractValueFromObject(obj, "data");- expect(result.value).toBe(JSON.stringify({ key: "value" }));+ expect(result.value).toEqual({ key: "value" });expect(result.error).toBeNull();});@@ -135,11 +136,11 @@ describe("extractValueFromObject", () => {expect(result.error).toBeNull();});- it("should return number as string", () => {+ it("should return number as-is", () => {const obj = { data: 42 };const result = extractValueFromObject(obj, "data");- expect(result.value).toBe("42");+ expect(result.value).toBe(42);expect(result.error).toBeNull();});});@@ -156,4 +157,28 @@ describe("extractValueFromObject", () => {expect(result.error).toBeNull();});});++ describe("extractValueFromObjectAsString", () => {+ it("should preserve string extraction behavior for prompt previews", () => {+ const obj = {+ object: { key: "value", count: 42 },+ array: ["a", "b"],+ zero: 0,+ falseValue: false,+ missing: null,+ };++ expect(extractValueFromObjectAsString(obj, "object").value).toBe(+ '{"key":"value","count":42}',+ );+ expect(extractValueFromObjectAsString(obj, "array").value).toBe(+ '["a","b"]',+ );+ expect(extractValueFromObjectAsString(obj, "zero").value).toBe("0");+ expect(extractValueFromObjectAsString(obj, "falseValue").value).toBe(+ "false",+ );+ expect(extractValueFromObjectAsString(obj, "missing").value).toBe("");+ });+ });});diff --git a/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.integration.test.ts b/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.integration.test.tsnew file mode 100644index 0000000000..68168d796c--- /dev/null+++ b/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.integration.test.ts@@ -0,0 +1,128 @@+import { describe, expect, it } from "vitest";+import {+ AwsLambdaCodeEvalDispatcher,+ CodeEvalDispatcherError,+ type CodeEvalRuntimeLanguage,+ type DispatchInput,+} from "@langfuse/shared/src/server";++const endpoint = process.env.LANGFUSE_CODE_EVAL_AWS_LAMBDA_ENDPOINT;+const describeWithFloci = endpoint ? describe : describe.skip;++process.env.AWS_ACCESS_KEY_ID ??= "test";+process.env.AWS_SECRET_ACCESS_KEY ??= "test";+process.env.AWS_REGION ??= "us-east-1";++const baseInput: DispatchInput = {+ scope: {+ organizationId: "org-floci-integration",+ projectId: "project-floci-integration",+ evaluatorId: "evaluator-floci-integration",+ },+ runtime: { language: "TYPESCRIPT" },+ execution: { jobExecutionId: "job-floci-integration" },+ code: { source: "function evaluate() {}" },+ payload: {+ observation: {+ input: "hello",+ output: "hello world",+ metadata: { topic: "integration" },+ },+ experiment: {+ itemExpectedOutput: "hello world",+ itemMetadata: { item: 42 },+ },+ },+};++// Each runner returns the same logical scores so we can share assertions.+// BOOLEAN variants cover every accepted input shape: native boolean,+// already-encoded 0/1, and string form ("true"). All normalize to 1.+const expectedScores = [+ { name: "output-contains-input-bool", value: 1, dataType: "BOOLEAN" },+ { name: "output-contains-input-int", value: 1, dataType: "BOOLEAN" },+ { name: "output-contains-input-str", value: 1, dataType: "BOOLEAN" },+ { name: "integration", value: 42, dataType: "NUMERIC" },+ {+ name: "expected-output",+ value: "hello world",+ dataType: "TEXT",+ metadata: { source: "runner-fixture" },+ },+ { name: "rating", value: "good", dataType: "CATEGORICAL" },+] as const;++const sources: Record<CodeEvalRuntimeLanguage, string> = {+ TYPESCRIPT: `+function evaluate(ctx: {+ observation: {+ input: string;+ output: string;+ metadata: { topic: string };+ };+ experiment: {+ itemExpectedOutput: string;+ itemMetadata: { item: number };+ } | undefined;+}) {+ const contains = ctx.observation.output.includes(ctx.observation.input);+ return {+ scores: [+ { name: "output-contains-input-bool", value: contains, dataType: "BOOLEAN" },+ { name: "output-contains-input-int", value: contains ? 1 : 0, dataType: "BOOLEAN" },+ { name: "output-contains-input-str", value: contains ? "True" : "False", dataType: "BOOLEAN" },+ { name: ctx.observation.metadata.topic, value: ctx.experiment?.itemMetadata.item ?? 0, dataType: "NUMERIC" },+ { name: "expected-output", value: ctx.experiment?.itemExpectedOutput ?? "", dataType: "TEXT", metadata: { source: "runner-fixture" } },+ { name: "rating", value: "good", dataType: "CATEGORICAL" },+ ],+ };+}+`,+ PYTHON: `+def evaluate(ctx):+ contains = ctx.observation.input in ctx.observation.output+ return {+ "scores": [+ {"name": "output-contains-input-bool", "value": contains, "dataType": "BOOLEAN"},+ {"name": "output-contains-input-int", "value": 1 if contains else 0, "dataType": "BOOLEAN"},+ {"name": "output-contains-input-str", "value": "true" if contains else "false", "dataType": "BOOLEAN"},+ {"name": ctx.observation.metadata["topic"], "value": ctx.experiment.item_metadata["item"], "dataType": "NUMERIC"},+ Score(name="expected-output", value=ctx.experiment.item_expected_output, data_type="TEXT", metadata={"source": "runner-fixture"}),+ {"name": "rating", "value": "good", "dataType": "CATEGORICAL"},+ ],+ }+`,+};++describeWithFloci("AwsLambdaCodeEvalDispatcher Floci integration", () => {+ const dispatcher = new AwsLambdaCodeEvalDispatcher({ endpoint });++ it.each<CodeEvalRuntimeLanguage>(["TYPESCRIPT", "PYTHON"])(+ "passes the payload and returns all score types for the %s runner",+ async (language) => {+ await expect(+ dispatcher.dispatch({+ ...baseInput,+ runtime: { language },+ code: { source: sources[language] },+ }),+ ).resolves.toEqual({ scores: expectedScores });+ },+ );++ it("preserves runner error classifications", async () => {+ await expect(+ dispatcher.dispatch({+ ...baseInput,+ runtime: { language: "TYPESCRIPT" },+ code: {+ source: `function evaluate() { throw new Error("boom") }`,+ },+ }),+ ).rejects.toMatchObject({+ code: "USER_CODE_ERROR",+ message: "boom",+ retryable: false,+ } satisfies Partial<CodeEvalDispatcherError>);+ });+});diff --git a/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.test.ts b/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.test.tsnew file mode 100644index 0000000000..3db8656504--- /dev/null+++ b/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.test.ts@@ -0,0 +1,386 @@+import { describe, expect, it, vi } from "vitest";+import {+ AwsLambdaCodeEvalDispatcher,+ CodeEvalDispatcherError,+ type DispatchInput,+} from "@langfuse/shared/src/server";++const baseInput: DispatchInput = {+ scope: {+ organizationId: "org-1",+ projectId: "project-1",+ evaluatorId: "evaluator-1",+ },+ runtime: { language: "TYPESCRIPT" },+ execution: { jobExecutionId: "job-1" },+ code: { source: "function evaluate() {}" },+ payload: {+ observation: {+ input: null,+ output: null,+ metadata: null,+ },+ },+};++describe("AwsLambdaCodeEvalDispatcher", () => {+ it("returns successful Lambda scores", async () => {+ const send = vi.fn().mockResolvedValue({+ Payload: Buffer.from(+ JSON.stringify({+ scores: [+ {+ name: "lambda-score",+ value: 1,+ dataType: "NUMERIC",+ metadata: { source: "lambda-fixture" },+ },+ ],+ }),+ ),+ });+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send } as any,+ });++ await expect(dispatcher.dispatch(baseInput)).resolves.toEqual({+ scores: [+ {+ name: "lambda-score",+ value: 1,+ dataType: "NUMERIC",+ metadata: { source: "lambda-fixture" },+ },+ ],+ });+ });++ it("propagates TenantId derived from scope.organizationId:projectId", async () => {+ const send = vi.fn().mockResolvedValue({+ Payload: Buffer.from(+ JSON.stringify({+ scores: [{ name: "score", value: 1, dataType: "NUMERIC" }],+ }),+ ),+ });+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send } as any,+ });++ await dispatcher.dispatch(baseInput);+ expect(send.mock.calls[0][0].input.TenantId).toBe("org-1:project-1");+ });++ it("sends the nested evaluation context payload to Lambda", async () => {+ const send = vi.fn().mockResolvedValue({+ Payload: Buffer.from(+ JSON.stringify({+ scores: [{ name: "score", value: 1, dataType: "NUMERIC" }],+ }),+ ),+ });+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send } as any,+ });+ const input: DispatchInput = {+ ...baseInput,+ payload: {+ observation: {+ input: { question: "2+2" },+ output: "4",+ metadata: { source: "test" },+ },+ experiment: {+ itemExpectedOutput: "4",+ itemMetadata: { difficulty: "easy" },+ },+ },+ };++ await dispatcher.dispatch(input);++ const lambdaPayload = JSON.parse(+ Buffer.from(send.mock.calls[0][0].input.Payload).toString("utf8"),+ );+ expect(lambdaPayload.payload).toEqual(input.payload);+ });++ it("prefers a valid dispatch result over an injected error envelope", async () => {+ // Defense in depth against runners that try to smuggle an `error`+ // envelope alongside valid scores to force a retry or mask the+ // outcome with a masked LAMBDA_* code.+ const send = vi.fn().mockResolvedValue({+ Payload: Buffer.from(+ JSON.stringify({+ scores: [{ name: "score", value: 1, dataType: "NUMERIC" }],+ error: {+ code: "LAMBDA_CONCURRENCY_LIMIT",+ message: "attacker-controlled",+ },+ }),+ ),+ });+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send } as any,+ });++ await expect(dispatcher.dispatch(baseInput)).resolves.toEqual({+ scores: [{ name: "score", value: 1, dataType: "NUMERIC" }],+ });+ });++ it("uses configured function names per runtime", async () => {+ const send = vi.fn().mockResolvedValue({+ Payload: Buffer.from(+ JSON.stringify({+ scores: [{ name: "score", value: 1, dataType: "NUMERIC" }],+ }),+ ),+ });+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send } as any,+ functionNameByLanguage: {+ PYTHON: "custom-python-fn",+ TYPESCRIPT: "custom-node-fn",+ },+ });++ await dispatcher.dispatch(baseInput);+ expect(send.mock.calls[0][0].input.FunctionName).toBe("custom-node-fn");++ await dispatcher.dispatch({+ ...baseInput,+ runtime: { language: "PYTHON" },+ });+ expect(send.mock.calls[1][0].input.FunctionName).toBe("custom-python-fn");+ });++ it("classifies typed user-code runner errors as non-retryable", async () => {+ const send = vi.fn().mockResolvedValue({+ FunctionError: "Handled",+ Payload: Buffer.from(+ JSON.stringify({+ error: { code: "USER_CODE_ERROR", message: "ReferenceError: x" },+ }),+ ),+ });+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send } as any,+ });++ await expect(dispatcher.dispatch(baseInput)).rejects.toMatchObject({+ code: "USER_CODE_ERROR",+ message: "ReferenceError: x",+ retryable: false,+ } satisfies Partial<CodeEvalDispatcherError>);+ });++ it("classifies successful runner error envelopes", async () => {+ const send = vi.fn().mockResolvedValue({+ Payload: Buffer.from(+ JSON.stringify({+ error: { code: "USER_CODE_ERROR", message: "ReferenceError: x" },+ }),+ ),+ });+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send } as any,+ });++ await expect(dispatcher.dispatch(baseInput)).rejects.toMatchObject({+ code: "USER_CODE_ERROR",+ message: "ReferenceError: x",+ retryable: false,+ } satisfies Partial<CodeEvalDispatcherError>);+ });++ it("classifies timeouts via errorType Function.TimedOut as retryable", async () => {+ // Envelope shape captured empirically from Floci probes.+ const send = vi.fn().mockResolvedValue({+ FunctionError: "Unhandled",+ Payload: Buffer.from(+ JSON.stringify({+ errorMessage: "Task timed out after 30 seconds",+ errorType: "Function.TimedOut",+ }),+ ),+ });+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send } as any,+ });++ await expect(dispatcher.dispatch(baseInput)).rejects.toMatchObject({+ code: "TIMEOUT",+ message: "Function.TimedOut: Task timed out after 30 seconds",+ retryable: true,+ } satisfies Partial<CodeEvalDispatcherError>);+ });++ it("classifies timeouts via errorType Sandbox.Timedout as retryable", async () => {+ const send = vi.fn().mockResolvedValue({+ FunctionError: "Unhandled",+ Payload: Buffer.from(+ JSON.stringify({+ errorMessage: "Task timed out after 30 seconds",+ errorType: "Sandbox.Timedout",+ }),+ ),+ });+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send } as any,+ });++ await expect(dispatcher.dispatch(baseInput)).rejects.toMatchObject({+ code: "TIMEOUT",+ message: "Sandbox.Timedout: Task timed out after 30 seconds",+ retryable: true,+ } satisfies Partial<CodeEvalDispatcherError>);+ });++ it("classifies timeouts via errorMessage substring as retryable", async () => {+ // Defensive fallback for runtimes that don't populate errorType.+ const send = vi.fn().mockResolvedValue({+ FunctionError: "Unhandled",+ Payload: Buffer.from(JSON.stringify({ errorMessage: "Task timed out" })),+ });+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send } as any,+ });++ await expect(dispatcher.dispatch(baseInput)).rejects.toMatchObject({+ code: "TIMEOUT",+ retryable: true,+ } satisfies Partial<CodeEvalDispatcherError>);+ });++ it("classifies Runtime.ExitError as non-retryable LAMBDA_CONFIGURATION_ERROR", async () => {+ // Documented Lambda RIC errorType for abnormal runtime termination+ // (OOM kill, segfault, process.exit). Retrying never recovers.+ const send = vi.fn().mockResolvedValue({+ FunctionError: "Unhandled",+ Payload: Buffer.from(+ JSON.stringify({+ errorMessage:+ "RequestId: abc Error: Runtime exited with error: signal: killed",+ errorType: "Runtime.ExitError",+ }),+ ),+ });+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send } as any,+ });++ await expect(dispatcher.dispatch(baseInput)).rejects.toMatchObject({+ code: "LAMBDA_CONFIGURATION_ERROR",+ retryable: false,+ } satisfies Partial<CodeEvalDispatcherError>);+ });++ it("classifies FunctionError=Handled without runner envelope as USER_CODE_ERROR", async () => {+ // Managed runtime caught a user-code exception that escaped our+ // handler's try/catch (e.g. async unhandled rejection). The envelope+ // carries the language-specific exception type+message.+ const send = vi.fn().mockResolvedValue({+ FunctionError: "Handled",+ Payload: Buffer.from(+ JSON.stringify({+ errorMessage: "x is not defined",+ errorType: "ReferenceError",+ }),+ ),+ });+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send } as any,+ });++ await expect(dispatcher.dispatch(baseInput)).rejects.toMatchObject({+ code: "USER_CODE_ERROR",+ message: "ReferenceError: x is not defined",+ retryable: false,+ } satisfies Partial<CodeEvalDispatcherError>);+ });++ it("classifies concurrency throttling as retryable", async () => {+ const error = new Error("Rate exceeded");+ error.name = "TooManyRequestsException";+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send: vi.fn().mockRejectedValue(error) } as any,+ });++ await expect(dispatcher.dispatch(baseInput)).rejects.toMatchObject({+ code: "LAMBDA_CONCURRENCY_LIMIT",+ retryable: true,+ } satisfies Partial<CodeEvalDispatcherError>);+ });++ it("classifies Node network timeout error codes as retryable invocation errors", async () => {+ const error = Object.assign(new Error("connect ETIMEDOUT"), {+ code: "ETIMEDOUT",+ });+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send: vi.fn().mockRejectedValue(error) } as any,+ });++ await expect(dispatcher.dispatch(baseInput)).rejects.toMatchObject({+ code: "LAMBDA_INVOCATION_ERROR",+ retryable: true,+ } satisfies Partial<CodeEvalDispatcherError>);+ });++ it("classifies Lambda configuration errors as non-retryable", async () => {+ const error = new Error("Function not found");+ error.name = "ResourceNotFoundException";+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send: vi.fn().mockRejectedValue(error) } as any,+ });++ await expect(dispatcher.dispatch(baseInput)).rejects.toMatchObject({+ code: "LAMBDA_CONFIGURATION_ERROR",+ retryable: false,+ } satisfies Partial<CodeEvalDispatcherError>);+ });++ it("classifies AWS-side payload-too-large rejection as PAYLOAD_TOO_LARGE", async () => {+ // If a request slips past our local `assertDispatchInputWithinLimits`+ // (5.5 MB) and AWS still rejects it at the 6 MB sync-invocation limit,+ // the failure should surface under the same `PAYLOAD_TOO_LARGE` code as+ // the local pre-check — same cause, same fix, same non-retryability.+ const error = new Error("Payload exceeds maximum allowed size");+ error.name = "RequestTooLargeException";+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send: vi.fn().mockRejectedValue(error) } as any,+ });++ await expect(dispatcher.dispatch(baseInput)).rejects.toMatchObject({+ code: "PAYLOAD_TOO_LARGE",+ retryable: false,+ } satisfies Partial<CodeEvalDispatcherError>);+ });++ it("rejects Lambda responses that exceed the wire byte-size limit", async () => {+ // Build a response payload larger than the 256 KiB result cap. The+ // guard inspects `response.Payload.byteLength` before any JSON parsing,+ // so it should fail fast as a non-retryable `RESULT_TOO_LARGE` without+ // ever allocating the parsed object.+ const oversizedBody = JSON.stringify({+ scores: [+ {+ name: "oversized-score",+ value: "a".repeat(512 * 1024),+ dataType: "CATEGORICAL",+ },+ ],+ });+ const send = vi.fn().mockResolvedValue({+ Payload: Buffer.from(oversizedBody),+ });+ const dispatcher = new AwsLambdaCodeEvalDispatcher({+ lambdaClient: { send } as any,+ });++ await expect(dispatcher.dispatch(baseInput)).rejects.toMatchObject({+ code: "RESULT_TOO_LARGE",+ retryable: false,+ } satisfies Partial<CodeEvalDispatcherError>);+ });+});diff --git a/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.test.ts b/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.test.tsnew file mode 100644index 0000000000..39c8edf6eb--- /dev/null+++ b/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.test.ts@@ -0,0 +1,595 @@+import { describe, expect, it, beforeEach, vi } from "vitest";+import {+ EvalTemplateSourceCodeLanguage,+ EvalTemplateType,+} from "@prisma/client";+import {+ CodeEvalDispatcherError,+ CodeEvalDispatcherErrorCodes,+} from "../../../../../packages/shared/src/server/evals/codeEvalDispatcherTypes";+import { CodeEvalExecutionError } from "../../../../../packages/shared/src/server/evals/codeEvalExecution";+import { UnrecoverableError } from "../../../errors/UnrecoverableError";++const mocks = vi.hoisted(() => ({+ dispatcher: {+ name: "test-dispatcher",+ dispatch: vi.fn(),+ },+ writeInternalTrace: vi.fn(),+ createW3CTraceId: vi.fn(() => "execution-trace-1"),+ span: {+ setAttribute: vi.fn(),+ },+}));++vi.mock("@langfuse/shared/src/server", async (importOriginal) => {+ const actual =+ await importOriginal<typeof import("@langfuse/shared/src/server")>();+ const { CodeEvalExecutionError, runCodeBasedEvaluationDispatch } =+ await import("../../../../../packages/shared/src/server/evals/codeEvalExecution");++ return {+ ...actual,+ CodeEvalExecutionError,+ INTERNAL_TRACE_EVENT_SOURCE: "test-source",+ LangfuseInternalTraceEnvironment: { CodeEval: "langfuse-code-eval" },+ instrumentAsync: vi.fn(async (_options, fn) => fn(mocks.span)),+ logger: { debug: vi.fn(), warn: vi.fn() },+ createW3CTraceId: mocks.createW3CTraceId,+ runCodeBasedEvaluationDispatch,+ resolveConfiguredCodeEvalDispatcher: vi.fn(() => mocks.dispatcher),+ };+});++vi.mock("../../internal-tracing/createInternalEventsWriter", () => ({+ createInternalEventsWriter: () => ({ write: mocks.writeInternalTrace }),+}));++import { executeCodeBasedEvaluation } from "./executeCodeBasedEvaluation";++describe("executeCodeBasedEvaluation", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.writeInternalTrace.mockResolvedValue(undefined);+ });++ it("keeps score names returned by the dispatcher", async () => {+ mocks.dispatcher.dispatch.mockResolvedValue({+ scores: [+ {+ name: "primary-score",+ value: 1,+ dataType: "BOOLEAN",+ metadata: { user: "value" },+ },+ { name: "extra-score", value: "good", dataType: "CATEGORICAL" },+ ],+ });++ const result = await executeCodeBasedEvaluation({+ projectId: "project-1",+ organizationId: "org-1",+ job: {+ id: "job-1",+ jobConfigurationId: "config-1",+ jobInputTraceId: "trace-1",+ jobInputObservationId: "obs-1",+ jobInputDatasetItemId: null,+ } as any,+ config: {+ id: "config-1",+ scoreName: "default-score",+ } as any,+ template: {+ id: "template-1",+ name: "Code evaluator",+ type: EvalTemplateType.CODE,+ version: 1,+ sourceCode: "function evaluate() {}",+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ prompt: null,+ outputDefinition: null,+ } as any,+ extractedVariables: [+ { var: "input", value: { question: "2+2" } },+ { var: "output", value: "4" },+ { var: "experimentItemExpectedOutput", value: "4" },+ ],+ hasExperimentContext: true,+ executionMetadata: { job_execution_id: "job-1" },+ });++ expect(result.scores).toMatchObject([+ {+ name: "primary-score",+ value: 1,+ dataType: "BOOLEAN",+ metadata: { user: "value" },+ },+ { name: "extra-score", value: "good", dataType: "CATEGORICAL" },+ ]);+ expect(mocks.span.setAttribute).toHaveBeenCalledWith("eval.score.count", 2);+ const expectedPayload = expect.objectContaining({+ observation: {+ input: { question: "2+2" },+ output: "4",+ metadata: null,+ },+ experiment: {+ itemExpectedOutput: "4",+ itemMetadata: null,+ },+ });+ expect(mocks.dispatcher.dispatch).toHaveBeenCalledWith(+ expect.objectContaining({+ scope: expect.objectContaining({ organizationId: "org-1" }),+ payload: expectedPayload,+ }),+ );+ expect(mocks.writeInternalTrace).toHaveBeenCalledWith(+ expect.objectContaining({+ eventInputs: [+ expect.objectContaining({+ projectId: "project-1",+ traceName: "Execute evaluator: Code evaluator",+ name: "Execute evaluator: Code evaluator",+ type: "SPAN",+ environment: "langfuse-code-eval",+ metadata: expect.objectContaining({+ code_eval_runtime: EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ code_eval_source_code: "function evaluate() {}",+ }),+ }),+ ],+ }),+ );+ });++ it("keeps multiple dispatcher-provided score names", async () => {+ mocks.dispatcher.dispatch.mockResolvedValue({+ scores: [+ { name: "boolean-score", value: 1, dataType: "BOOLEAN" },+ { name: "categorical-score", value: "good", dataType: "CATEGORICAL" },+ ],+ });++ const result = await executeCodeBasedEvaluation({+ projectId: "project-1",+ organizationId: "org-1",+ job: {+ id: "job-1",+ jobConfigurationId: "config-1",+ jobInputTraceId: "trace-1",+ jobInputObservationId: "obs-1",+ jobInputDatasetItemId: null,+ } as any,+ config: {+ id: "config-1",+ scoreName: "default-score",+ } as any,+ template: {+ id: "template-1",+ type: EvalTemplateType.CODE,+ version: 1,+ sourceCode: "function evaluate() {}",+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ prompt: null,+ outputDefinition: null,+ } as any,+ extractedVariables: [],+ executionMetadata: { job_execution_id: "job-1" },+ });++ expect(result.scores).toMatchObject([+ { name: "boolean-score", value: 1, dataType: "BOOLEAN" },+ { name: "categorical-score", value: "good", dataType: "CATEGORICAL" },+ ]);+ expect(mocks.dispatcher.dispatch).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: {+ observation: { input: null, output: null, metadata: null },+ },+ }),+ );+ });++ it("passes an empty experiment payload when the source observation has experiment context", async () => {+ mocks.dispatcher.dispatch.mockResolvedValue({+ scores: [{ name: "score", value: 1, dataType: "BOOLEAN" }],+ });++ await executeCodeBasedEvaluation({+ projectId: "project-1",+ organizationId: "org-1",+ job: {+ id: "job-1",+ jobConfigurationId: "config-1",+ jobInputTraceId: "trace-1",+ jobInputObservationId: "obs-1",+ jobInputDatasetItemId: null,+ } as any,+ config: { id: "config-1", scoreName: "default-score" } as any,+ template: {+ id: "template-1",+ type: EvalTemplateType.CODE,+ version: 1,+ sourceCode: "function evaluate() {}",+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ prompt: null,+ outputDefinition: null,+ } as any,+ extractedVariables: [],+ hasExperimentContext: true,+ executionMetadata: { job_execution_id: "job-1" },+ });++ expect(mocks.dispatcher.dispatch).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: {+ observation: { input: null, output: null, metadata: null },+ experiment: {+ itemExpectedOutput: null,+ itemMetadata: null,+ },+ },+ }),+ );+ });++ it("does not infer experiment payload from mapped variables alone", async () => {+ mocks.dispatcher.dispatch.mockResolvedValue({+ scores: [{ name: "score", value: 1, dataType: "BOOLEAN" }],+ });++ await executeCodeBasedEvaluation({+ projectId: "project-1",+ organizationId: "org-1",+ job: {+ id: "job-1",+ jobConfigurationId: "config-1",+ jobInputTraceId: "trace-1",+ jobInputObservationId: "obs-1",+ jobInputDatasetItemId: null,+ } as any,+ config: { id: "config-1", scoreName: "default-score" } as any,+ template: {+ id: "template-1",+ type: EvalTemplateType.CODE,+ version: 1,+ sourceCode: "function evaluate() {}",+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ prompt: null,+ outputDefinition: null,+ } as any,+ extractedVariables: [{ var: "experimentItemExpectedOutput", value: "4" }],+ hasExperimentContext: false,+ executionMetadata: { job_execution_id: "job-1" },+ });++ expect(mocks.dispatcher.dispatch).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: {+ observation: { input: null, output: null, metadata: null },+ },+ }),+ );+ });++ it("passes extracted variable values through to the dispatcher payload as-is", async () => {+ mocks.dispatcher.dispatch.mockResolvedValue({+ scores: [{ name: "score", value: 1, dataType: "BOOLEAN" }],+ });++ await executeCodeBasedEvaluation({+ projectId: "project-1",+ organizationId: "org-1",+ job: {+ id: "job-1",+ jobConfigurationId: "config-1",+ jobInputTraceId: "trace-1",+ jobInputObservationId: "obs-1",+ jobInputDatasetItemId: null,+ } as any,+ config: { id: "config-1", scoreName: "default-score" } as any,+ template: {+ id: "template-1",+ type: EvalTemplateType.CODE,+ version: 1,+ sourceCode: "function evaluate() {}",+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ prompt: null,+ outputDefinition: null,+ } as any,+ extractedVariables: [+ { var: "output", value: "true" },+ { var: "metadata", value: "42" },+ { var: "experimentItemExpectedOutput", value: "null" },+ ],+ hasExperimentContext: true,+ executionMetadata: { job_execution_id: "job-1" },+ });++ expect(mocks.dispatcher.dispatch).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ observation: {+ input: null,+ output: "true",+ metadata: "42",+ },+ experiment: {+ itemExpectedOutput: "null",+ itemMetadata: null,+ },+ }),+ }),+ );+ });++ it("passes experiment item metadata through without expected output", async () => {+ mocks.dispatcher.dispatch.mockResolvedValue({+ scores: [{ name: "score", value: 1, dataType: "BOOLEAN" }],+ });++ await executeCodeBasedEvaluation({+ projectId: "project-1",+ organizationId: "org-1",+ job: {+ id: "job-1",+ jobConfigurationId: "config-1",+ jobInputTraceId: "trace-1",+ jobInputObservationId: "obs-1",+ jobInputDatasetItemId: null,+ } as any,+ config: { id: "config-1", scoreName: "default-score" } as any,+ template: {+ id: "template-1",+ type: EvalTemplateType.CODE,+ version: 1,+ sourceCode: "function evaluate() {}",+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ prompt: null,+ outputDefinition: null,+ } as any,+ extractedVariables: [+ {+ var: "experimentItemMetadata",+ value: { difficulty: "easy", source: "dataset" },+ },+ ],+ hasExperimentContext: true,+ executionMetadata: { job_execution_id: "job-1" },+ });++ expect(mocks.dispatcher.dispatch).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ observation: {+ input: null,+ output: null,+ metadata: null,+ },+ experiment: {+ itemExpectedOutput: null,+ itemMetadata: { difficulty: "easy", source: "dataset" },+ },+ }),+ }),+ );+ });++ it("continues successful execution when writing the internal trace fails", async () => {+ mocks.dispatcher.dispatch.mockResolvedValue({+ scores: [{ name: "score", value: 1, dataType: "NUMERIC" }],+ });+ mocks.writeInternalTrace.mockRejectedValue(new Error("trace write failed"));++ await expect(+ executeCodeBasedEvaluation({+ projectId: "project-1",+ organizationId: "org-1",+ job: {+ id: "job-1",+ jobConfigurationId: "config-1",+ jobInputTraceId: "trace-1",+ jobInputObservationId: "obs-1",+ jobInputDatasetItemId: null,+ } as any,+ config: { id: "config-1", scoreName: "default-score" } as any,+ template: {+ id: "template-1",+ name: "Code evaluator",+ type: EvalTemplateType.CODE,+ version: 1,+ sourceCode: "function evaluate() {}",+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ prompt: null,+ outputDefinition: null,+ } as any,+ extractedVariables: [{ var: "input", value: "prompt" }],+ executionMetadata: { job_execution_id: "job-1" },+ }),+ ).resolves.toMatchObject({+ scores: [{ name: "score", value: 1, dataType: "NUMERIC" }],+ metadata: expect.objectContaining({ dispatcher_name: "test-dispatcher" }),+ });+ });++ it("writes a user-visible error internal trace when code eval execution fails and rethrows", async () => {+ const error = new CodeEvalDispatcherError("runner exploded", {+ code: CodeEvalDispatcherErrorCodes.USER_CODE_ERROR,+ retryable: false,+ });+ mocks.dispatcher.dispatch.mockRejectedValue(error);++ const promise = executeCodeBasedEvaluation({+ projectId: "project-1",+ organizationId: "org-1",+ job: {+ id: "job-1",+ jobConfigurationId: "config-1",+ jobInputTraceId: "trace-1",+ jobInputObservationId: "obs-1",+ jobInputDatasetItemId: null,+ } as any,+ config: { id: "config-1", scoreName: "default-score" } as any,+ template: {+ id: "template-1",+ name: "Code evaluator",+ type: EvalTemplateType.CODE,+ version: 1,+ sourceCode: "function evaluate() {}",+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ prompt: null,+ outputDefinition: null,+ } as any,+ extractedVariables: [{ var: "input", value: "prompt" }],+ executionMetadata: { job_execution_id: "job-1" },+ });++ await expect(promise).rejects.toThrow(UnrecoverableError);+ await expect(promise).rejects.toThrow("runner exploded");++ expect(mocks.writeInternalTrace).toHaveBeenCalledTimes(1);+ expect(mocks.writeInternalTrace).toHaveBeenCalledWith(+ expect.objectContaining({+ eventInputs: [+ expect.objectContaining({+ projectId: "project-1",+ traceName: "Execute evaluator: Code evaluator",+ name: "Execute evaluator: Code evaluator",+ type: "SPAN",+ environment: "langfuse-code-eval",+ level: "ERROR",+ statusMessage: "Code eval execution failed: runner exploded",+ input: JSON.stringify({+ observation: { input: "prompt", output: null, metadata: null },+ }),+ output: expect.stringContaining("runner exploded"),+ metadata: expect.objectContaining({+ dispatcher_name: "test-dispatcher",+ code_eval_runtime: EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ code_eval_source_code: "function evaluate() {}",+ job_execution_id: "job-1",+ error_name: "CodeEvalDispatcherError",+ error_message: "runner exploded",+ error_code: "USER_CODE_ERROR",+ error_retryable: false,+ }),+ }),+ ],+ }),+ );+ });++ it("writes an actionable user-visible timeout error", async () => {+ const rawTimeoutMessage =+ "Function.TimedOut: Task timed out after 2 seconds";+ const error = new CodeEvalDispatcherError(rawTimeoutMessage, {+ code: CodeEvalDispatcherErrorCodes.TIMEOUT,+ retryable: true,+ });+ mocks.dispatcher.dispatch.mockRejectedValue(error);++ const promise = executeCodeBasedEvaluation({+ projectId: "project-1",+ organizationId: "org-1",+ job: {+ id: "job-1",+ jobConfigurationId: "config-1",+ jobInputTraceId: "trace-1",+ jobInputObservationId: "obs-1",+ jobInputDatasetItemId: null,+ } as any,+ config: { id: "config-1", scoreName: "default-score" } as any,+ template: {+ id: "template-1",+ name: "Code evaluator",+ type: EvalTemplateType.CODE,+ version: 1,+ sourceCode: "function evaluate() {}",+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ prompt: null,+ outputDefinition: null,+ } as any,+ extractedVariables: [{ var: "input", value: "prompt" }],+ executionMetadata: { job_execution_id: "job-1" },+ });++ await expect(promise).rejects.toThrow(CodeEvalExecutionError);+ await expect(promise).rejects.toMatchObject({+ code: CodeEvalDispatcherErrorCodes.TIMEOUT,+ retryable: true,+ });+ await expect(promise).rejects.toThrow("Evaluator timed out.");++ expect(mocks.writeInternalTrace).toHaveBeenCalledTimes(1);+ const trace = JSON.stringify(mocks.writeInternalTrace.mock.calls[0]?.[0]);+ expect(trace).toContain("Evaluator timed out.");+ expect(trace).toContain(+ "Long executions can be caused by network calls, which are forbidden and may never complete.",+ );+ expect(trace).not.toContain(rawTimeoutMessage);+ });++ it("masks internal dispatcher errors in the internal trace", async () => {+ const error = new CodeEvalDispatcherError(+ "Failed to invoke code eval Lambda code-based-eval-executor-node: ResourceNotFoundException: Function not found",+ {+ code: CodeEvalDispatcherErrorCodes.LAMBDA_CONFIGURATION_ERROR,+ retryable: false,+ },+ );+ mocks.dispatcher.dispatch.mockRejectedValue(error);++ const promise = executeCodeBasedEvaluation({+ projectId: "project-1",+ organizationId: "org-1",+ job: {+ id: "job-1",+ jobConfigurationId: "config-1",+ jobInputTraceId: "trace-1",+ jobInputObservationId: "obs-1",+ jobInputDatasetItemId: null,+ } as any,+ config: { id: "config-1", scoreName: "default-score" } as any,+ template: {+ id: "template-1",+ name: "Code evaluator",+ type: EvalTemplateType.CODE,+ version: 1,+ sourceCode: "function evaluate() {}",+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ prompt: null,+ outputDefinition: null,+ } as any,+ extractedVariables: [{ var: "input", value: "prompt" }],+ executionMetadata: { job_execution_id: "job-1" },+ });++ await expect(promise).rejects.toThrow(UnrecoverableError);+ await expect(promise).rejects.toThrow("An internal error occurred");++ expect(mocks.writeInternalTrace).toHaveBeenCalledTimes(1);+ expect(mocks.writeInternalTrace).toHaveBeenCalledWith(+ expect.objectContaining({+ eventInputs: [+ expect.objectContaining({+ level: "ERROR",+ statusMessage:+ "Code eval execution failed: An internal error occurred",+ output: expect.stringContaining("An internal error occurred"),+ metadata: expect.objectContaining({+ error_name: "CodeEvalDispatcherError",+ error_message: "An internal error occurred",+ error_code:+ CodeEvalDispatcherErrorCodes.LAMBDA_CONFIGURATION_ERROR,+ error_public_code: "INTERNAL_ERROR",+ error_retryable: false,+ }),+ }),+ ],+ }),+ );+ });+});diff --git a/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.ts b/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.tsnew file mode 100644index 0000000000..47606169a6--- /dev/null+++ b/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.ts@@ -0,0 +1,91 @@+import { type JobConfiguration, type JobExecution } from "@prisma/client";+import { type EvalTemplateCodeBased } from "@langfuse/shared";+import {+ CodeEvalExecutionError,+ instrumentAsync,+ logger,+ resolveConfiguredCodeEvalDispatcher,+ runCodeBasedEvaluationDispatch,+ type ExtractedVariable,+} from "@langfuse/shared/src/server";+import { UnrecoverableError } from "../../../errors/UnrecoverableError";+import { createW3CTraceId } from "../../utils";+import { createInternalEventsWriter } from "../../internal-tracing/createInternalEventsWriter";+import { type EvalExecutionResult } from "../evalCompletion";+import { type EvalExecutionDeps } from "../evalExecutionDeps";++export async function executeCodeBasedEvaluation(params: {+ projectId: string;+ organizationId: string;+ job: JobExecution;+ config: JobConfiguration;+ template: EvalTemplateCodeBased;+ extractedVariables: ExtractedVariable[];+ hasExperimentContext?: boolean;+ executionMetadata: Record<string, string>;+ // Unused by code-based eval; the shared observation processor passes it.+ deps?: EvalExecutionDeps;+}): Promise<EvalExecutionResult> {+ return instrumentAsync(+ { name: "eval.execute-code-based-eval" },+ async (span) => {+ const dispatcher = resolveConfiguredCodeEvalDispatcher();+ const jobExecutionId = params.job.id;++ if (!dispatcher) {+ throw new UnrecoverableError("Code eval dispatcher is not configured");+ }++ const executionTraceId = createW3CTraceId(jobExecutionId);+ const executionMetadata = {+ ...params.executionMetadata,+ dispatcher_name: dispatcher.name,+ code_eval_runtime: params.template.sourceCodeLanguage,+ };+ span.setAttribute("langfuse.project.id", params.projectId);+ span.setAttribute("eval.job_execution.id", jobExecutionId);+ span.setAttribute("eval.job_configuration.id", params.config.id);+ span.setAttribute("eval.template.id", params.template.id);+ span.setAttribute("eval.template.version", params.template.version);+ span.setAttribute("eval.dispatcher.name", dispatcher.name);+ span.setAttribute(+ "eval.runner.language",+ params.template.sourceCodeLanguage,+ );++ logger.debug(+ `Executing code-based evaluation for job ${jobExecutionId} in project ${params.projectId}`,+ );++ const dispatchOutcome = await runCodeBasedEvaluationDispatch({+ dispatcher,+ organizationId: params.organizationId,+ projectId: params.projectId,+ executionTraceId,+ jobExecutionId,+ template: params.template,+ extractedVariables: params.extractedVariables,+ hasExperimentContext: params.hasExperimentContext ?? false,+ traceName: `Execute evaluator: ${params.template.name}`,+ metadata: executionMetadata,+ writeTrace: (trace) => createInternalEventsWriter().write(trace),+ });++ if (!dispatchOutcome.success) {+ if (dispatchOutcome.error.retryable === false) {+ throw new UnrecoverableError(dispatchOutcome.error.message);+ }++ throw new CodeEvalExecutionError(dispatchOutcome.error);+ }++ span.setAttribute("eval.score.count", dispatchOutcome.scores.length);++ return {+ scores: dispatchOutcome.scores,+ executionTraceId,+ metadata: executionMetadata,+ };+ },+ );+}diff --git a/worker/src/features/evaluation/codeBased/index.ts b/worker/src/features/evaluation/codeBased/index.tsnew file mode 100644index 0000000000..7d97825c97--- /dev/null+++ b/worker/src/features/evaluation/codeBased/index.ts@@ -0,0 +1 @@+export { executeCodeBasedEvaluation } from "./executeCodeBasedEvaluation";diff --git a/worker/src/features/evaluation/codeBased/localCodeEvalDispatcher.test.ts b/worker/src/features/evaluation/codeBased/localCodeEvalDispatcher.test.tsnew file mode 100644index 0000000000..c85dfb9536--- /dev/null+++ b/worker/src/features/evaluation/codeBased/localCodeEvalDispatcher.test.ts@@ -0,0 +1,254 @@+import { describe, expect, it } from "vitest";+import {+ CodeEvalDispatcherError,+ LocalCodeEvalDispatcher,+ type DispatchInput,+} from "@langfuse/shared/src/server";+import { TEXT_SCORE_MAX_LENGTH } from "../../../../../packages/shared/src/domain/scores";++const baseInput: Omit<DispatchInput, "runtime" | "code"> = {+ scope: {+ organizationId: "org-1",+ projectId: "project-1",+ evaluatorId: "evaluator-1",+ },+ execution: {+ jobExecutionId: "job-1",+ },+ payload: {+ observation: {+ input: { question: "2+2" },+ output: "4",+ metadata: { source: "test" },+ },+ experiment: {+ itemExpectedOutput: "4",+ itemMetadata: { difficulty: "easy" },+ },+ },+};++describe("LocalCodeEvalDispatcher", () => {+ it("executes TS-lite evaluate(ctx) functions in process", async () => {+ const dispatcher = new LocalCodeEvalDispatcher();++ const result = await dispatcher.dispatch({+ ...baseInput,+ runtime: { language: "TYPESCRIPT" },+ code: {+ source: `+ type EvaluationContext = {+ observation: { output: string };+ experiment: { itemExpectedOutput: string } | undefined;+ };+ function evaluate(ctx: EvaluationContext) {+ return {+ scores: [{ name: "match", value: ctx.observation.output === ctx.experiment?.itemExpectedOutput ? 1 : 0, dataType: "BOOLEAN" }],+ };+ }+ `,+ },+ });++ expect(result).toEqual({+ scores: [{ name: "match", value: 1, dataType: "BOOLEAN" }],+ });+ });++ it("rejects unsupported TypeScript syntax with a docs link", async () => {+ const dispatcher = new LocalCodeEvalDispatcher();++ const promise = dispatcher.dispatch({+ ...baseInput,+ runtime: { language: "TYPESCRIPT" },+ code: {+ source: `+ enum MatchScore {+ Mismatch = 0,+ Match = 1,+ }++ function evaluate() {+ return { scores: [{ name: "match", value: MatchScore.Match }] };+ }+ `,+ },+ });++ await expect(promise).rejects.toMatchObject({+ code: "INVALID_SOURCE",+ retryable: false,+ } satisfies Partial<CodeEvalDispatcherError>);+ await expect(promise).rejects.toThrow(+ "See https://langfuse.com/docs/evaluation/overview for details.",+ );+ });++ it("rejects sources whose module throws at top level", async () => {+ const dispatcher = new LocalCodeEvalDispatcher();++ await expect(+ dispatcher.dispatch({+ ...baseInput,+ runtime: { language: "TYPESCRIPT" },+ code: { source: `throw new Error("top-level boom");` },+ }),+ ).rejects.toMatchObject({+ code: "INVALID_SOURCE",+ retryable: false,+ } satisfies Partial<CodeEvalDispatcherError>);+ });++ it("rejects sources missing an evaluate function", async () => {+ const dispatcher = new LocalCodeEvalDispatcher();++ await expect(+ dispatcher.dispatch({+ ...baseInput,+ runtime: { language: "TYPESCRIPT" },+ code: { source: `const evaluate = 42;` },+ }),+ ).rejects.toMatchObject({+ code: "INVALID_SOURCE",+ retryable: false,+ } satisfies Partial<CodeEvalDispatcherError>);+ });++ it("surfaces evaluator runtime throws as USER_CODE_ERROR", async () => {+ const dispatcher = new LocalCodeEvalDispatcher();++ await expect(+ dispatcher.dispatch({+ ...baseInput,+ runtime: { language: "TYPESCRIPT" },+ code: {+ source: `function evaluate() { throw new Error("boom"); }`,+ },+ }),+ ).rejects.toMatchObject({+ code: "USER_CODE_ERROR",+ retryable: false,+ message: expect.stringContaining("boom"),+ } satisfies Partial<CodeEvalDispatcherError>);+ });++ it("times out runaway evaluators", async () => {+ const dispatcher = new LocalCodeEvalDispatcher({ timeoutMs: 50 });++ await expect(+ dispatcher.dispatch({+ ...baseInput,+ runtime: { language: "TYPESCRIPT" },+ code: {+ source: `function evaluate() { while (true) {} }`,+ },+ }),+ ).rejects.toMatchObject({+ code: "TIMEOUT",+ retryable: true,+ } satisfies Partial<CodeEvalDispatcherError>);+ });++ it("times out async evaluators that never settle", async () => {+ const dispatcher = new LocalCodeEvalDispatcher({ timeoutMs: 10 });++ const result = await Promise.race([+ dispatcher+ .dispatch({+ ...baseInput,+ runtime: { language: "TYPESCRIPT" },+ code: {+ source: `+ async function evaluate() {+ await new Promise(() => {});+ return { scores: [{ name: "match", value: 1, dataType: "BOOLEAN" }] };+ }+ `,+ },+ })+ .catch((error: unknown) => error),+ new Promise((resolve) => setTimeout(() => resolve("test-timeout"), 100)),+ ]);++ expect(result).toBeInstanceOf(CodeEvalDispatcherError);+ expect(result).toMatchObject({+ code: "TIMEOUT",+ retryable: true,+ } satisfies Partial<CodeEvalDispatcherError>);+ });++ it("rejects Python evaluators", async () => {+ const dispatcher = new LocalCodeEvalDispatcher();++ await expect(+ dispatcher.dispatch({+ ...baseInput,+ runtime: { language: "PYTHON" },+ code: { source: "def evaluate(ctx): pass" },+ }),+ ).rejects.toThrow(CodeEvalDispatcherError);+ });++ it("accepts TEXT scores within the public ingestion length cap", async () => {+ const dispatcher = new LocalCodeEvalDispatcher();++ const source = `+ function evaluate() {+ return {+ scores: [{+ value: "reasoning fits within the limit",+ dataType: "TEXT",+ name: "judge-rationale",+ }],+ };+ }+ `;++ await expect(+ dispatcher.dispatch({+ ...baseInput,+ runtime: { language: "TYPESCRIPT" },+ code: { source },+ }),+ ).resolves.toEqual({+ scores: [+ {+ value: "reasoning fits within the limit",+ dataType: "TEXT",+ name: "judge-rationale",+ },+ ],+ });+ });++ it("rejects TEXT scores that exceed the public ingestion length cap", async () => {+ const dispatcher = new LocalCodeEvalDispatcher();++ // Produce a TEXT value just over the public 500-char ingestion cap. The+ // dispatcher must surface this as a non-retryable INVALID_RESULT so the+ // job execution fails clearly instead of completing and then having the+ // score silently dropped by the ingestion consumer.+ const source = `+ function evaluate() {+ return {+ scores: [{+ value: "a".repeat(${TEXT_SCORE_MAX_LENGTH + 1}),+ dataType: "TEXT",+ name: "judge-rationale",+ }],+ };+ }+ `;++ await expect(+ dispatcher.dispatch({+ ...baseInput,+ runtime: { language: "TYPESCRIPT" },+ code: { source },+ }),+ ).rejects.toMatchObject({+ code: "INVALID_RESULT",+ retryable: false,+ } satisfies Partial<CodeEvalDispatcherError>);+ });+});diff --git a/worker/src/features/evaluation/evalCompletion.ts b/worker/src/features/evaluation/evalCompletion.tsnew file mode 100644index 0000000000..3a73274944--- /dev/null+++ b/worker/src/features/evaluation/evalCompletion.ts@@ -0,0 +1,95 @@+import { JobExecutionStatus } from "@prisma/client";+import {+ logger,+ traceException,+ type CodeEvalScoreWithName,+} from "@langfuse/shared/src/server";+import { buildEvalScoreWritePayloads } from "./evalScoreEvent";+import { type EvalExecutionDeps } from "./evalExecutionDeps";++/**+ * Common result returned by every evaluator executor (LLM-as-judge,+ * code-based, future executors). The first persisted score payload is treated+ * as primary and is persisted on `JobExecution.jobOutputScoreId`.+ */+export type EvalExecutionResult = {+ scores: CodeEvalScoreWithName[];+ executionTraceId: string;+ metadata: Record<string, string>;+};++export async function completeEvalExecution({+ projectId,+ jobExecutionId,+ result,+ traceId,+ observationId,+ environment,+ deps,+}: {+ projectId: string;+ jobExecutionId: string;+ result: EvalExecutionResult;+ traceId: string | null;+ observationId: string | null;+ environment: string;+ deps: EvalExecutionDeps;+}): Promise<{ scoreCount: number }> {+ const scoreWritePayloads = buildEvalScoreWritePayloads({+ scores: result.scores,+ jobExecutionId,+ traceId,+ observationId,+ environment,+ executionTraceId: result.executionTraceId,+ executionMetadata: result.metadata,+ });+ const [firstScorePayload] = scoreWritePayloads;++ if (!firstScorePayload) {+ throw new Error(`Evaluation job ${jobExecutionId} returned no scores`);+ }+ const jobOutputScoreId = firstScorePayload.scoreId;++ try {+ await Promise.all(+ scoreWritePayloads.map(async ({ scoreId, eventId, event }) => {+ await deps.uploadScore({+ projectId,+ scoreId,+ eventId,+ event,+ });++ await deps.enqueueScoreIngestion({+ projectId,+ scoreId,+ eventId,+ });+ }),+ );+ } catch (e) {+ logger.error(`Failed to persist score: ${e}`, e);+ traceException(e);+ throw new Error(+ `Failed to write score ${jobOutputScoreId} into IngestionQueue`,+ );+ }++ logger.debug(+ `Persisted ${scoreWritePayloads.length} score(s) for job ${jobExecutionId}`,+ );++ await deps.updateJobExecution({+ id: jobExecutionId,+ projectId,+ data: {+ status: JobExecutionStatus.COMPLETED,+ endTime: new Date(),+ jobOutputScoreId,+ executionTraceId: result.executionTraceId,+ },+ });++ return { scoreCount: scoreWritePayloads.length };+}diff --git a/worker/src/features/evaluation/evalRuntime.ts b/worker/src/features/evaluation/evalRuntime.tsindex 24f61f902e..03bb984a9d 100644--- a/worker/src/features/evaluation/evalRuntime.ts+++ b/worker/src/features/evaluation/evalRuntime.ts@@ -1,6 +1,10 @@-import { ChatMessageRole, ChatMessageType } from "@langfuse/shared";+import {+ ChatMessageRole,+ ChatMessageType,+ parseUnknownToString,+} from "@langfuse/shared";+import { type ExtractedVariable } from "@langfuse/shared/src/server";import { compileTemplateString } from "../utils";-import { ExtractedVariable } from "./observationEval/extractObservationVariables";export interface CompileEvalPromptParams {templatePrompt: string;@@ -8,8 +12,14 @@ export interface CompileEvalPromptParams {}export function compileEvalPrompt(params: CompileEvalPromptParams): string {+ // Stringify extracted values here (LLM-judge's consumption boundary) so+ // the upstream extractor can preserve original shapes for code-eval and+ // template substitution still gets a flat string per variable.const variableMap = Object.fromEntries(- params.variables.map(({ var: key, value }) => [key, value]),+ params.variables.map(({ var: key, value }) => [+ key,+ parseUnknownToString(value),+ ]),);return compileTemplateString(params.templatePrompt, variableMap);diff --git a/worker/src/features/evaluation/evalScoreEvent.ts b/worker/src/features/evaluation/evalScoreEvent.tsindex bfa2d7fa72..de072f4799 100644--- a/worker/src/features/evaluation/evalScoreEvent.ts+++ b/worker/src/features/evaluation/evalScoreEvent.ts@@ -1,73 +1,11 @@import { randomUUID } from "crypto";+import { ScoreSourceEnum } from "@langfuse/shared";import {- type EvalOutputResult,- ScoreDataTypeEnum,- ScoreSourceEnum,-} from "@langfuse/shared";-import { eventTypes, ScoreEventType } from "@langfuse/shared/src/server";--type BuildScoreEventBase = {- eventId: string;- scoreId: string;- traceId: string | null;- observationId: string | null;- scoreName: string;- reasoning: string;- environment: string;- executionTraceId: string;- metadata: Record<string, string>;-};--export type BuildScoreEventParams = BuildScoreEventBase &- (- | {- dataType: typeof ScoreDataTypeEnum.NUMERIC;- scoreValue: number;- }- | {- dataType: typeof ScoreDataTypeEnum.BOOLEAN;- scoreValue: 0 | 1;- }- | {- dataType: typeof ScoreDataTypeEnum.CATEGORICAL;- scoreValue: string;- }- );--type BuildScoreWritePayloadParams =- | Omit<- Extract<- BuildScoreEventParams,- { dataType: typeof ScoreDataTypeEnum.NUMERIC }- >,- "eventId"- >- | Omit<- Extract<- BuildScoreEventParams,- { dataType: typeof ScoreDataTypeEnum.BOOLEAN }- >,- "eventId"- >- | Omit<- Extract<- BuildScoreEventParams,- { dataType: typeof ScoreDataTypeEnum.CATEGORICAL }- >,- "eventId"- >;--function createScoreEventEnvelope(params: {- eventId: string;- body: ScoreEventType["body"];-}): ScoreEventType {- return {- id: params.eventId,- timestamp: new Date().toISOString(),- type: eventTypes.SCORE_CREATE,- body: params.body,- };-}+ buildDeterministicEvalScoreIds,+ eventTypes,+ ScoreEventType,+ type CodeEvalScoreWithName,+} from "@langfuse/shared/src/server";export type EvalScoreWritePayload = {eventId: string;@@ -75,142 +13,49 @@ export type EvalScoreWritePayload = {event: ScoreEventType;};-export function buildScoreEvent(params: BuildScoreEventParams): ScoreEventType {- const bodyBase = {- id: params.scoreId,- traceId: params.traceId,- observationId: params.observationId,- name: params.scoreName,- comment: params.reasoning,- source: ScoreSourceEnum.EVAL,- environment: params.environment,- executionTraceId: params.executionTraceId,- metadata: params.metadata,- };-- if (params.dataType === ScoreDataTypeEnum.CATEGORICAL) {- return createScoreEventEnvelope({- eventId: params.eventId,- body: {- ...bodyBase,- value: params.scoreValue,- dataType: ScoreDataTypeEnum.CATEGORICAL,- },- });- }-- if (params.dataType === ScoreDataTypeEnum.BOOLEAN) {- return createScoreEventEnvelope({- eventId: params.eventId,- body: {- ...bodyBase,- value: params.scoreValue,- dataType: ScoreDataTypeEnum.BOOLEAN,- },- });- }-- return createScoreEventEnvelope({- eventId: params.eventId,- body: {- ...bodyBase,- value: params.scoreValue,- dataType: ScoreDataTypeEnum.NUMERIC,- },- });-}--function buildScoreWritePayload(- params: BuildScoreWritePayloadParams,-): EvalScoreWritePayload {- const eventId = randomUUID();-- if (params.dataType === ScoreDataTypeEnum.CATEGORICAL) {- return {- eventId,- scoreId: params.scoreId,- event: buildScoreEvent({- ...params,- eventId,- dataType: ScoreDataTypeEnum.CATEGORICAL,- scoreValue: params.scoreValue,- }),- };- }-- if (params.dataType === ScoreDataTypeEnum.BOOLEAN) {- return {- eventId,- scoreId: params.scoreId,- event: buildScoreEvent({- ...params,- eventId,- dataType: ScoreDataTypeEnum.BOOLEAN,- scoreValue: params.scoreValue,- }),- };- }-- return {- eventId,- scoreId: params.scoreId,- event: buildScoreEvent({- ...params,- eventId,- dataType: ScoreDataTypeEnum.NUMERIC,- scoreValue: params.scoreValue,- }),- };-}-export function buildEvalScoreWritePayloads(params: {- outputResult: EvalOutputResult;- primaryScoreId: string;+ scores: CodeEvalScoreWithName[];+ jobExecutionId: string;traceId: string | null;observationId: string | null;- scoreName: string;environment: string;executionTraceId: string;- metadata: Record<string, string>;+ executionMetadata: Record<string, string>;}): EvalScoreWritePayload[] {- const commonParams = {- traceId: params.traceId,- observationId: params.observationId,- scoreName: params.scoreName,- reasoning: params.outputResult.reasoning,- environment: params.environment,- executionTraceId: params.executionTraceId,- metadata: params.metadata,- };-- if (params.outputResult.dataType === ScoreDataTypeEnum.NUMERIC) {- return [- buildScoreWritePayload({- ...commonParams,- scoreId: params.primaryScoreId,- scoreValue: params.outputResult.score,- dataType: ScoreDataTypeEnum.NUMERIC,- }),- ];- }+ const scoreIds = buildDeterministicEvalScoreIds({+ scores: params.scores,+ jobExecutionId: params.jobExecutionId,+ });- if (params.outputResult.dataType === ScoreDataTypeEnum.BOOLEAN) {- return [- buildScoreWritePayload({- ...commonParams,- scoreId: params.primaryScoreId,- scoreValue: params.outputResult.score ? 1 : 0,- dataType: ScoreDataTypeEnum.BOOLEAN,- }),- ];- }+ return params.scores.map((score, index) => {+ const eventId = randomUUID();+ const scoreId = scoreIds[index]!;- return params.outputResult.matches.map((scoreValue, index) =>- buildScoreWritePayload({- ...commonParams,- scoreId: index === 0 ? params.primaryScoreId : randomUUID(),- scoreValue,- dataType: ScoreDataTypeEnum.CATEGORICAL,- }),- );+ return {+ eventId,+ scoreId,+ event: {+ id: eventId,+ timestamp: new Date().toISOString(),+ type: eventTypes.SCORE_CREATE,+ body: {+ id: scoreId,+ traceId: params.traceId,+ observationId: params.observationId,+ name: score.name,+ comment: score.comment,+ metadata: {+ ...(score.metadata ?? {}),+ ...params.executionMetadata,+ },+ configId: score.configId,+ source: ScoreSourceEnum.EVAL,+ environment: params.environment,+ executionTraceId: params.executionTraceId,+ value: score.value,+ dataType: score.dataType,+ } as ScoreEventType["body"],+ },+ };+ });}diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.tsindex ab5ead5a4b..9b1a77cf07 100644--- a/worker/src/features/evaluation/evalService.ts+++ b/worker/src/features/evaluation/evalService.ts@@ -1,17 +1,16 @@import { randomUUID } from "crypto";import { z } from "zod";import {+ EvalTemplateType,JobConfigState,JobExecutionStatus,type JobExecution,type JobConfiguration,- type EvalTemplate,} from "@prisma/client";import {QueueJobs,QueueName,EvalExecutionEvent,- traceException,logger,EvalExecutionQueue,checkTraceExistsAndGetTimestamp,@@ -34,6 +33,7 @@ import {isLLMCompletionError,blockEvaluatorConfigs,EvaluatorBlockSource,+ type CodeEvalScoreWithName,} from "@langfuse/shared/src/server";import {mapTraceFilterColumn,@@ -56,9 +56,11 @@ import {getEvaluatorBlockMetadata,getBlockReasonForInvalidModelConfig,isJobConfigExecutable,+ type EvalTemplateLlmAsAJudge,PersistedEvalOutputDefinitionSchema,ScoreDataTypeEnum,validateEvalOutputResult,+ type EvalOutputResult,extractValueFromObject,validateEvaluatorFiltersForTarget,} from "@langfuse/shared";@@ -73,12 +75,15 @@ import {buildEvalExecutionMetadata,getEnvironmentFromVariables,} from "./evalRuntime";-import { buildEvalScoreWritePayloads } from "./evalScoreEvent";+import {+ completeEvalExecution,+ type EvalExecutionResult,+} from "./evalCompletion";import {type EvalExecutionDeps,createProductionEvalExecutionDeps,} from "./evalExecutionDeps";-import { ExtractedVariable } from "./observationEval/extractObservationVariables";+import { type ExtractedVariable } from "@langfuse/shared/src/server";/*** Determines which eval jobs to create for a given event (traces or dataset run items).@@ -710,8 +715,7 @@ export const createEvalJobs = async ({* It handles:* - Compiling the prompt with extracted variables* - Calling the LLM with structured output- * - Persisting the score to S3 and queueing for ingestion- * - Updating job execution status+ * - Returning the validated eval output and completion metadata** Note: Callers are responsible for:* - Fetching and validating job, config, and template@@ -724,27 +728,28 @@ export const createEvalJobs = async ({* @param params.config - Pre-fetched job configuration* @param params.template - Pre-fetched eval template* @param params.extractedVariables - Pre-extracted variables from trace/observation data+ * @param params.executionMetadata - Metadata identifying this eval execution* @param params.deps - Optional dependency injection for testing (defaults to production deps)*/-export async function executeLLMAsJudgeEvaluation({+export async function runLLMAsJudgeEvaluation({projectId,jobExecutionId,job,config,template,extractedVariables,- environment,- deps = createProductionEvalExecutionDeps(),+ executionMetadata,+ deps,}: {projectId: string;jobExecutionId: string;job: JobExecution;config: JobConfiguration;- template: EvalTemplate;+ template: EvalTemplateLlmAsAJudge;extractedVariables: ExtractedVariable[];- environment: string;- deps?: EvalExecutionDeps;-}): Promise<void> {+ executionMetadata: Record<string, string>;+ deps: EvalExecutionDeps;+}): Promise<EvalExecutionResult> {return instrumentAsync({ name: "eval.execute-llm-as-judge" },async (span) => {@@ -851,18 +856,8 @@ export async function executeLLMAsJudgeEvaluation({// Prepare LLM callconst messages = buildEvalMessages(prompt);- const primaryScoreId = randomUUID();- span.setAttribute("eval.score.id", primaryScoreId);const executionTraceId = createW3CTraceId(jobExecutionId);- const executionMetadata = buildEvalExecutionMetadata({- jobExecutionId,- jobConfigurationId: job.jobConfigurationId,- targetTraceId: job.jobInputTraceId,- targetObservationId: job.jobInputObservationId,- targetDatasetItemId: job.jobInputDatasetItemId,- });-// Call LLMconst llmOutput = await instrumentAsync({ name: "eval.call-llm" },@@ -898,7 +893,6 @@ export async function executeLLMAsJudgeEvaluation({environment: LangfuseInternalTraceEnvironment.LLMJudge,metadata: {...executionMetadata,- score_id: primaryScoreId,},},});@@ -949,72 +943,91 @@ export async function executeLLMAsJudgeEvaluation({}`,);- const scoreWritePayloads = buildEvalScoreWritePayloads({+ const scores = toNormalizedScores({outputResult: parsedLLMOutput.data,- primaryScoreId,- traceId: job.jobInputTraceId,- observationId: job.jobInputObservationId,scoreName: config.scoreName,- environment,+ });++ span.setAttribute("eval.score.count", scores.length);++ return {+ scores,executionTraceId,metadata: executionMetadata,- });+ };+ },+ );+}- span.setAttribute("eval.score.count", scoreWritePayloads.length);+function toNormalizedScores(params: {+ outputResult: EvalOutputResult;+ scoreName: string;+}): CodeEvalScoreWithName[] {+ const { outputResult, scoreName } = params;+ const baseFields = {+ name: scoreName,+ comment: outputResult.reasoning,+ };- // Write score to S3 and enqueue for ingestion- try {- await Promise.all(- scoreWritePayloads.map(async ({ scoreId, eventId, event }) => {- await deps.uploadScore({- projectId,- scoreId,- eventId,- event,- });+ if (outputResult.dataType === ScoreDataTypeEnum.NUMERIC) {+ return [+ {+ ...baseFields,+ dataType: ScoreDataTypeEnum.NUMERIC,+ value: outputResult.score,+ },+ ];+ }- await deps.enqueueScoreIngestion({- projectId,- scoreId,- eventId,- });- }),- );- } catch (e) {- logger.error(`Failed to persist score: ${e}`, e);- traceException(e);- throw new Error(- `Failed to write score ${primaryScoreId} into IngestionQueue`,- );- }+ if (outputResult.dataType === ScoreDataTypeEnum.BOOLEAN) {+ return [+ {+ ...baseFields,+ dataType: ScoreDataTypeEnum.BOOLEAN,+ value: outputResult.score ? 1 : 0,+ },+ ];+ }- logger.debug(- `Persisted ${scoreWritePayloads.length} score(s) for job ${jobExecutionId}`,- );+ return outputResult.matches.map((value) => ({+ ...baseFields,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ value,+ }));+}- // Update job execution status- await deps.updateJobExecution({- id: jobExecutionId,- projectId,- data: {- status: JobExecutionStatus.COMPLETED,- endTime: new Date(),- jobOutputScoreId: primaryScoreId,- executionTraceId,- },- });+export async function executeLLMAsJudgeEvaluation(+ params: Omit<+ Parameters<typeof runLLMAsJudgeEvaluation>[0],+ "deps" | "executionMetadata"+ > & {+ environment: string;+ deps?: EvalExecutionDeps;+ },+): Promise<void> {+ const deps = params.deps ?? createProductionEvalExecutionDeps();+ const executionMetadata = buildEvalExecutionMetadata({+ jobExecutionId: params.jobExecutionId,+ jobConfigurationId: params.job.jobConfigurationId,+ targetTraceId: params.job.jobInputTraceId,+ targetObservationId: params.job.jobInputObservationId,+ targetDatasetItemId: params.job.jobInputDatasetItemId,+ });+ const result = await runLLMAsJudgeEvaluation({+ ...params,+ deps,+ executionMetadata,+ });- logger.debug(- `Eval job ${job.id} completed with ${- parsedLLMOutput.data.dataType === ScoreDataTypeEnum.NUMERIC- ? `score ${parsedLLMOutput.data.score}`- : parsedLLMOutput.data.dataType === ScoreDataTypeEnum.BOOLEAN- ? `score ${parsedLLMOutput.data.score}`- : `matches ${parsedLLMOutput.data.matches.join(",")}`- }`,- );- },- );+ await completeEvalExecution({+ projectId: params.projectId,+ jobExecutionId: params.jobExecutionId,+ traceId: params.job.jobInputTraceId,+ observationId: params.job.jobInputObservationId,+ environment: params.environment,+ deps,+ result,+ });}/**@@ -1091,6 +1104,7 @@ export const evaluate = async ({const template = await prisma.evalTemplate.findFirst({where: {id: config.evalTemplateId,+ type: EvalTemplateType.LLM_AS_JUDGE,OR: [{ projectId: event.projectId }, { projectId: null }],},});@@ -1126,7 +1140,7 @@ export const evaluate = async ({jobExecutionId: event.jobExecutionId,job,config,- template,+ template: template as EvalTemplateLlmAsAJudge,extractedVariables,environment:getEnvironmentFromVariables(extractedVariables) ??@@ -1151,13 +1165,13 @@ export async function extractVariablesFromTracingData({traceTimestamp?: Date;datasetItemId?: string;datasetItemValidFrom?: Date;-}): Promise<{ var: string; value: string; environment?: string }[]> {+}): Promise<ExtractedVariable[]> {// Internal cache for this function call to avoid duplicate database lookups.// We do not cache dataset items as Postgres is cheaper than ClickHouse.const traceCache = new Map<string, TraceDomain | null>();const observationCache = new Map<string, Observation | null>();- const results: { var: string; value: string; environment?: string }[] = [];+ const results: ExtractedVariable[] = [];// We run through this list sequentially to make use of caching.// The performance improvement by parallel execution should be less than the improvement we gain by caching.@@ -1221,7 +1235,7 @@ export async function extractVariablesFromTracingData({results.push({var: variable,- value: parseDatabaseRowToString(datasetItem, mapping),+ value: parseDatabaseRowValue(datasetItem, mapping),});continue;}@@ -1266,7 +1280,7 @@ export async function extractVariablesFromTracingData({results.push({var: variable,- value: parseDatabaseRowToString(trace, mapping),+ value: parseDatabaseRowValue(trace, mapping),environment: trace.environment,});continue;@@ -1327,7 +1341,7 @@ export async function extractVariablesFromTracingData({results.push({var: variable,- value: parseDatabaseRowToString(observation, mapping),+ value: parseDatabaseRowValue(observation, mapping),environment: observation.environment,});continue;@@ -1342,10 +1356,13 @@ export async function extractVariablesFromTracingData({const snakeToCamel = (s: string) =>s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());-export const parseDatabaseRowToString = (+// Returns the typed value extracted from a database row. LLM-as-judge+// stringifies at template-substitution time via `compileEvalPrompt`; code-+// based evaluators consume the typed value directly.+export const parseDatabaseRowValue = (dbRow: Record<string, unknown>,mapping: z.infer<typeof variableMapping>,-): string => {+): unknown => {// Prisma returns camelCase keys, but selectedColumnId may be snake_caseconst selectedColumn =dbRow[mapping.selectedColumnId] ??diff --git a/worker/src/features/evaluation/evaluationHelpers.test.ts b/worker/src/features/evaluation/evaluationHelpers.test.tsindex aab5792554..7d16bb0583 100644--- a/worker/src/features/evaluation/evaluationHelpers.test.ts+++ b/worker/src/features/evaluation/evaluationHelpers.test.ts@@ -11,14 +11,16 @@ import {ScoreDataTypeEnum,validateEvalOutputResult,} from "@langfuse/shared";-import { type ExtractedVariable } from "./observationEval/extractObservationVariables";+import { type ExtractedVariable } from "@langfuse/shared/src/server";+import { parseDispatchResult } from "../../../../packages/shared/src/server/evals/codeEvalDispatcherTypes";+import { createDeterministicEvalScoreId } from "../../../../packages/shared/src/server/evals/evalScoreIds";import {buildEvalExecutionMetadata,buildEvalMessages,compileEvalPrompt,getEnvironmentFromVariables,} from "./evalRuntime";-import { buildEvalScoreWritePayloads, buildScoreEvent } from "./evalScoreEvent";+import { buildEvalScoreWritePayloads } from "./evalScoreEvent";describe("evaluation helpers", () => {describe("compileEvalPrompt", () => {@@ -70,6 +72,33 @@ describe("evaluation helpers", () => {const result = compileEvalPrompt(params);expect(result).toBe('Data: {"key": "value", "count": 42}');});++ it("stringifies non-string variable values via parseUnknownToString", () => {+ // Regression guard for the upstream refactor that made+ // `ExtractedVariable.value: unknown`. A naive `String(value)` would+ // render `"[object Object]"` for object inputs and the comma-joined+ // form for arrays — both useless to an LLM.+ const params = {+ templatePrompt:+ "meta={{meta}} tools={{tools}} score={{score}} flag={{flag}} missing={{missing}}",+ variables: [+ { var: "meta", value: { key: "value", count: 42 } },+ { var: "tools", value: ["get_weather", "search_web"] },+ { var: "score", value: 0.85 },+ { var: "flag", value: true },+ { var: "missing", value: null },+ ] as ExtractedVariable[],+ };++ const result = compileEvalPrompt(params);++ expect(result).toContain('meta={"key":"value","count":42}');+ expect(result).not.toContain("[object Object]");+ expect(result).toContain('tools=["get_weather","search_web"]');+ expect(result).toContain("score=0.85");+ expect(result).toContain("flag=true");+ expect(result).toContain("missing=");+ });});describe("buildEvalOutputResultSchema", () => {@@ -353,119 +382,206 @@ describe("evaluation helpers", () => {});});- describe("buildScoreEvent", () => {- it("should build complete score event", () => {- const params = {- eventId: "event-123",- scoreId: "score-456",- traceId: "trace-789",- observationId: null,- scoreName: "accuracy",- scoreValue: 0.85,- reasoning: "High accuracy observed",- environment: "production",- executionTraceId: "exec-trace-abc",- metadata: { job_execution_id: "exec-123" },- dataType: ScoreDataTypeEnum.NUMERIC,- };-- const result = buildScoreEvent(params);+ describe("parseDispatchResult", () => {+ it("should preserve optional per-score metadata from code eval runners", () => {+ const result = parseDispatchResult({+ scores: [+ {+ name: "quality",+ dataType: ScoreDataTypeEnum.NUMERIC,+ value: 0.9,+ metadata: { rubric: "strict" },+ },+ ],+ });- expect(result.id).toBe("event-123");- expect(result.type).toBe("score-create");- expect(result.body.id).toBe("score-456");- expect(result.body.traceId).toBe("trace-789");- expect(result.body.observationId).toBeNull();- expect(result.body.name).toBe("accuracy");- expect(result.body.value).toBe(0.85);- expect(result.body.comment).toBe("High accuracy observed");- expect(result.body.source).toBe("EVAL");- expect(result.body.environment).toBe("production");- expect(result.body.executionTraceId).toBe("exec-trace-abc");- expect(result.body.metadata).toEqual({ job_execution_id: "exec-123" });- expect(result.body.dataType).toBe("NUMERIC");+ expect(result.scores[0]).toMatchObject({+ dataType: ScoreDataTypeEnum.NUMERIC,+ value: 0.9,+ metadata: { rubric: "strict" },+ });});- it("should include observation ID when provided", () => {- const params = {- eventId: "event-123",- scoreId: "score-456",- traceId: "trace-789",- observationId: "obs-abc",- scoreName: "relevance",- scoreValue: 0.9,- reasoning: "Highly relevant",- environment: "default",- executionTraceId: "exec-trace-def",- metadata: {},- dataType: ScoreDataTypeEnum.NUMERIC,- };+ it("should reject non-object score metadata from code eval runners", () => {+ expect(() =>+ parseDispatchResult({+ scores: [+ {+ name: "quality",+ dataType: ScoreDataTypeEnum.NUMERIC,+ value: 0.9,+ metadata: "not-a-dict",+ },+ ],+ }),+ ).toThrow("Invalid code eval result");+ });+ });- const result = buildScoreEvent(params);+ describe("buildEvalScoreWritePayloads", () => {+ it("should build stable code eval score IDs when different score names reorder", () => {+ const originalPayloads = buildEvalScoreWritePayloads({+ scores: [+ {+ dataType: ScoreDataTypeEnum.NUMERIC,+ value: 0.9,+ name: "accuracy",+ },+ {+ dataType: ScoreDataTypeEnum.NUMERIC,+ value: 0.7,+ name: "fluency",+ },+ ],+ jobExecutionId: "job-1",+ traceId: "trace-456",+ observationId: "obs-789",+ environment: "production",+ executionTraceId: "exec-trace-789",+ executionMetadata: { job_execution_id: "job-1" },+ });+ const reorderedPayloads = buildEvalScoreWritePayloads({+ scores: [+ {+ dataType: ScoreDataTypeEnum.NUMERIC,+ value: 0.7,+ name: "fluency",+ },+ {+ dataType: ScoreDataTypeEnum.NUMERIC,+ value: 0.9,+ name: "accuracy",+ },+ ],+ jobExecutionId: "job-1",+ traceId: "trace-456",+ observationId: "obs-789",+ environment: "production",+ executionTraceId: "exec-trace-789",+ executionMetadata: { job_execution_id: "job-1" },+ });- expect(result.body.observationId).toBe("obs-abc");+ expect(originalPayloads[0].scoreId).toBe(reorderedPayloads[1].scoreId);+ expect(originalPayloads[1].scoreId).toBe(reorderedPayloads[0].scoreId);});- it("should build categorical score events", () => {- const result = buildScoreEvent({- eventId: "event-123",- scoreId: "score-456",- traceId: "trace-789",- observationId: null,- scoreName: "factuality",- scoreValue: "correct",- reasoning: "The answer is fully supported.",+ it("should build distinct deterministic code eval score IDs for duplicate score names", () => {+ const result = buildEvalScoreWritePayloads({+ scores: [+ {+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ value: "correct",+ name: "accuracy",+ },+ {+ dataType: ScoreDataTypeEnum.NUMERIC,+ value: 0.7,+ name: "fluency",+ },+ {+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ value: "partial",+ name: "accuracy",+ },+ ],+ jobExecutionId: "job-1",+ traceId: "trace-456",+ observationId: "obs-789",environment: "production",- executionTraceId: "exec-trace-abc",- metadata: { job_execution_id: "exec-123" },- dataType: ScoreDataTypeEnum.CATEGORICAL,+ executionTraceId: "exec-trace-789",+ executionMetadata: { job_execution_id: "job-1" },});-- expect(result.body.value).toBe("correct");- expect(result.body.dataType).toBe("CATEGORICAL");+ const scoreIds = result.map((payload) => payload.scoreId);++ expect(new Set(scoreIds).size).toBe(3);+ expect(scoreIds).toEqual([+ createDeterministicEvalScoreId({+ jobExecutionId: "job-1",+ scoreName: "accuracy",+ occurrenceIndex: 0,+ }),+ createDeterministicEvalScoreId({+ jobExecutionId: "job-1",+ scoreName: "fluency",+ occurrenceIndex: 0,+ }),+ createDeterministicEvalScoreId({+ jobExecutionId: "job-1",+ scoreName: "accuracy",+ occurrenceIndex: 1,+ }),+ ]);});- it("should build boolean score events", () => {- const result = buildScoreEvent({- eventId: "event-123",- scoreId: "score-456",- traceId: "trace-789",- observationId: null,- scoreName: "correctness",- scoreValue: 1,- reasoning: "The answer meets the criteria.",+ it("should build deterministic score IDs as part of payload creation", () => {+ const expectedScoreIds = [+ createDeterministicEvalScoreId({+ jobExecutionId: "job-1",+ scoreName: "accuracy",+ occurrenceIndex: 0,+ }),+ createDeterministicEvalScoreId({+ jobExecutionId: "job-1",+ scoreName: "accuracy",+ occurrenceIndex: 1,+ }),+ ];+ const result = buildEvalScoreWritePayloads({+ scores: [+ {+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ value: "correct",+ name: "accuracy",+ },+ {+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ value: "partial",+ name: "accuracy",+ },+ ],+ jobExecutionId: "job-1",+ traceId: "trace-456",+ observationId: "obs-789",environment: "production",- executionTraceId: "exec-trace-abc",- metadata: { job_execution_id: "exec-123" },- dataType: ScoreDataTypeEnum.BOOLEAN,+ executionTraceId: "exec-trace-789",+ executionMetadata: { job_execution_id: "job-1" },});- expect(result.body.value).toBe(1);- expect(result.body.dataType).toBe("BOOLEAN");+ expect(result.map((payload) => payload.scoreId)).toEqual(+ expectedScoreIds,+ );+ expect(result.map((payload) => payload.event.body.id)).toEqual(+ expectedScoreIds,+ );});- });- describe("buildEvalScoreWritePayloads", () => {it("should build a single numeric score payload", () => {+ const scoreId = createDeterministicEvalScoreId({+ jobExecutionId: "job-1",+ scoreName: "accuracy",+ occurrenceIndex: 0,+ });const result = buildEvalScoreWritePayloads({- outputResult: {- dataType: ScoreDataTypeEnum.NUMERIC,- score: 0.85,- reasoning: "High accuracy observed",- },- primaryScoreId: "score-123",+ scores: [+ {+ dataType: ScoreDataTypeEnum.NUMERIC,+ value: 0.85,+ name: "accuracy",+ comment: "High accuracy observed",+ },+ ],+ jobExecutionId: "job-1",traceId: "trace-456",observationId: null,- scoreName: "accuracy",environment: "production",executionTraceId: "exec-trace-789",- metadata: { job_execution_id: "job-1" },+ executionMetadata: { job_execution_id: "job-1" },});expect(result).toHaveLength(1);expect(result[0]).toEqual({eventId: expect.any(String),- scoreId: "score-123",+ scoreId,event: expect.objectContaining({body: expect.objectContaining({value: 0.85,@@ -476,25 +592,32 @@ describe("evaluation helpers", () => {});it("should build a single boolean score payload", () => {+ const scoreId = createDeterministicEvalScoreId({+ jobExecutionId: "job-1",+ scoreName: "correctness",+ occurrenceIndex: 0,+ });const result = buildEvalScoreWritePayloads({- outputResult: {- dataType: ScoreDataTypeEnum.BOOLEAN,- score: true,- reasoning: "The answer satisfies the criteria",- },- primaryScoreId: "score-123",+ scores: [+ {+ dataType: ScoreDataTypeEnum.BOOLEAN,+ value: 1,+ name: "correctness",+ comment: "The answer satisfies the criteria",+ },+ ],+ jobExecutionId: "job-1",traceId: "trace-456",observationId: null,- scoreName: "correctness",environment: "production",executionTraceId: "exec-trace-789",- metadata: { job_execution_id: "job-1" },+ executionMetadata: { job_execution_id: "job-1" },});expect(result).toHaveLength(1);expect(result[0]).toEqual({eventId: expect.any(String),- scoreId: "score-123",+ scoreId,event: expect.objectContaining({body: expect.objectContaining({value: 1,@@ -505,24 +628,42 @@ describe("evaluation helpers", () => {});it("should build one categorical payload per match while preserving shared metadata", () => {+ const firstScoreId = createDeterministicEvalScoreId({+ jobExecutionId: "job-1",+ scoreName: "accuracy",+ occurrenceIndex: 0,+ });+ const secondScoreId = createDeterministicEvalScoreId({+ jobExecutionId: "job-1",+ scoreName: "accuracy",+ occurrenceIndex: 1,+ });const result = buildEvalScoreWritePayloads({- outputResult: {- dataType: ScoreDataTypeEnum.CATEGORICAL,- matches: ["correct", "partial"],- reasoning: "Both categories apply",- },- primaryScoreId: "score-123",+ scores: [+ {+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ value: "correct",+ name: "accuracy",+ comment: "Both categories apply",+ },+ {+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ value: "partial",+ name: "accuracy",+ comment: "Both categories apply",+ },+ ],+ jobExecutionId: "job-1",traceId: "trace-456",observationId: "obs-789",- scoreName: "accuracy",environment: "production",executionTraceId: "exec-trace-789",- metadata: { job_execution_id: "job-1" },+ executionMetadata: { job_execution_id: "job-1" },});expect(result).toHaveLength(2);- expect(result[0].scoreId).toBe("score-123");- expect(result[1].scoreId).not.toBe("score-123");+ expect(result[0].scoreId).toBe(firstScoreId);+ expect(result[1].scoreId).toBe(secondScoreId);expect(result[0].event.body.value).toBe("correct");expect(result[1].event.body.value).toBe("partial");expect(result[0].event.body.comment).toBe("Both categories apply");@@ -534,6 +675,48 @@ describe("evaluation helpers", () => {job_execution_id: "job-1",});});++ it("should merge returned score metadata with execution metadata", () => {+ const result = buildEvalScoreWritePayloads({+ scores: [+ {+ dataType: ScoreDataTypeEnum.NUMERIC,+ value: 0.9,+ name: "accuracy",+ metadata: {+ rubric: "strict",+ tags: ["math", "strict"],+ job_execution_id: "user-supplied-job",+ },+ },+ {+ dataType: ScoreDataTypeEnum.NUMERIC,+ value: 0.7,+ name: "fluency",+ },+ ],+ jobExecutionId: "job-1",+ traceId: "trace-456",+ observationId: "obs-789",+ environment: "production",+ executionTraceId: "exec-trace-789",+ executionMetadata: {+ job_execution_id: "job-1",+ dispatcher_name: "test-dispatcher",+ },+ });++ expect(result[0].event.body.metadata).toEqual({+ rubric: "strict",+ tags: ["math", "strict"],+ job_execution_id: "job-1",+ dispatcher_name: "test-dispatcher",+ });+ expect(result[1].event.body.metadata).toEqual({+ job_execution_id: "job-1",+ dispatcher_name: "test-dispatcher",+ });+ });});describe("getEnvironmentFromVariables", () => {diff --git a/worker/src/features/evaluation/executeLLMAsJudgeEvaluation.test.ts b/worker/src/features/evaluation/executeLLMAsJudgeEvaluation.test.tsindex abd3ca6fb7..3b1e2c22d4 100644--- a/worker/src/features/evaluation/executeLLMAsJudgeEvaluation.test.ts+++ b/worker/src/features/evaluation/executeLLMAsJudgeEvaluation.test.ts@@ -4,7 +4,7 @@ import z from "zod";import { executeLLMAsJudgeEvaluation } from "./evalService";import { createMockEvalExecutionDeps } from "./evalExecutionDeps";import { UnrecoverableError } from "../../errors/UnrecoverableError";-import { ExtractedVariable } from "./observationEval/extractObservationVariables";+import { type ExtractedVariable } from "@langfuse/shared/src/server";import {EvalTargetObject,type PersistedEvalOutputDefinition,@@ -453,7 +453,6 @@ describe("executeLLMAsJudgeEvaluation", () => {job_execution_id: jobExecutionId,job_configuration_id: mockJobExecution.jobConfigurationId,target_trace_id: mockJobExecution.jobInputTraceId,- score_id: expect.any(String),}),}),}),diff --git a/worker/src/features/evaluation/observationEval/__tests__/createSchedulerDeps.test.ts b/worker/src/features/evaluation/observationEval/__tests__/createSchedulerDeps.test.tsnew file mode 100644index 0000000000..7975f0a593--- /dev/null+++ b/worker/src/features/evaluation/observationEval/__tests__/createSchedulerDeps.test.ts@@ -0,0 +1,81 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { EvalTemplateType } from "@langfuse/shared/src/db";++const addToLLMQueue = vi.fn();+const addToCodeQueue = vi.fn();+const getLLMQueueInstance = vi.fn(() => ({ add: addToLLMQueue }));+const getCodeQueueInstance = vi.fn(() => ({ add: addToCodeQueue }));++vi.mock("@langfuse/shared/src/server", async () => {+ const actual = await vi.importActual("@langfuse/shared/src/server");++ return {+ ...actual,+ LLMAsJudgeExecutionQueue: {+ getInstance: getLLMQueueInstance,+ },+ CodeEvalExecutionQueue: {+ getInstance: getCodeQueueInstance,+ },+ };+});++describe("createObservationEvalSchedulerDeps", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("routes LLM-as-judge observation eval jobs to the LLM queue", async () => {+ const { createObservationEvalSchedulerDeps } =+ await import("../createSchedulerDeps");++ await createObservationEvalSchedulerDeps().enqueueEvalJob({+ projectId: "project-1",+ jobExecutionId: "job-1",+ observationS3Path: "evals/project-1/observations/obs-1.json",+ delay: 10,+ evalTemplateType: EvalTemplateType.LLM_AS_JUDGE,+ });++ expect(getLLMQueueInstance).toHaveBeenCalledWith({+ shardingKey: "project-1-job-1",+ });+ expect(addToLLMQueue).toHaveBeenCalledWith(+ "llm-as-a-judge-execution-queue",+ expect.objectContaining({+ name: "llm-as-a-judge-execution-job",+ id: "job-1",+ payload: expect.objectContaining({ projectId: "project-1" }),+ }),+ { delay: 10 },+ );+ expect(getCodeQueueInstance).not.toHaveBeenCalled();+ });++ it("routes code observation eval jobs to the code eval queue", async () => {+ const { createObservationEvalSchedulerDeps } =+ await import("../createSchedulerDeps");++ await createObservationEvalSchedulerDeps().enqueueEvalJob({+ projectId: "project-1",+ jobExecutionId: "job-2",+ observationS3Path: "evals/project-1/observations/obs-1.json",+ delay: 20,+ evalTemplateType: EvalTemplateType.CODE,+ });++ expect(getCodeQueueInstance).toHaveBeenCalledWith({+ shardingKey: "project-1-job-2",+ });+ expect(addToCodeQueue).toHaveBeenCalledWith(+ "code-eval-execution-queue",+ expect.objectContaining({+ name: "code-eval-execution-job",+ id: "job-2",+ payload: expect.objectContaining({ projectId: "project-1" }),+ }),+ { delay: 20 },+ );+ expect(getLLMQueueInstance).not.toHaveBeenCalled();+ });+});diff --git a/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.ts b/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.tsindex 754fe18133..1a8bc66a79 100644--- a/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.ts+++ b/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from "vitest";-import { extractObservationVariables } from "../extractObservationVariables";+import { extractObservationVariables } from "../../../../../../packages/shared/src/server/evals/extractObservationVariables";import { type ObservationForEval } from "../types";import {availableObservationEvalVariableColumns,@@ -124,7 +124,7 @@ describe("extractObservationVariables", () => {expect(result).toHaveLength(1);expect(result[0].var).toBe("meta");- expect(result[0].value).toBe(JSON.stringify(mockObservation.metadata));+ expect(result[0].value).toEqual(mockObservation.metadata);});it("should extract multiple variables", () => {@@ -167,7 +167,7 @@ describe("extractObservationVariables", () => {expect(result).toHaveLength(1);expect(result[0].var).toBe("tools");- expect(result[0].value).toBe(JSON.stringify(mockObservation.tool_calls));+ expect(result[0].value).toEqual(mockObservation.tool_calls);});it("should extract toolDefinitions variable", () => {@@ -188,9 +188,7 @@ describe("extractObservationVariables", () => {expect(result).toHaveLength(1);expect(result[0].var).toBe("definitions");- expect(result[0].value).toBe(- JSON.stringify(mockObservation.tool_definitions),- );+ expect(result[0].value).toEqual(mockObservation.tool_definitions);});});@@ -254,7 +252,7 @@ describe("extractObservationVariables", () => {expect(result[0].value).toBe("expected response");});- it("should extract experimentItemMetadata variable as JSON string", () => {+ it("should extract experimentItemMetadata variable", () => {const variableMapping: ObservationVariableMapping[] = [{templateVariable: "item_metadata",@@ -269,9 +267,7 @@ describe("extractObservationVariables", () => {expect(result).toHaveLength(1);expect(result[0].var).toBe("item_metadata");- expect(result[0].value).toBe(- JSON.stringify(mockObservation.experiment_item_metadata),- );+ expect(result[0].value).toEqual(mockObservation.experiment_item_metadata);});});@@ -291,9 +287,7 @@ describe("extractObservationVariables", () => {expect(result).toHaveLength(1);expect(result[0].var).toBe("usage");- expect(result[0].value).toBe(- JSON.stringify(mockObservation.usage_details),- );+ expect(result[0].value).toEqual(mockObservation.usage_details);});it("should extract costDetails variable", () => {@@ -311,9 +305,7 @@ describe("extractObservationVariables", () => {expect(result).toHaveLength(1);expect(result[0].var).toBe("cost");- expect(result[0].value).toBe(- JSON.stringify(mockObservation.cost_details),- );+ expect(result[0].value).toEqual(mockObservation.cost_details);});});@@ -401,9 +393,7 @@ describe("extractObservationVariables", () => {variableMapping,});- expect(result[0].value).toBe(- JSON.stringify(["get_weather", "search_web"]),- );+ expect(result[0].value).toEqual(["get_weather", "search_web"]);});it("should handle null jsonSelector by returning full value", () => {@@ -439,6 +429,30 @@ describe("extractObservationVariables", () => {expect(result[0].value).toBe(mockObservation.input);});++ it("keeps raw value for no-selector mapping when selector sibling uses the same JSON string column", () => {+ const variableMapping: ObservationVariableMapping[] = [+ {+ templateVariable: "rawInput",+ selectedColumnId: "input",+ },+ {+ templateVariable: "prompt",+ selectedColumnId: "input",+ jsonSelector: "$.prompt",+ },+ ];++ const result = extractObservationVariables({+ observation: mockObservation,+ variableMapping,+ });++ expect(result).toEqual([+ { var: "rawInput", value: mockObservation.input },+ { var: "prompt", value: "Hello, how are you?" },+ ]);+ });});describe("edge cases", () => {@@ -471,8 +485,8 @@ describe("extractObservationVariables", () => {availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],);- expect(result[0].value).toBe("");- expect(result[1].value).toBe("");+ expect(result[0].value).toBeNull();+ expect(result[1].value).toBeUndefined();});it("should handle invalid JSON selector gracefully", () => {@@ -492,8 +506,8 @@ describe("extractObservationVariables", () => {availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],);- // Non-matching JSONPath returns empty string- expect(result[0].value).toBe("");+ // Non-matching JSONPath returns undefined+ expect(result[0].value).toBeUndefined();});it("should handle non-JSON string column with JSON selector", () => {@@ -566,7 +580,7 @@ describe("extractObservationVariables", () => {variableMapping,});- expect(result[0].value).toBe(JSON.stringify(mockObservation.metadata));+ expect(result[0].value).toEqual(mockObservation.metadata);});});});diff --git a/worker/src/features/evaluation/observationEval/__tests__/fixtures.ts b/worker/src/features/evaluation/observationEval/__tests__/fixtures.tsindex 02de3d0f58..c98494bbee 100644--- a/worker/src/features/evaluation/observationEval/__tests__/fixtures.ts+++ b/worker/src/features/evaluation/observationEval/__tests__/fixtures.ts@@ -1,7 +1,12 @@import { vi, type Mock } from "vitest";import { randomUUID } from "crypto";import { type Prisma } from "@langfuse/shared/src/db";-import { type ObservationForEval, EvalTargetObject } from "@langfuse/shared";+import {+ EvalTemplateSourceCodeLanguage,+ EvalTemplateType,+ type ObservationForEval,+ EvalTargetObject,+} from "@langfuse/shared";import {type ObservationEvalConfig,type ObservationEvalSchedulerDeps,@@ -24,6 +29,7 @@ type MockProcessorDeps = ObservationEvalProcessorDeps & {downloadObservationFromS3: Mock<ObservationEvalProcessorDeps["downloadObservationFromS3"]>;+ evalExecutionDeps: EvalExecutionDeps;};/**@@ -108,6 +114,7 @@ export function createTestEvalConfig(filter: [],sampling: { toNumber: () => 1 } as unknown as Prisma.Decimal,evalTemplateId: `template-${randomUUID()}`,+ evalTemplate: { type: EvalTemplateType.LLM_AS_JUDGE },scoreName: "test-score",status: "ACTIVE",blockedAt: null,@@ -161,6 +168,7 @@ export function createMockProcessorDeps(downloadObservationFromS3: Mock<ObservationEvalProcessorDeps["downloadObservationFromS3"]>;+ evalExecutionDeps: EvalExecutionDeps;}> = {},): MockProcessorDeps {const defaultObservation = createTestObservation();@@ -171,6 +179,8 @@ export function createMockProcessorDeps(vi.fn<ObservationEvalProcessorDeps["downloadObservationFromS3"]>().mockResolvedValue(JSON.stringify(defaultObservation)),+ evalExecutionDeps:+ overrides.evalExecutionDeps ?? createMockEvalExecutionDeps(),};}@@ -269,6 +279,7 @@ export function createMockJobConfiguration(overrides.evalTemplate !== undefined? overrides.evalTemplate: createMockEvalTemplate({ id: templateId, projectId }),+ project: { orgId: "test-org-123" },};}@@ -281,11 +292,14 @@ export function createMockEvalTemplate(projectId: string | null;name: string;version: number;- prompt: string;+ type: EvalTemplateType;+ prompt: string | null;model: string;provider: string;modelParams: Record<string, unknown>;- outputDefinition: Record<string, string>;+ outputDefinition: Record<string, string> | null;+ sourceCode: string | null;+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage | null;vars: string[];createdAt: Date;updatedAt: Date;@@ -293,19 +307,27 @@ export function createMockEvalTemplate() {return {id: overrides.id ?? `template-${randomUUID()}`,- projectId: overrides.projectId ?? "test-project-123",+ projectId:+ "projectId" in overrides ? overrides.projectId : "test-project-123",name: overrides.name ?? "Test Evaluator",version: overrides.version ?? 1,+ type: overrides.type ?? EvalTemplateType.LLM_AS_JUDGE,prompt:- overrides.prompt ??- "Evaluate the following output: {{output}}. Score 0-1.",+ "prompt" in overrides+ ? overrides.prompt+ : "Evaluate the following output: {{output}}. Score 0-1.",model: overrides.model ?? "gpt-4",provider: overrides.provider ?? "openai",modelParams: overrides.modelParams ?? {},- outputDefinition: overrides.outputDefinition ?? {- score: "A number between 0 and 1",- reasoning: "Explain your reasoning",- },+ outputDefinition:+ "outputDefinition" in overrides+ ? overrides.outputDefinition+ : {+ score: "A number between 0 and 1",+ reasoning: "Explain your reasoning",+ },+ sourceCode: overrides.sourceCode ?? null,+ sourceCodeLanguage: overrides.sourceCodeLanguage ?? null,vars: overrides.vars ?? ["output"],createdAt: overrides.createdAt ?? new Date(),updatedAt: overrides.updatedAt ?? new Date(),@@ -344,18 +366,6 @@ export function createFullyMockedEvalPipeline(.mockResolvedValue(undefined),};- const processorDeps: MockProcessorDeps = {- downloadObservationFromS3: vi- .fn<ObservationEvalProcessorDeps["downloadObservationFromS3"]>()- .mockImplementation(async (path) => {- const data = uploadedData.get(path);- if (data) {- return JSON.stringify(data);- }- return JSON.stringify(observation);- }),- };-const executionDeps: EvalExecutionDeps = createMockEvalExecutionDeps({callLLM: vi.fn()@@ -376,6 +386,19 @@ export function createFullyMockedEvalPipeline(updateJobExecution: vi.fn().mockResolvedValue(undefined),});+ const processorDeps: MockProcessorDeps = {+ downloadObservationFromS3: vi+ .fn<ObservationEvalProcessorDeps["downloadObservationFromS3"]>()+ .mockImplementation(async (path) => {+ const data = uploadedData.get(path);+ if (data) {+ return JSON.stringify(data);+ }+ return JSON.stringify(observation);+ }),+ evalExecutionDeps: executionDeps,+ };+return {schedulerDeps,processorDeps,diff --git a/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.ts b/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.tsindex 7567b0f162..84f3fc31bc 100644--- a/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.ts+++ b/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.ts@@ -1,5 +1,10 @@import { describe, it, expect, vi, beforeEach, type Mock } from "vitest";-import { JobExecutionStatus, type Prisma } from "@prisma/client";+import {+ EvalTemplateSourceCodeLanguage,+ EvalTemplateType,+ JobExecutionStatus,+ type Prisma,+} from "@prisma/client";import { randomUUID } from "crypto";import { scheduleObservationEvals } from "../scheduleObservationEvals";import { processObservationEval } from "../observationEvalProcessor";@@ -8,8 +13,18 @@ import {createTestObservation,createTestEvalConfig,createFullyMockedEvalPipeline,+ createMockEvalTemplate,+ createMockJobConfiguration,+ createMockJobExecution,} from "./fixtures";-import { type ObservationForEval, EvalTargetObject } from "@langfuse/shared";+import {+ EvalTargetObject,+ type ObservationVariableMapping,+} from "@langfuse/shared";++const mocks = vi.hoisted(() => ({+ writeInternalTrace: vi.fn(),+}));// Mock prisma for processObservationEvalvi.mock("@langfuse/shared/src/db", () => ({@@ -24,14 +39,20 @@ vi.mock("@langfuse/shared/src/db", () => ({},}));-// Mock executeLLMAsJudgeEvaluation+// Mock runLLMAsJudgeEvaluationvi.mock("../../evalService", () => ({- executeLLMAsJudgeEvaluation: vi.fn(),+ runLLMAsJudgeEvaluation: vi.fn(),+}));++vi.mock("../../../internal-tracing/createInternalEventsWriter", () => ({+ createInternalEventsWriter: () => ({ write: mocks.writeInternalTrace }),}));// Mock loggervi.mock("@langfuse/shared/src/server", async () => {- const actual = await vi.importActual("@langfuse/shared/src/server");+ const actual = await vi.importActual<+ typeof import("@langfuse/shared/src/server")+ >("@langfuse/shared/src/server");return {...actual,logger: {@@ -41,17 +62,36 @@ vi.mock("@langfuse/shared/src/server", async () => {error: vi.fn(),},DEFAULT_TRACE_ENVIRONMENT: "default",+ resolveConfiguredCodeEvalDispatcher: vi.fn(+ () => new actual.LocalCodeEvalDispatcher(),+ ),};});import { prisma } from "@langfuse/shared/src/db";-import { executeLLMAsJudgeEvaluation } from "../../evalService";+import { runLLMAsJudgeEvaluation } from "../../evalService";++const mockEvalExecutionResult = {+ scores: [+ {+ dataType: "NUMERIC" as const,+ value: 0.85,+ name: "test-score",+ comment: "Good response",+ },+ ],+ executionTraceId: "trace-123",+ metadata: {},+};describe("Observation Eval E2E Pipeline", () => {const projectId = "test-project-123";beforeEach(() => {vi.clearAllMocks();+ (runLLMAsJudgeEvaluation as Mock).mockResolvedValue(+ mockEvalExecutionResult,+ );});describe("full pipeline: schedule → process → execute", () => {@@ -97,7 +137,7 @@ describe("Observation Eval E2E Pipeline", () => {let capturedJobExecutionId: string | undefined;const mockCreateJobExecution = vi.fn<ObservationEvalSchedulerDeps["upsertJobExecution"]>()- .mockImplementation(async (params) => {+ .mockImplementation(async () => {capturedJobExecutionId = `job-exec-${randomUUID()}`;return { id: capturedJobExecutionId };});@@ -159,6 +199,7 @@ describe("Observation Eval E2E Pipeline", () => {projectId,name: "Accuracy Evaluator",version: 1,+ type: EvalTemplateType.LLM_AS_JUDGE,prompt: "Evaluate the accuracy of: {{output}}",model: "gpt-4",provider: "openai",@@ -167,6 +208,8 @@ describe("Observation Eval E2E Pipeline", () => {score: "A number between 0 and 1",reasoning: "Explanation",},+ sourceCode: null,+ sourceCodeLanguage: null,vars: ["output"],createdAt: new Date(),updatedAt: new Date(),@@ -188,6 +231,7 @@ describe("Observation Eval E2E Pipeline", () => {createdAt: new Date(),updatedAt: new Date(),evalTemplate: mockTemplate,+ project: { orgId: "test-org-123" },};(prisma.jobExecution.findFirst as Mock).mockResolvedValue(mockJob);@@ -200,6 +244,7 @@ describe("Observation Eval E2E Pipeline", () => {jobExecutionId: capturedJobExecutionId!,observationS3Path,},+ executionType: EvalTemplateType.LLM_AS_JUDGE,deps: pipeline.processorDeps,});@@ -207,9 +252,10 @@ describe("Observation Eval E2E Pipeline", () => {expect(pipeline.processorDeps.downloadObservationFromS3,).toHaveBeenCalledWith(observationS3Path);- expect(executeLLMAsJudgeEvaluation).toHaveBeenCalledWith(+ expect(runLLMAsJudgeEvaluation).toHaveBeenCalledWith(expect.objectContaining({projectId,+ organizationId: "test-org-123",jobExecutionId: capturedJobExecutionId,extractedVariables: expect.arrayContaining([expect.objectContaining({@@ -222,6 +268,139 @@ describe("Observation Eval E2E Pipeline", () => {);});+ it("should process a code-based eval through execution and score persistence", async () => {+ const observation = createTestObservation({+ project_id: projectId,+ input: { question: "2+2" },+ output: { answer: "4" },+ metadata: { rubric: "math" },+ experiment_id: "experiment-123",+ experiment_item_expected_output: "4",+ environment: "production",+ });+ const variableMapping: ObservationVariableMapping[] = [+ { templateVariable: "input", selectedColumnId: "input" },+ { templateVariable: "output", selectedColumnId: "output" },+ {+ templateVariable: "metadata",+ selectedColumnId: "metadata",+ },+ {+ templateVariable: "experimentItemExpectedOutput",+ selectedColumnId: "experimentItemExpectedOutput",+ },+ ];+ const config = createTestEvalConfig({+ id: `config-${randomUUID()}`,+ projectId,+ scoreName: "code-score",+ variableMapping,+ });+ const pipeline = createFullyMockedEvalPipeline({ observation });+ const job = createMockJobExecution({+ id: `job-exec-${randomUUID()}`,+ projectId,+ jobConfigurationId: config.id,+ jobInputTraceId: observation.trace_id,+ jobInputObservationId: observation.span_id,+ });+ const template = createMockEvalTemplate({+ id: config.evalTemplateId,+ projectId,+ name: "Code nested context evaluator",+ type: EvalTemplateType.CODE,+ prompt: null,+ outputDefinition: null,+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.TYPESCRIPT,+ sourceCode: `+ function evaluate(ctx) {+ const matched =+ ctx.observation.input.question === "2+2" &&+ ctx.observation.output.answer === ctx.experiment?.itemExpectedOutput &&+ ctx.observation.metadata.rubric === "math";++ return {+ scores: [+ {+ name: "nested-context-score",+ value: matched ? 1 : 0,+ dataType: "BOOLEAN",+ comment: ctx.experiment?.itemExpectedOutput,+ },+ ],+ };+ }+ `,+ });+ const mockConfig = createMockJobConfiguration({+ id: config.id,+ projectId,+ evalTemplateId: config.evalTemplateId,+ scoreName: config.scoreName,+ variableMapping,+ evalTemplate: template,+ });++ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);+ (prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(mockConfig);++ await processObservationEval({+ event: {+ projectId,+ jobExecutionId: job.id,+ observationS3Path: "test-path",+ },+ executionType: EvalTemplateType.CODE,+ deps: pipeline.processorDeps,+ });++ expect(+ pipeline.processorDeps.downloadObservationFromS3,+ ).toHaveBeenCalledWith("test-path");+ expect(pipeline.executionDeps.uploadScore).toHaveBeenCalledTimes(1);+ expect(+ pipeline.executionDeps.enqueueScoreIngestion,+ ).toHaveBeenCalledTimes(1);+ expect(pipeline.executionDeps.updateJobExecution).toHaveBeenCalledWith(+ expect.objectContaining({+ id: job.id,+ projectId,+ data: expect.objectContaining({+ status: JobExecutionStatus.COMPLETED,+ executionTraceId: expect.any(String),+ jobOutputScoreId: expect.any(String),+ }),+ }),+ );+ expect(pipeline.executionDeps.uploadScore).toHaveBeenCalledWith(+ expect.objectContaining({+ projectId,+ event: expect.objectContaining({+ body: expect.objectContaining({+ traceId: observation.trace_id,+ observationId: observation.span_id,+ name: "nested-context-score",+ value: 1,+ dataType: "BOOLEAN",+ comment: "4",+ environment: "production",+ source: "EVAL",+ }),+ }),+ }),+ );+ expect(mocks.writeInternalTrace).toHaveBeenCalledWith(+ expect.objectContaining({+ eventInputs: [+ expect.objectContaining({+ input: expect.stringContaining('"observation"'),+ output: expect.stringContaining('"nested-context-score"'),+ }),+ ],+ }),+ );+ });+it("should not schedule eval when filter does not match", async () => {const observation = createTestObservation({project_id: projectId,@@ -388,11 +567,14 @@ describe("Observation Eval E2E Pipeline", () => {projectId,name: "Test Eval",version: 1,+ type: EvalTemplateType.LLM_AS_JUDGE,prompt: "Q: {{question}} A: {{answer}}",model: "gpt-4",provider: "openai",modelParams: {},outputDefinition: { score: "0-1", reasoning: "Why" },+ sourceCode: null,+ sourceCodeLanguage: null,vars: ["question", "answer"],createdAt: new Date(),updatedAt: new Date(),@@ -414,6 +596,7 @@ describe("Observation Eval E2E Pipeline", () => {createdAt: new Date(),updatedAt: new Date(),evalTemplate: mockTemplate,+ project: { orgId: "test-org-123" },};(prisma.jobExecution.findFirst as Mock).mockResolvedValue(mockJob);@@ -425,10 +608,11 @@ describe("Observation Eval E2E Pipeline", () => {jobExecutionId: "job-123",observationS3Path: "test-path",},+ executionType: EvalTemplateType.LLM_AS_JUDGE,deps: pipeline.processorDeps,});- expect(executeLLMAsJudgeEvaluation).toHaveBeenCalledWith(+ expect(runLLMAsJudgeEvaluation).toHaveBeenCalledWith(expect.objectContaining({extractedVariables: expect.arrayContaining([expect.objectContaining({@@ -488,11 +672,14 @@ describe("Observation Eval E2E Pipeline", () => {projectId,name: "Test Eval",version: 1,+ type: EvalTemplateType.LLM_AS_JUDGE,prompt: "Compare {{generated}} to {{expected}}",model: "gpt-4",provider: "openai",modelParams: {},outputDefinition: { score: "0-1", reasoning: "Why" },+ sourceCode: null,+ sourceCodeLanguage: null,vars: ["generated", "expected"],createdAt: new Date(),updatedAt: new Date(),@@ -514,6 +701,7 @@ describe("Observation Eval E2E Pipeline", () => {createdAt: new Date(),updatedAt: new Date(),evalTemplate: mockTemplate,+ project: { orgId: "test-org-123" },};(prisma.jobExecution.findFirst as Mock).mockResolvedValue(mockJob);@@ -525,10 +713,11 @@ describe("Observation Eval E2E Pipeline", () => {jobExecutionId: "job-123",observationS3Path: "test-path",},+ executionType: EvalTemplateType.LLM_AS_JUDGE,deps: pipeline.processorDeps,});- expect(executeLLMAsJudgeEvaluation).toHaveBeenCalledWith(+ expect(runLLMAsJudgeEvaluation).toHaveBeenCalledWith(expect.objectContaining({extractedVariables: expect.arrayContaining([expect.objectContaining({diff --git a/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts b/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.tsindex 8bebfcf772..fe7e59c1ba 100644--- a/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts+++ b/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts@@ -1,5 +1,10 @@import { describe, it, expect, vi, beforeEach, type Mock } from "vitest";-import { JobConfigState, JobExecutionStatus } from "@prisma/client";+import {+ EvalTemplateSourceCodeLanguage,+ EvalTemplateType,+ JobConfigState,+ JobExecutionStatus,+} from "@prisma/client";import {processObservationEval,type ObservationEvalProcessorDeps,@@ -31,16 +36,26 @@ vi.mock("@langfuse/shared/src/db", async () => {};});-// Mock executeLLMAsJudgeEvaluation+// Mock runLLMAsJudgeEvaluationvi.mock("../../evalService", () => ({- executeLLMAsJudgeEvaluation: vi.fn(),+ runLLMAsJudgeEvaluation: vi.fn(),+}));++vi.mock("../../codeBased", () => ({+ executeCodeBasedEvaluation: vi.fn(),}));// Mock loggervi.mock("@langfuse/shared/src/server", async () => {const actual = await vi.importActual("@langfuse/shared/src/server");+ const { extractObservationVariables } =+ await import("../../../../../../packages/shared/src/server/evals/extractObservationVariables");+ const { buildDeterministicEvalScoreIds } =+ await import("../../../../../../packages/shared/src/server/evals/evalScoreIds");return {...actual,+ buildDeterministicEvalScoreIds,+ extractObservationVariables,logger: {debug: vi.fn(),info: vi.fn(),@@ -52,7 +67,32 @@ vi.mock("@langfuse/shared/src/server", async () => {});import { prisma } from "@langfuse/shared/src/db";-import { executeLLMAsJudgeEvaluation } from "../../evalService";+import { executeCodeBasedEvaluation } from "../../codeBased";+import {+ createMockEvalExecutionDeps,+ type EvalExecutionDeps,+} from "../../evalExecutionDeps";+import { runLLMAsJudgeEvaluation } from "../../evalService";+import { createDeterministicEvalScoreId } from "../../../../../../packages/shared/src/server/evals/evalScoreIds";++const mockScoreId = createDeterministicEvalScoreId({+ jobExecutionId: "job-exec-456",+ scoreName: "test-score",+ occurrenceIndex: 0,+});++const mockEvalExecutionResult = {+ scores: [+ {+ dataType: "NUMERIC" as const,+ value: 0.5,+ name: "test-score",+ comment: "Mock eval result",+ },+ ],+ executionTraceId: "trace-123",+ metadata: {},+};describe("processObservationEval", () => {const projectId = "test-project-123";@@ -67,6 +107,12 @@ describe("processObservationEval", () => {beforeEach(() => {vi.clearAllMocks();+ (executeCodeBasedEvaluation as Mock).mockResolvedValue(+ mockEvalExecutionResult,+ );+ (runLLMAsJudgeEvaluation as Mock).mockResolvedValue(+ mockEvalExecutionResult,+ );});describe("job execution lookup", () => {@@ -75,7 +121,11 @@ describe("processObservationEval", () => {const deps = createMockProcessorDeps();- await processObservationEval({ event: baseEvent, deps });+ await processObservationEval({+ event: baseEvent,+ executionType: EvalTemplateType.LLM_AS_JUDGE,+ deps,+ });expect(prisma.jobExecution.findFirst).toHaveBeenCalledWith({where: {@@ -84,7 +134,7 @@ describe("processObservationEval", () => {},});expect(deps.downloadObservationFromS3).not.toHaveBeenCalled();- expect(executeLLMAsJudgeEvaluation).not.toHaveBeenCalled();+ expect(runLLMAsJudgeEvaluation).not.toHaveBeenCalled();});});@@ -102,10 +152,18 @@ describe("processObservationEval", () => {const deps = createMockProcessorDeps();await expect(- processObservationEval({ event: baseEvent, deps }),+ processObservationEval({+ event: baseEvent,+ executionType: EvalTemplateType.LLM_AS_JUDGE,+ deps,+ }),).rejects.toThrow(UnrecoverableError);await expect(- processObservationEval({ event: baseEvent, deps }),+ processObservationEval({+ event: baseEvent,+ executionType: EvalTemplateType.LLM_AS_JUDGE,+ deps,+ }),).rejects.toThrow("Job configuration or template not found");});@@ -130,7 +188,11 @@ describe("processObservationEval", () => {const deps = createMockProcessorDeps();await expect(- processObservationEval({ event: baseEvent, deps }),+ processObservationEval({+ event: baseEvent,+ executionType: EvalTemplateType.LLM_AS_JUDGE,+ deps,+ }),).rejects.toThrow(UnrecoverableError);});@@ -152,7 +214,11 @@ describe("processObservationEval", () => {const deps = createMockProcessorDeps();- await processObservationEval({ event: baseEvent, deps });+ await processObservationEval({+ event: baseEvent,+ executionType: EvalTemplateType.LLM_AS_JUDGE,+ deps,+ });expect(prisma.jobExecution.update).toHaveBeenCalledWith({where: {@@ -165,7 +231,44 @@ describe("processObservationEval", () => {},});expect(deps.downloadObservationFromS3).not.toHaveBeenCalled();- expect(executeLLMAsJudgeEvaluation).not.toHaveBeenCalled();+ expect(runLLMAsJudgeEvaluation).not.toHaveBeenCalled();+ });+ });++ describe("template type filtering", () => {+ it("should throw UnrecoverableError when no template matches the requested execution type", async () => {+ const job = createMockJobExecution({+ id: jobExecutionId,+ projectId,+ status: JobExecutionStatus.PENDING,+ jobConfigurationId: "config-123",+ });++ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);+ (prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(null);++ const deps = createMockProcessorDeps();++ await expect(+ processObservationEval({+ event: baseEvent,+ executionType: EvalTemplateType.LLM_AS_JUDGE,+ deps,+ }),+ ).rejects.toThrow(UnrecoverableError);+ expect(prisma.jobConfiguration.findFirst).toHaveBeenCalledWith(+ expect.objectContaining({+ where: expect.objectContaining({+ evalTemplate: {+ is: {+ type: EvalTemplateType.LLM_AS_JUDGE,+ },+ },+ }),+ }),+ );+ expect(deps.downloadObservationFromS3).not.toHaveBeenCalled();+ expect(runLLMAsJudgeEvaluation).not.toHaveBeenCalled();});it("should cancel inactive evaluators when execution mode is omitted", async () => {@@ -186,7 +289,11 @@ describe("processObservationEval", () => {const deps = createMockProcessorDeps();- await processObservationEval({ event: baseEvent, deps });+ await processObservationEval({+ event: baseEvent,+ executionType: EvalTemplateType.LLM_AS_JUDGE,+ deps,+ });expect(prisma.jobExecution.update).toHaveBeenCalledWith({where: {@@ -199,7 +306,7 @@ describe("processObservationEval", () => {},});expect(deps.downloadObservationFromS3).not.toHaveBeenCalled();- expect(executeLLMAsJudgeEvaluation).not.toHaveBeenCalled();+ expect(runLLMAsJudgeEvaluation).not.toHaveBeenCalled();});it("should execute inactive evaluators for manual execution", async () => {@@ -222,6 +329,7 @@ describe("processObservationEval", () => {await processObservationEval({event: { ...baseEvent, executionMode: "MANUAL" },+ executionType: EvalTemplateType.LLM_AS_JUDGE,deps,});@@ -229,7 +337,7 @@ describe("processObservationEval", () => {expect(deps.downloadObservationFromS3).toHaveBeenCalledWith(observationS3Path,);- expect(executeLLMAsJudgeEvaluation).toHaveBeenCalledWith(+ expect(runLLMAsJudgeEvaluation).toHaveBeenCalledWith(expect.objectContaining({projectId,jobExecutionId,@@ -256,15 +364,19 @@ describe("processObservationEval", () => {(prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);(prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(config);- const deps: ObservationEvalProcessorDeps = {+ const deps = createMockProcessorDeps({downloadObservationFromS3: vi.fn<ObservationEvalProcessorDeps["downloadObservationFromS3"]>().mockRejectedValue(new Error("S3 connection failed")),- };+ });// S3 connection errors should be retryable (not UnrecoverableError)await expect(- processObservationEval({ event: baseEvent, deps }),+ processObservationEval({+ event: baseEvent,+ executionType: EvalTemplateType.LLM_AS_JUDGE,+ deps,+ }),).rejects.toThrow("Failed to download observation from S3");});@@ -283,15 +395,19 @@ describe("processObservationEval", () => {(prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);(prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(config);- const deps: ObservationEvalProcessorDeps = {+ const deps = createMockProcessorDeps({downloadObservationFromS3: vi.fn<ObservationEvalProcessorDeps["downloadObservationFromS3"]>().mockResolvedValue("not valid json {"),- };+ });// Invalid JSON is a permanent error - should be UnrecoverableErrorawait expect(- processObservationEval({ event: baseEvent, deps }),+ processObservationEval({+ event: baseEvent,+ executionType: EvalTemplateType.LLM_AS_JUDGE,+ deps,+ }),).rejects.toThrow(UnrecoverableError);});@@ -312,21 +428,25 @@ describe("processObservationEval", () => {// Missing required fields - valid JSON but invalid schemaconst invalidObservation = { id: "obs-123", someField: "value" };- const deps: ObservationEvalProcessorDeps = {+ const deps = createMockProcessorDeps({downloadObservationFromS3: vi.fn<ObservationEvalProcessorDeps["downloadObservationFromS3"]>().mockResolvedValue(JSON.stringify(invalidObservation)),- };+ });// Schema validation failures are permanent - should be UnrecoverableErrorawait expect(- processObservationEval({ event: baseEvent, deps }),+ processObservationEval({+ event: baseEvent,+ executionType: EvalTemplateType.LLM_AS_JUDGE,+ deps,+ }),).rejects.toThrow(UnrecoverableError);});});describe("successful execution", () => {- it("should call executeLLMAsJudgeEvaluation with correct parameters", async () => {+ it("should call runLLMAsJudgeEvaluation with correct parameters", async () => {const job = createMockJobExecution({id: jobExecutionId,projectId,@@ -353,6 +473,7 @@ describe("processObservationEval", () => {span_id: "obs-xyz",project_id: projectId,trace_id: "trace-abc",+ experiment_id: "experiment-123",environment: "production",output: '{"response": "test output"}',});@@ -366,11 +487,27 @@ describe("processObservationEval", () => {.mockResolvedValue(JSON.stringify(observation)),});- await processObservationEval({ event: baseEvent, deps });+ await processObservationEval({+ event: baseEvent,+ executionType: EvalTemplateType.LLM_AS_JUDGE,+ deps,+ });- expect(executeLLMAsJudgeEvaluation).toHaveBeenCalledWith(+ expect(prisma.jobConfiguration.findFirst).toHaveBeenCalledWith(+ expect.objectContaining({+ where: expect.objectContaining({+ evalTemplate: {+ is: {+ type: EvalTemplateType.LLM_AS_JUDGE,+ },+ },+ }),+ }),+ );+ expect(runLLMAsJudgeEvaluation).toHaveBeenCalledWith(expect.objectContaining({projectId,+ organizationId: "test-org-123",jobExecutionId,job: expect.objectContaining({ id: jobExecutionId }),config: expect.objectContaining({ id: "config-123" }),@@ -381,12 +518,170 @@ describe("processObservationEval", () => {value: '{"response": "test output"}',}),]),- environment: "production",+ hasExperimentContext: true,}),);});- it("should use default environment when observation environment is null", async () => {+ it("should complete eval execution with the executor result", async () => {+ const job = createMockJobExecution({+ id: jobExecutionId,+ projectId,+ status: JobExecutionStatus.PENDING,+ jobConfigurationId: "config-123",+ jobInputTraceId: "trace-abc",+ jobInputObservationId: "obs-xyz",+ });+ const template = createMockEvalTemplate({+ id: "template-456",+ projectId,+ prompt: "Evaluate: {{output}}",+ });+ const config = createMockJobConfiguration({+ id: "config-123",+ projectId,+ evalTemplateId: "template-456",+ variableMapping: [+ { templateVariable: "output", selectedColumnId: "output" },+ ],+ evalTemplate: template,+ });+ const observation = createTestObservation({+ span_id: "obs-xyz",+ project_id: projectId,+ trace_id: "trace-abc",+ environment: "production",+ output: '{"response": "test output"}',+ });++ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);+ (prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(config);++ const uploadScore = vi+ .fn<EvalExecutionDeps["uploadScore"]>()+ .mockResolvedValue(undefined);+ const enqueueScoreIngestion = vi+ .fn<EvalExecutionDeps["enqueueScoreIngestion"]>()+ .mockResolvedValue(undefined);+ const updateJobExecution = vi+ .fn<EvalExecutionDeps["updateJobExecution"]>()+ .mockResolvedValue(undefined);+ const deps = createMockProcessorDeps({+ downloadObservationFromS3: vi+ .fn()+ .mockResolvedValue(JSON.stringify(observation)),+ evalExecutionDeps: createMockEvalExecutionDeps({+ uploadScore,+ enqueueScoreIngestion,+ updateJobExecution,+ }),+ });++ await processObservationEval({+ event: baseEvent,+ executionType: EvalTemplateType.LLM_AS_JUDGE,+ deps,+ });++ expect(uploadScore).toHaveBeenCalledWith(+ expect.objectContaining({+ projectId,+ scoreId: mockScoreId,+ event: expect.objectContaining({+ body: expect.objectContaining({+ environment: "production",+ }),+ }),+ }),+ );+ expect(enqueueScoreIngestion).toHaveBeenCalledWith(+ expect.objectContaining({+ projectId,+ scoreId: mockScoreId,+ }),+ );+ expect(updateJobExecution).toHaveBeenCalledWith({+ id: jobExecutionId,+ projectId,+ data: expect.objectContaining({+ status: JobExecutionStatus.COMPLETED,+ jobOutputScoreId: mockScoreId,+ executionTraceId: mockEvalExecutionResult.executionTraceId,+ }),+ });+ });++ it("should call the code executor for code templates", async () => {+ const job = createMockJobExecution({+ id: jobExecutionId,+ projectId,+ status: JobExecutionStatus.PENDING,+ jobConfigurationId: "config-123",+ jobInputTraceId: "trace-abc",+ jobInputObservationId: "obs-xyz",+ });+ const template = createMockEvalTemplate({+ id: "template-456",+ projectId,+ type: EvalTemplateType.CODE,+ prompt: null,+ outputDefinition: null,+ sourceCode: "def evaluate(): pass",+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.PYTHON,+ });+ const config = createMockJobConfiguration({+ id: "config-123",+ projectId,+ evalTemplateId: "template-456",+ variableMapping: [+ { templateVariable: "output", selectedColumnId: "output" },+ ],+ evalTemplate: template,+ });+ const observation = createTestObservation({+ span_id: "obs-xyz",+ project_id: projectId,+ trace_id: "trace-abc",+ environment: "production",+ output: '{"response": "test output"}',+ });++ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);+ (prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(config);++ const deps = createMockProcessorDeps({+ downloadObservationFromS3: vi+ .fn()+ .mockResolvedValue(JSON.stringify(observation)),+ });++ await processObservationEval({+ event: baseEvent,+ executionType: EvalTemplateType.CODE,+ deps,+ });++ expect(executeCodeBasedEvaluation).toHaveBeenCalledWith(+ expect.objectContaining({+ projectId,+ organizationId: "test-org-123",+ jobExecutionId,+ template: expect.objectContaining({+ id: "template-456",+ type: EvalTemplateType.CODE,+ }),+ extractedVariables: expect.arrayContaining([+ expect.objectContaining({+ var: "output",+ value: '{"response": "test output"}',+ }),+ ]),+ }),+ );+ expect(runLLMAsJudgeEvaluation).not.toHaveBeenCalled();+ });++ it("should use default environment for persisted scores when observation environment is null", async () => {const job = createMockJobExecution({id: jobExecutionId,projectId,@@ -406,17 +701,31 @@ describe("processObservationEval", () => {(prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);(prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(config);+ const uploadScore = vi+ .fn<EvalExecutionDeps["uploadScore"]>()+ .mockResolvedValue(undefined);const deps = createMockProcessorDeps({downloadObservationFromS3: vi.fn().mockResolvedValue(JSON.stringify(observation)),+ evalExecutionDeps: createMockEvalExecutionDeps({+ uploadScore,+ }),});- await processObservationEval({ event: baseEvent, deps });+ await processObservationEval({+ event: baseEvent,+ executionType: EvalTemplateType.LLM_AS_JUDGE,+ deps,+ });- expect(executeLLMAsJudgeEvaluation).toHaveBeenCalledWith(+ expect(uploadScore).toHaveBeenCalledWith(expect.objectContaining({- environment: "default",+ event: expect.objectContaining({+ body: expect.objectContaining({+ environment: "default",+ }),+ }),}),);});@@ -451,9 +760,13 @@ describe("processObservationEval", () => {.mockResolvedValue(JSON.stringify(observation)),});- await processObservationEval({ event: baseEvent, deps });+ await processObservationEval({+ event: baseEvent,+ executionType: EvalTemplateType.LLM_AS_JUDGE,+ deps,+ });- expect(executeLLMAsJudgeEvaluation).toHaveBeenCalledWith(+ expect(runLLMAsJudgeEvaluation).toHaveBeenCalledWith(expect.objectContaining({extractedVariables: expect.arrayContaining([expect.objectContaining({@@ -490,7 +803,10 @@ describe("processObservationEval", () => {// Without injected deps, it will try to use real S3 which should failawait expect(- processObservationEval({ event: baseEvent }),+ processObservationEval({+ event: baseEvent,+ executionType: EvalTemplateType.LLM_AS_JUDGE,+ }),).rejects.toThrow();});});diff --git a/worker/src/features/evaluation/observationEval/__tests__/scheduleObservationEvals.test.ts b/worker/src/features/evaluation/observationEval/__tests__/scheduleObservationEvals.test.tsindex a9a4beb67c..7709240156 100644--- a/worker/src/features/evaluation/observationEval/__tests__/scheduleObservationEvals.test.ts+++ b/worker/src/features/evaluation/observationEval/__tests__/scheduleObservationEvals.test.ts@@ -8,6 +8,7 @@ import {import { type Prisma } from "@langfuse/shared/src/db";import {EvalTargetObject,+ EvalTemplateType,JobConfigState,JobExecutionStatus,} from "@langfuse/shared";@@ -82,6 +83,7 @@ describe("scheduleObservationEvals", () => {filter: [],sampling: { toNumber: () => 1 } as unknown as Prisma.Decimal,evalTemplateId: "template-1",+ evalTemplate: { type: EvalTemplateType.LLM_AS_JUDGE },scoreName: "quality",variableMapping: [],targetObject: EvalTargetObject.EVENT,@@ -375,8 +377,29 @@ describe("scheduleObservationEvals", () => {projectId: "project-789",observationS3Path: "observations/project-789/obs-123.json",delay: 0,+ evalTemplateType: EvalTemplateType.LLM_AS_JUDGE,});});++ it("should pass code template type to the scheduler deps", async () => {+ const schedulerDeps = createMockSchedulerDeps();+ const observation = createMockObservation();+ const config = createMockConfig({+ evalTemplate: { type: EvalTemplateType.CODE },+ });++ await scheduleObservationEvals({+ observation,+ configs: [config],+ schedulerDeps,+ });++ expect(schedulerDeps.enqueueEvalJob).toHaveBeenCalledWith(+ expect.objectContaining({+ evalTemplateType: EvalTemplateType.CODE,+ }),+ );+ });});describe("multiple configs", () => {diff --git a/worker/src/features/evaluation/observationEval/createSchedulerDeps.ts b/worker/src/features/evaluation/observationEval/createSchedulerDeps.tsindex 9d45dfef2c..e3b1fe7a63 100644--- a/worker/src/features/evaluation/observationEval/createSchedulerDeps.ts+++ b/worker/src/features/evaluation/observationEval/createSchedulerDeps.ts@@ -1,5 +1,6 @@-import { prisma } from "@langfuse/shared/src/db";+import { EvalTemplateType, prisma } from "@langfuse/shared/src/db";import {+ CodeEvalExecutionQueue,LLMAsJudgeExecutionQueue,QueueJobs,QueueName,@@ -59,6 +60,34 @@ export function createObservationEvalSchedulerDeps(): ObservationEvalSchedulerDeenqueueEvalJob: async (params) => {const shardingKey = `${params.projectId}-${params.jobExecutionId}`;+ const payload = {+ projectId: params.projectId,+ jobExecutionId: params.jobExecutionId,+ observationS3Path: params.observationS3Path,+ ...(params.executionMode+ ? { executionMode: params.executionMode }+ : {}),+ };++ if (params.evalTemplateType === EvalTemplateType.CODE) {+ const queue = CodeEvalExecutionQueue.getInstance({ shardingKey });+ if (!queue) {+ throw new Error("CodeEvalExecutionQueue is not initialized");+ }++ await queue.add(+ QueueName.CodeEvalExecution,+ {+ name: QueueJobs.CodeEvalExecution,+ id: params.jobExecutionId,+ timestamp: new Date(),+ payload,+ },+ { delay: params.delay },+ );+ return;+ }+const queue = LLMAsJudgeExecutionQueue.getInstance({ shardingKey });if (!queue) {throw new Error("LLMAsJudgeExecutionQueue is not initialized");@@ -70,18 +99,9 @@ export function createObservationEvalSchedulerDeps(): ObservationEvalSchedulerDename: QueueJobs.LLMAsJudgeExecution,id: params.jobExecutionId,timestamp: new Date(),- payload: {- projectId: params.projectId,- jobExecutionId: params.jobExecutionId,- observationS3Path: params.observationS3Path,- ...(params.executionMode- ? { executionMode: params.executionMode }- : {}),- },- },- {- delay: params.delay,+ payload,},+ { delay: params.delay },);},};diff --git a/worker/src/features/evaluation/observationEval/fetchObservationEvalConfigs.ts b/worker/src/features/evaluation/observationEval/fetchObservationEvalConfigs.tsindex fb0cc9edc3..6b12566433 100644--- a/worker/src/features/evaluation/observationEval/fetchObservationEvalConfigs.ts+++ b/worker/src/features/evaluation/observationEval/fetchObservationEvalConfigs.ts@@ -39,6 +39,7 @@ export async function fetchObservationEvalConfigs(},status: JobConfigState.ACTIVE,blockedAt: null,+ evalTemplateId: { not: null },},select: {id: true,@@ -51,6 +52,11 @@ export async function fetchObservationEvalConfigs(blockedAt: true,targetObject: true,variableMapping: true,+ evalTemplate: {+ select: {+ type: true,+ },+ },},});@@ -68,5 +74,16 @@ export async function fetchObservationEvalConfigs(`Found ${configs.length} observation eval configs for project ${projectId}`,);- return configs;+ return configs.map((config) => {+ if (!config.evalTemplate) {+ throw new Error(+ `Observation eval config ${config.id} has no eval template`,+ );+ }++ return {+ ...config,+ evalTemplate: config.evalTemplate,+ };+ });}diff --git a/worker/src/features/evaluation/observationEval/observationEvalProcessor.ts b/worker/src/features/evaluation/observationEval/observationEvalProcessor.tsindex b0de8f7555..650fb77d2f 100644--- a/worker/src/features/evaluation/observationEval/observationEvalProcessor.ts+++ b/worker/src/features/evaluation/observationEval/observationEvalProcessor.ts@@ -1,19 +1,37 @@import { z } from "zod";import {DEFAULT_TRACE_ENVIRONMENT,- LLMAsJudgeExecutionEventSchema,+ ObservationEvalExecutionEventSchema,+ extractObservationVariables,logger,+ type ExtractedVariable,} from "@langfuse/shared/src/server";import {observationForEvalSchema,observationVariableMappingList,+ type EvalTemplateCodeBased,+ type EvalTemplateLlmAsAJudge,isJobConfigExecutableForExecutionMode,type ObservationVariableMapping,} from "@langfuse/shared";+import {+ EvalTemplateType,+ type JobConfiguration,+ type JobExecution,+} from "@prisma/client";import { prisma, JobExecutionStatus } from "@langfuse/shared/src/db";import { UnrecoverableError } from "../../../errors/UnrecoverableError";-import { extractObservationVariables } from "./extractObservationVariables";-import { executeLLMAsJudgeEvaluation } from "../evalService";+import { buildEvalExecutionMetadata } from "../evalRuntime";+import {+ completeEvalExecution,+ type EvalExecutionResult,+} from "../evalCompletion";+import {+ createProductionEvalExecutionDeps,+ type EvalExecutionDeps,+} from "../evalExecutionDeps";+import { runLLMAsJudgeEvaluation } from "../evalService";+import { executeCodeBasedEvaluation } from "../codeBased";import { getEvalS3StorageClient } from "../s3StorageClient";import { type ObservationForEval } from "./types";@@ -21,8 +39,22 @@ import { type ObservationForEval } from "./types";* Dependencies for processing observation evals.* Allows S3 operations to be injected for testability.*/+export type ObservationEvalExecutionBaseParams = {+ projectId: string;+ organizationId: string;+ jobExecutionId: string;+ job: JobExecution;+ config: JobConfiguration;+ extractedVariables: ExtractedVariable[];+ hasExperimentContext: boolean;+ environment: string;+ executionMetadata: Record<string, string>;+ deps: EvalExecutionDeps;+};+export interface ObservationEvalProcessorDeps {downloadObservationFromS3: (path: string) => Promise<string>;+ evalExecutionDeps: EvalExecutionDeps;}/**@@ -35,25 +67,34 @@ export function createObservationEvalProcessorDeps(): ObservationEvalProcessorDereturn s3Client.download(path);},+ evalExecutionDeps: createProductionEvalExecutionDeps(),};}/**- * Processes an observation-level LLM-as-a-judge evaluation job.+ * Processes an observation-level evaluation job.** This function:- * 1. Fetches and validates job execution, config, and template+ * 1. Fetches job execution, config, and the expected template type* 2. Downloads observation data from S3 (stored during scheduling)* 3. Extracts variables from the observation- * 4. Calls the shared executeLLMAsJudgeEvaluation() for LLM call and score persistence+ * 4. Executes the evaluator-specific implementation+ * 5. Completes the eval execution with shared score persistence*/-export async function processObservationEval({- event,- deps = createObservationEvalProcessorDeps(),-}: {- event: z.infer<typeof LLMAsJudgeExecutionEventSchema>;+type ObservationEvalExecutionType =+ | typeof EvalTemplateType.LLM_AS_JUDGE+ | typeof EvalTemplateType.CODE;++type ProcessObservationEvalParams = {+ event: z.infer<typeof ObservationEvalExecutionEventSchema>;+ executionType: ObservationEvalExecutionType;deps?: ObservationEvalProcessorDeps;-}): Promise<void> {+};++export async function processObservationEval(+ params: ProcessObservationEvalParams,+): Promise<void> {+ const { event, deps = createObservationEvalProcessorDeps() } = params;logger.debug(`Processing observation eval job ${event.jobExecutionId} for project ${event.projectId}`,);@@ -90,9 +131,19 @@ export async function processObservationEval({where: {id: job.jobConfigurationId,projectId: event.projectId,+ evalTemplate: {+ is: {+ type: params.executionType,+ },+ },},include: {evalTemplate: true,+ project: {+ select: {+ orgId: true,+ },+ },},});@@ -167,14 +218,50 @@ export async function processObservationEval({`Extracted ${extractedVariables.length} variables for job ${job.id}`,);- // Execute the shared LLM-as-a-judge evaluation- await executeLLMAsJudgeEvaluation({+ const executionParams = {projectId: event.projectId,+ organizationId: evalJobConfig.project.orgId,jobExecutionId: event.jobExecutionId,job,config: evalJobConfig,- template: evalJobConfig.evalTemplate,extractedVariables,+ hasExperimentContext: Boolean(observationData.experiment_id),environment: observationData.environment ?? DEFAULT_TRACE_ENVIRONMENT,+ executionMetadata: buildEvalExecutionMetadata({+ jobExecutionId: event.jobExecutionId,+ jobConfigurationId: job.jobConfigurationId,+ targetTraceId: job.jobInputTraceId,+ targetObservationId: job.jobInputObservationId,+ targetDatasetItemId: job.jobInputDatasetItemId,+ }),+ deps: deps.evalExecutionDeps,+ };++ // The config query filters evalTemplate.type, but Prisma does not narrow the+ // nullable template fields from that relation predicate.+ let executionResult: EvalExecutionResult;+ switch (params.executionType) {+ case EvalTemplateType.LLM_AS_JUDGE:+ executionResult = await runLLMAsJudgeEvaluation({+ ...executionParams,+ template: evalJobConfig.evalTemplate as EvalTemplateLlmAsAJudge,+ });+ break;+ case EvalTemplateType.CODE:+ executionResult = await executeCodeBasedEvaluation({+ ...executionParams,+ template: evalJobConfig.evalTemplate as EvalTemplateCodeBased,+ });+ break;+ }++ await completeEvalExecution({+ projectId: executionParams.projectId,+ jobExecutionId: executionParams.jobExecutionId,+ traceId: executionParams.job.jobInputTraceId,+ observationId: executionParams.job.jobInputObservationId,+ environment: executionParams.environment,+ deps: executionParams.deps,+ result: executionResult,});}diff --git a/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts b/worker/src/features/evaluation/observationEval/scheduleObservationEvals.tsindex 95e5edd1c8..8fef0e1a6e 100644--- a/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts+++ b/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts@@ -153,6 +153,7 @@ async function processMatchingConfig(projectId: observation.project_id,observationS3Path,delay: 0,+ evalTemplateType: matchingConfig.evalTemplate.type,...(executionMode ? { executionMode } : {}),});diff --git a/worker/src/features/evaluation/observationEval/types.ts b/worker/src/features/evaluation/observationEval/types.tsindex 859889bba6..8ca7b9ad7b 100644--- a/worker/src/features/evaluation/observationEval/types.ts+++ b/worker/src/features/evaluation/observationEval/types.ts@@ -1,4 +1,9 @@-import { JobConfiguration, JobExecutionStatus } from "@langfuse/shared/src/db";+import {+ EvalTemplate,+ EvalTemplateType,+ JobConfiguration,+ JobExecutionStatus,+} from "@langfuse/shared/src/db";import { type JobConfigExecutionMode } from "@langfuse/shared";/**@@ -31,7 +36,9 @@ export type ObservationEvalConfig = Pick<| "variableMapping"| "status"| "blockedAt"->;+> & {+ evalTemplate: Pick<EvalTemplate, "type">;+};/*** Dependencies for scheduling observation evals.@@ -62,6 +69,7 @@ export interface ObservationEvalSchedulerDeps {projectId: string;observationS3Path: string;delay: number;+ evalTemplateType: EvalTemplateType;executionMode?: JobConfigExecutionMode;}) => Promise<void>;}diff --git a/worker/src/features/utils/utilities.ts b/worker/src/features/utils/utilities.tsindex 87d277caf2..2e6187756e 100644--- a/worker/src/features/utils/utilities.ts+++ b/worker/src/features/utils/utilities.ts@@ -1,5 +1,6 @@-import crypto from "node:crypto";-import { logger } from "@langfuse/shared/src/server";+import { createW3CTraceId, logger } from "@langfuse/shared/src/server";++export { createW3CTraceId };export function compileTemplateString(template: string,@@ -20,35 +21,6 @@ export function compileTemplateString(}}-/**- * Creates a W3C Trace Context compliant trace ID (16 bytes as 32 hex characters).- *- * @param {string} [seed] - Optional seed string for deterministic trace ID generation.- * If provided, generates a trace ID by hashing the seed with SHA-256.- * If omitted, generates a cryptographically random trace ID.- * @returns {string} A 32-character hexadecimal string representing a 16-byte trace ID.- *- * @example- * // Generate a random trace ID- * const traceId = createW3CTraceId();- * // => "a3f5b2c8d9e1f4a7b6c3d2e5f8a9b4c7"- *- * @example- * // Generate a deterministic trace ID from a seed- * const traceId = createW3CTraceId("my-seed-value");- * // => "5d41402abc4b2a76b9719d911017c592"- */-export function createW3CTraceId(seed?: string): string {- if (seed) {- const data = new TextEncoder().encode(seed);- const hash = crypto.createHash("SHA-256").update(data).digest("hex");-- return hash.slice(0, 32); // take first 32 chars (16 bytes worth)- } else {- return crypto.randomBytes(16).toString("hex"); // already 32 chars- }-}-const MS_PER_DAY = 24 * 60 * 60 * 1000;/**diff --git a/worker/src/queues/__tests__/codeEvalExecutionQueueProcessor.test.ts b/worker/src/queues/__tests__/codeEvalExecutionQueueProcessor.test.tsnew file mode 100644index 0000000000..bc82a04c93--- /dev/null+++ b/worker/src/queues/__tests__/codeEvalExecutionQueueProcessor.test.ts@@ -0,0 +1,272 @@+import {+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+ type Mock,+} from "vitest";+import { Job } from "bullmq";+import { EvalTemplateType } from "@prisma/client";+import { UnrecoverableError } from "../../errors/UnrecoverableError";++const QueueName = {+ CodeEvalExecution: "code-eval-execution-queue",+} as const;++const JobExecutionStatus = {+ ERROR: "ERROR",+} as const;++vi.mock("@langfuse/shared/src/db", () => ({+ prisma: {+ jobExecution: {+ update: vi.fn(),+ },+ },+}));++vi.mock("../../features/evaluation/observationEval", () => ({+ processObservationEval: vi.fn(),+}));++vi.mock("../../features/evaluation/codeBased", () => ({+ executeCodeBasedEvaluation: vi.fn(),+}));++vi.mock("@langfuse/shared/src/server", async (importOriginal) => {+ const actual =+ await importOriginal<typeof import("@langfuse/shared/src/server")>();+ const { CodeEvalExecutionError } =+ await import("../../../../packages/shared/src/server/evals/codeEvalExecution");++ return {+ ...actual,+ CodeEvalExecutionError,+ getCurrentSpan: vi.fn().mockReturnValue({+ setAttribute: vi.fn(),+ }),+ logger: {+ debug: vi.fn(),+ error: vi.fn(),+ },+ QueueName: {+ CodeEvalExecution: "code-eval-execution-queue",+ },+ traceException: vi.fn(),+ };+});++vi.mock("../../features/utils", () => ({+ createW3CTraceId: vi.fn().mockReturnValue("test-trace-id"),+}));++vi.mock("../../errors/UnrecoverableError", async () => {+ const actual = await vi.importActual("../../errors/UnrecoverableError");+ return {+ ...actual,+ isUnrecoverableError: vi.fn(),+ };+});++import { prisma } from "@langfuse/shared/src/db";+import { processObservationEval } from "../../features/evaluation/observationEval";+import { traceException } from "@langfuse/shared/src/server";+import { CodeEvalDispatcherErrorCodes } from "../../../../packages/shared/src/server/evals/codeEvalDispatcherTypes";+import { CodeEvalExecutionError } from "../../../../packages/shared/src/server/evals/codeEvalExecution";+import { isUnrecoverableError } from "../../errors/UnrecoverableError";++describe("codeEvalExecutionQueueProcessor", () => {+ const projectId = "test-project-123";+ const jobExecutionId = "job-exec-456";+ const observationS3Path = "evals/test/observation.json";+ const queueName = `${QueueName.CodeEvalExecution}-1`;+ let codeEvalExecutionQueueProcessor: (job: Job<any>) => Promise<unknown>;++ const createMockJob = (+ overrides: {+ data?: Record<string, unknown>;+ attemptsMade?: number;+ opts?: { attempts?: number };+ } = {},+ ): Job<any> =>+ ({+ data: {+ id: "queue-job-123",+ name: "CodeEvalExecution",+ timestamp: new Date(),+ payload: {+ projectId,+ jobExecutionId,+ observationS3Path,+ },+ retryBaggage: { attempt: 0 },+ ...overrides.data,+ },+ attemptsMade: overrides.attemptsMade ?? 0,+ opts: overrides.opts ?? { attempts: 10 },+ }) as Job<any>;++ beforeAll(async () => {+ const { codeEvalExecutionQueueProcessorBuilder } =+ await import("../codeEvalQueue");+ codeEvalExecutionQueueProcessor =+ codeEvalExecutionQueueProcessorBuilder(queueName);+ });++ beforeEach(() => {+ vi.clearAllMocks();+ (isUnrecoverableError as unknown as Mock).mockReturnValue(false);+ });++ it("should process code observation evals through the code template gate", async () => {+ (processObservationEval as Mock).mockResolvedValue(undefined);++ const result = await codeEvalExecutionQueueProcessor(createMockJob());++ expect(result).toBe(true);+ expect(processObservationEval).toHaveBeenCalledWith({+ event: {+ projectId,+ jobExecutionId,+ observationS3Path,+ },+ executionType: EvalTemplateType.CODE,+ });+ });++ it("should treat unrecoverable code eval errors as terminal", async () => {+ const error = new UnrecoverableError(+ "The evaluator returned an invalid result.",+ );+ (processObservationEval as Mock).mockRejectedValue(error);+ (isUnrecoverableError as unknown as Mock).mockReturnValue(true);++ const result = await codeEvalExecutionQueueProcessor(createMockJob());++ expect(result).toBeUndefined();+ expect(prisma.jobExecution.update).toHaveBeenCalledWith({+ where: { id: jobExecutionId, projectId },+ data: {+ status: JobExecutionStatus.ERROR,+ endTime: expect.any(Date),+ error: "The evaluator returned an invalid result.",+ executionTraceId: "test-trace-id",+ },+ });+ expect(traceException).not.toHaveBeenCalled();+ });++ it("should persist already-masked internal code eval errors", async () => {+ const error = new UnrecoverableError("An internal error occurred");+ (processObservationEval as Mock).mockRejectedValue(error);+ (isUnrecoverableError as unknown as Mock).mockReturnValue(true);++ const result = await codeEvalExecutionQueueProcessor(createMockJob());++ expect(result).toBeUndefined();+ expect(prisma.jobExecution.update).toHaveBeenCalledWith({+ where: { id: jobExecutionId, projectId },+ data: {+ status: JobExecutionStatus.ERROR,+ endTime: expect.any(Date),+ error: "An internal error occurred",+ executionTraceId: "test-trace-id",+ },+ });+ });++ it("should mark unrecoverable skeleton errors as terminal", async () => {+ const error = new UnrecoverableError(+ "Code-based eval execution is not implemented yet",+ );+ (processObservationEval as Mock).mockRejectedValue(error);+ (isUnrecoverableError as unknown as Mock).mockReturnValue(true);++ const result = await codeEvalExecutionQueueProcessor(createMockJob());++ expect(result).toBeUndefined();+ expect(prisma.jobExecution.update).toHaveBeenCalledWith({+ where: {+ id: jobExecutionId,+ projectId,+ },+ data: {+ status: JobExecutionStatus.ERROR,+ endTime: expect.any(Date),+ error: "Code-based eval execution is not implemented yet",+ executionTraceId: "test-trace-id",+ },+ });+ expect(traceException).not.toHaveBeenCalled();+ });++ it("should rethrow retryable errors without writing ERROR while retries remain", async () => {+ const error = new Error("temporary dispatcher failure");+ (processObservationEval as Mock).mockRejectedValue(error);++ await expect(+ codeEvalExecutionQueueProcessor(createMockJob()),+ ).rejects.toThrow(error);++ expect(prisma.jobExecution.update).not.toHaveBeenCalled();+ expect(traceException).toHaveBeenCalledWith(error);+ });++ it("should mark the job as ERROR with a masked message on the final retry attempt", async () => {+ const error = new Error("temporary dispatcher failure");+ (processObservationEval as Mock).mockRejectedValue(error);++ await expect(+ codeEvalExecutionQueueProcessor(+ createMockJob({ attemptsMade: 9, opts: { attempts: 10 } }),+ ),+ ).rejects.toThrow(error);++ expect(prisma.jobExecution.update).toHaveBeenCalledWith({+ where: {+ id: jobExecutionId,+ projectId,+ },+ data: {+ status: JobExecutionStatus.ERROR,+ endTime: expect.any(Date),+ error: "An internal error occurred",+ executionTraceId: "test-trace-id",+ },+ });+ expect(traceException).toHaveBeenCalledWith(error);+ });++ it("should preserve retryable code eval timeout messages on the final retry attempt", async () => {+ const timeoutMessage =+ "Evaluator timed out. Code-based evaluators must complete within the configured runtime limit. Long executions can be caused by network calls, which are forbidden and may never complete. Remove network calls, optimize your evaluator code, and try again. See https://langfuse.com/docs/evaluation/overview for details.";+ const error = new CodeEvalExecutionError({+ code: CodeEvalDispatcherErrorCodes.TIMEOUT,+ message: timeoutMessage,+ retryable: true,+ });+ (processObservationEval as Mock).mockRejectedValue(error);++ await expect(+ codeEvalExecutionQueueProcessor(+ createMockJob({ attemptsMade: 9, opts: { attempts: 10 } }),+ ),+ ).rejects.toThrow(error);++ expect(prisma.jobExecution.update).toHaveBeenCalledWith({+ where: {+ id: jobExecutionId,+ projectId,+ },+ data: {+ status: JobExecutionStatus.ERROR,+ endTime: expect.any(Date),+ error: timeoutMessage,+ executionTraceId: "test-trace-id",+ },+ });+ expect(traceException).toHaveBeenCalledWith(error);+ });+});diff --git a/worker/src/queues/__tests__/llmAsJudgeExecutionQueueProcessor.test.ts b/worker/src/queues/__tests__/llmAsJudgeExecutionQueueProcessor.test.tsindex d8c29ae3ea..04a54f35e2 100644--- a/worker/src/queues/__tests__/llmAsJudgeExecutionQueueProcessor.test.ts+++ b/worker/src/queues/__tests__/llmAsJudgeExecutionQueueProcessor.test.ts@@ -27,6 +27,9 @@ const JobExecutionStatus = {vi.mock("@langfuse/shared", () => ({removeEmptyEnvVariables: <T>(value: T) => value,+ EvalTemplateType: {+ LLM_AS_JUDGE: "LLM_AS_JUDGE",+ },JobExecutionStatus: {DELAYED: "DELAYED",ERROR: "ERROR",@@ -152,8 +155,8 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {beforeEach(() => {vi.clearAllMocks();- (isLLMCompletionError as Mock).mockReturnValue(false);- (isUnrecoverableError as Mock).mockReturnValue(false);+ vi.mocked(isLLMCompletionError).mockReturnValue(false);+ vi.mocked(isUnrecoverableError).mockReturnValue(false);});describe("successful processing", () => {@@ -170,6 +173,7 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {jobExecutionId,observationS3Path,},+ executionType: "LLM_AS_JUDGE",});});@@ -197,7 +201,7 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {it("should schedule retry and set DELAYED status for retryable LLM errors", async () => {const rateLimitError = new Error("Rate limit exceeded");(processObservationEval as Mock).mockRejectedValue(rateLimitError);- (isLLMCompletionError as Mock).mockReturnValue(true);+ vi.mocked(isLLMCompletionError).mockReturnValue(true);// Mark as retryable(rateLimitError as unknown as { isRetryable: boolean }).isRetryable =true;@@ -237,7 +241,7 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {(rateLimitError as unknown as { isRetryable: boolean }).isRetryable =true;(processObservationEval as Mock).mockRejectedValue(rateLimitError);- (isLLMCompletionError as Mock).mockReturnValue(true);+ vi.mocked(isLLMCompletionError).mockReturnValue(true);(retryLLMRateLimitError as Mock).mockResolvedValue({outcome: "scheduled",});@@ -253,7 +257,7 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {it("should set ERROR when retryable LLM errors are not re-enqueued", async () => {const rateLimitError = new Error("Rate limit exceeded");(processObservationEval as Mock).mockRejectedValue(rateLimitError);- (isLLMCompletionError as Mock).mockReturnValue(true);+ vi.mocked(isLLMCompletionError).mockReturnValue(true);(rateLimitError as unknown as { isRetryable: boolean }).isRetryable =true;(retryLLMRateLimitError as Mock).mockResolvedValue({@@ -281,7 +285,7 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {it("should set ERROR when the retry queue is unavailable", async () => {const rateLimitError = new Error("Rate limit exceeded");(processObservationEval as Mock).mockRejectedValue(rateLimitError);- (isLLMCompletionError as Mock).mockReturnValue(true);+ vi.mocked(isLLMCompletionError).mockReturnValue(true);(rateLimitError as unknown as { isRetryable: boolean }).isRetryable =true;(retryLLMRateLimitError as Mock).mockResolvedValue({@@ -311,7 +315,7 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {const llmError = new Error("Invalid API key");(llmError as unknown as { isRetryable: boolean }).isRetryable = false;(processObservationEval as Mock).mockRejectedValue(llmError);- (isLLMCompletionError as Mock).mockReturnValue(true);+ vi.mocked(isLLMCompletionError).mockReturnValue(true);const job = createMockJob();await llmAsJudgeExecutionQueueProcessor(job);@@ -334,7 +338,7 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {const llmError = new Error("Invalid API key");(llmError as unknown as { isRetryable: boolean }).isRetryable = false;(processObservationEval as Mock).mockRejectedValue(llmError);- (isLLMCompletionError as Mock).mockReturnValue(true);+ vi.mocked(isLLMCompletionError).mockReturnValue(true);const job = createMockJob();@@ -351,7 +355,7 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {"Job configuration not found",);(processObservationEval as Mock).mockRejectedValue(unrecoverableError);- (isUnrecoverableError as Mock).mockReturnValue(true);+ vi.mocked(isUnrecoverableError).mockReturnValue(true);const job = createMockJob();await llmAsJudgeExecutionQueueProcessor(job);@@ -373,7 +377,7 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {it("should not rethrow UnrecoverableError", async () => {const unrecoverableError = new UnrecoverableError("Config not found");(processObservationEval as Mock).mockRejectedValue(unrecoverableError);- (isUnrecoverableError as Mock).mockReturnValue(true);+ vi.mocked(isUnrecoverableError).mockReturnValue(true);const job = createMockJob();@@ -386,7 +390,7 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {it("should not call traceException for UnrecoverableError", async () => {const unrecoverableError = new UnrecoverableError("Config not found");(processObservationEval as Mock).mockRejectedValue(unrecoverableError);- (isUnrecoverableError as Mock).mockReturnValue(true);+ vi.mocked(isUnrecoverableError).mockReturnValue(true);const job = createMockJob();await llmAsJudgeExecutionQueueProcessor(job);@@ -451,7 +455,7 @@ describe("llmAsJudgeExecutionQueueProcessor", () => {it("should generate deterministic trace ID from job execution ID", async () => {const error = new UnrecoverableError("Test error");(processObservationEval as Mock).mockRejectedValue(error);- (isUnrecoverableError as Mock).mockReturnValue(true);+ vi.mocked(isUnrecoverableError).mockReturnValue(true);const { createW3CTraceId } = await import("../../features/utils");diff --git a/worker/src/queues/codeEvalQueue.ts b/worker/src/queues/codeEvalQueue.tsnew file mode 100644index 0000000000..31d948ae9e--- /dev/null+++ b/worker/src/queues/codeEvalQueue.ts@@ -0,0 +1,92 @@+import { Job, Processor } from "bullmq";+import { EvalTemplateType, JobExecutionStatus } from "@prisma/client";+import { prisma } from "@langfuse/shared/src/db";+import {+ CodeEvalExecutionError,+ getCodeEvalUserVisibleError,+ getCurrentSpan,+ logger,+ QueueName,+ TQueueJobTypes,+ traceException,+} from "@langfuse/shared/src/server";+import { processObservationEval } from "../features/evaluation/observationEval";+import { createW3CTraceId } from "../features/utils";+import { isUnrecoverableError } from "../errors/UnrecoverableError";++export const codeEvalExecutionQueueProcessorBuilder = (+ _queueName: string,+): Processor => {+ return async (job: Job<TQueueJobTypes[QueueName.CodeEvalExecution]>) => {+ try {+ logger.debug("Executing Code Evaluation Observation Job", job.data);++ const span = getCurrentSpan();++ if (span) {+ span.setAttribute(+ "messaging.bullmq.job.input.jobExecutionId",+ job.data.payload.jobExecutionId,+ );+ span.setAttribute(+ "messaging.bullmq.job.input.projectId",+ job.data.payload.projectId,+ );+ span.setAttribute(+ "messaging.bullmq.job.input.retryBaggage.attempt",+ job.data.retryBaggage?.attempt ?? 0,+ );+ }++ await processObservationEval({+ event: job.data.payload,+ executionType: EvalTemplateType.CODE,+ });++ return true;+ } catch (e) {+ const executionTraceId = createW3CTraceId(+ job.data.payload.jobExecutionId,+ );++ const isTerminalError = isUnrecoverableError(e);+ const totalAttempts = job.opts.attempts ?? 1;+ const isFinalAttempt = job.attemptsMade + 1 >= totalAttempts;++ // Only persist the terminal ERROR state when there will be no more+ // retries; otherwise observationEvalProcessor would short-circuit the+ // retry attempts because it skips jobs already in ERROR status.+ if (isTerminalError || isFinalAttempt) {+ await prisma.jobExecution.update({+ where: {+ id: job.data.payload.jobExecutionId,+ projectId: job.data.payload.projectId,+ },+ data: {+ status: JobExecutionStatus.ERROR,+ endTime: new Date(),+ error: getJobExecutionErrorMessage(e),+ executionTraceId,+ },+ });+ }++ if (isTerminalError) return;++ traceException(e);+ logger.error(+ `Failed code eval execution job for id ${job.data.payload.jobExecutionId}`,+ e,+ );++ throw e;+ }+ };+};++function getJobExecutionErrorMessage(e: unknown): string {+ if (isUnrecoverableError(e)) return e.message;+ if (e instanceof CodeEvalExecutionError) return e.message;++ return getCodeEvalUserVisibleError(e).message;+}diff --git a/worker/src/queues/evalQueue.ts b/worker/src/queues/evalQueue.tsindex 2fd638727b..3e29c49c49 100644--- a/worker/src/queues/evalQueue.ts+++ b/worker/src/queues/evalQueue.ts@@ -1,5 +1,5 @@import { Job, Processor } from "bullmq";-import { JobExecutionStatus } from "@langfuse/shared";+import { EvalTemplateType, JobExecutionStatus } from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";import {QueueName,@@ -296,7 +296,10 @@ export const llmAsJudgeExecutionQueueProcessorBuilder =);}- await processObservationEval({ event: job.data.payload });+ await processObservationEval({+ event: job.data.payload,+ executionType: EvalTemplateType.LLM_AS_JUDGE,+ });return true;} catch (e) {const executionTraceId = createW3CTraceId(diff --git a/worker/src/queues/shardedQueueRegistry.ts b/worker/src/queues/shardedQueueRegistry.tsindex 3405e1c464..894713ace0 100644--- a/worker/src/queues/shardedQueueRegistry.ts+++ b/worker/src/queues/shardedQueueRegistry.ts@@ -11,6 +11,7 @@ import {EvalExecutionQueue,SecondaryEvalExecutionQueue,LLMAsJudgeExecutionQueue,+ CodeEvalExecutionQueue,} from "@langfuse/shared/src/server";export type ShardedQueueDef = {@@ -66,6 +67,12 @@ export const SHARDED_QUEUES: ShardedQueueDef[] = [getInstance: (shard) =>LLMAsJudgeExecutionQueue.getInstance({ shardName: shard }),},+ {+ baseQueueName: QueueName.CodeEvalExecution,+ getShardNames: () => CodeEvalExecutionQueue.getShardNames(),+ getInstance: (shard) =>+ CodeEvalExecutionQueue.getInstance({ shardName: shard }),+ },];export const SHARDED_QUEUE_BASE_NAMES = new Set<QueueName>(@@ -92,6 +99,7 @@ export function resolveQueueInstance(queueName: string): Queue | null {| QueueName.EvaluationExecution| QueueName.EvaluationExecutionSecondaryQueue| QueueName.LLMAsJudgeExecution+ | QueueName.CodeEvalExecution| QueueName.TraceUpsert| QueueName.OtelIngestionQueue| QueueName.OtelIngestionSecondaryQueue