Skip to content

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

feat(web): derive code eval support from dispatcher (#13979)

Tobias Wochinger7cd43cde7c9c
diff --git a/.env.dev.example b/.env.dev.example
index 5f5214f643..9d255c11ae 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -71,9 +71,6 @@ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION="DEV"
# Langfuse experimental features
LANGFUSE_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 hashing
SALT="salt"
diff --git a/.github/workflows/_deploy_ecs_service.yml b/.github/workflows/_deploy_ecs_service.yml
index c618815640..3f1ed15124 100644
--- a/.github/workflows/_deploy_ecs_service.yml
+++ b/.github/workflows/_deploy_ecs_service.yml
@@ -62,7 +62,6 @@ jobs:
VARS_NEXT_PUBLIC_POSTHOG_KEY: ${{ vars.NEXT_PUBLIC_POSTHOG_KEY }}
VARS_NEXT_PUBLIC_POSTHOG_HOST: ${{ vars.NEXT_PUBLIC_POSTHOG_HOST }}
VARS_NEXT_PUBLIC_PLAIN_APP_ID: ${{ vars.NEXT_PUBLIC_PLAIN_APP_ID }}
- VARS_NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED: ${{ vars.NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED }}
VARS_SENTRY_ORG: ${{ vars.SENTRY_ORG }}
VARS_SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT }}
VARS_NEXT_PUBLIC_LANGFUSE_TRACING_SAMPLE_RATE: ${{ vars.NEXT_PUBLIC_LANGFUSE_TRACING_SAMPLE_RATE }}
@@ -81,7 +80,6 @@ jobs:
--build-arg NEXT_PUBLIC_POSTHOG_KEY=${VARS_NEXT_PUBLIC_POSTHOG_KEY} \
--build-arg NEXT_PUBLIC_POSTHOG_HOST=${VARS_NEXT_PUBLIC_POSTHOG_HOST} \
--build-arg NEXT_PUBLIC_PLAIN_APP_ID=${VARS_NEXT_PUBLIC_PLAIN_APP_ID} \
- --build-arg NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED=${VARS_NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED} \
--build-arg SENTRY_AUTH_TOKEN=${SECRETS_SENTRY_AUTH_TOKEN} \
--build-arg SENTRY_ORG=${VARS_SENTRY_ORG} \
--build-arg SENTRY_PROJECT=${VARS_SENTRY_PROJECT} \
diff --git a/docker-compose.build.yml b/docker-compose.build.yml
index feee22b6eb..2eeaa59ce4 100644
--- a/docker-compose.build.yml
+++ b/docker-compose.build.yml
@@ -5,7 +5,6 @@ services:
context: .
args:
- NEXT_PUBLIC_LANGFUSE_CLOUD_REGION=${NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}
- - NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED=${NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED}
depends_on: &langfuse-depends-on
postgres:
condition: service_healthy
diff --git a/turbo.json b/turbo.json
index 16959abf9e..f746df4dd5 100644
--- a/turbo.json
+++ b/turbo.json
@@ -2,10 +2,7 @@
"$schema": "https://turbo.build/schema.json",
"noUpdateNotifier": true,
"globalDependencies": [".env"],
- "globalEnv": [
- "NEXT_PUBLIC_LANGFUSE_BLOB_EXPORT_CUTOFF",
- "NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED"
- ],
+ "globalEnv": ["NEXT_PUBLIC_LANGFUSE_BLOB_EXPORT_CUTOFF"],
"envMode": "loose",
"tasks": {
"build": {
diff --git a/web/Dockerfile b/web/Dockerfile
index e94482548b..6933b5e77c 100644
--- a/web/Dockerfile
+++ b/web/Dockerfile
@@ -59,8 +59,6 @@ ENV NEXT_MANUAL_SIG_HANDLE true
ARG NEXT_PUBLIC_PLAIN_APP_ID
ARG NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
ENV NEXT_PUBLIC_LANGFUSE_CLOUD_REGION=$NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
-ARG NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED
-ENV NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED=$NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED
ARG NEXT_PUBLIC_DEMO_ORG_ID
ENV NEXT_PUBLIC_DEMO_ORG_ID=$NEXT_PUBLIC_DEMO_ORG_ID
ARG NEXT_PUBLIC_DEMO_PROJECT_ID
@@ -122,8 +120,6 @@ ARG NEXT_PUBLIC_BUILD_ID
ENV BUILD_ID=$NEXT_PUBLIC_BUILD_ID
ARG NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
ENV NEXT_PUBLIC_LANGFUSE_CLOUD_REGION=$NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
-ARG NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED
-ENV NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED=$NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED
ENV NODE_ENV production
# Uncomment the following line in case you want to disable telemetry during runtime.
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.ts
index 22ea63330f..8dfe35888b 100644
--- a/web/src/__tests__/server/code-eval-test-run-trpc.servertest.ts
+++ b/web/src/__tests__/server/code-eval-test-run-trpc.servertest.ts
@@ -1,5 +1,24 @@
import { randomUUID } from "node:crypto";
import { describe, expect, it, afterAll, vi } from "vitest";
+import type * as SharedEnvModule from "@langfuse/shared/src/env";
+
+vi.hoisted(() => {
+ process.env.LANGFUSE_CODE_EVAL_DISPATCHER = "insecure-local";
+});
+
+vi.mock("@langfuse/shared/src/env", async (importOriginal) => {
+ const actual = await importOriginal<typeof SharedEnvModule>();
+
+ return {
+ ...actual,
+ env: {
+ ...actual.env,
+ LANGFUSE_CODE_EVAL_DISPATCHER: "insecure-local",
+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: undefined,
+ },
+ };
+});
+
import type { Session } from "next-auth";
import {
EvalTemplateSourceCodeLanguage,
@@ -21,11 +40,6 @@ import {
} from "@langfuse/shared/src/server";
import { EvalTargetObject } from "@langfuse/shared";
-vi.hoisted(() => {
- process.env.NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED = "true";
- process.env.LANGFUSE_CODE_EVAL_DISPATCHER = "insecure-local";
-});
-
const orgIds: string[] = [];
const maybe =
@@ -70,6 +84,8 @@ async function prepare() {
v4BetaToggleVisible: false,
observationEvals: false,
experimentsV4Enabled: false,
+ monitors: false,
+ inAppAgent: false,
},
admin: true,
},
@@ -602,9 +618,51 @@ maybe("evals.testRunCodeEval", () => {
}),
).rejects.toThrow(/Evaluator template not found/);
});
+
+ it("rejects Python templates for the insecure-local dispatcher", async () => {
+ const { project, caller } = await prepare();
+ const observationId = randomUUID();
+ const traceId = randomUUID();
+ const startTime = new Date();
+
+ const template = await createCodeTemplate(
+ project.id,
+ 'def evaluate(ctx):\n return { "scores": [{ "name": "python-score", "value": 1 }] }',
+ EvalTemplateSourceCodeLanguage.PYTHON,
+ );
+
+ await createEventsCh([
+ createEvent({
+ project_id: project.id,
+ trace_id: traceId,
+ span_id: observationId,
+ id: observationId,
+ start_time: startTime.getTime() * 1000,
+ }),
+ ]);
+
+ await expect(
+ caller.evals.testRunCodeEval({
+ projectId: project.id,
+ evalTemplateId: template.id,
+ target: EvalTargetObject.EVENT,
+ scoreName: "unsaved-score",
+ observationId,
+ traceId,
+ startTime,
+ mapping: [],
+ }),
+ ).rejects.toThrow(
+ "This code evaluator language is not supported by the configured dispatcher.",
+ );
+ });
});
-async function createCodeTemplate(projectId: string, sourceCode?: string) {
+async function createCodeTemplate(
+ projectId: string,
+ sourceCode?: string,
+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage = EvalTemplateSourceCodeLanguage.TYPESCRIPT,
+) {
return prisma.evalTemplate.create({
data: {
projectId,
@@ -616,7 +674,7 @@ async function createCodeTemplate(projectId: string, sourceCode?: string) {
sourceCode:
sourceCode ??
'function evaluate() { return { scores: [{ name: "test-score", value: 1 }] }; }',
- sourceCodeLanguage: EvalTemplateSourceCodeLanguage.TYPESCRIPT,
+ sourceCodeLanguage,
},
});
}
diff --git a/web/src/__tests__/server/evals-trpc.servertest.ts b/web/src/__tests__/server/evals-trpc.servertest.ts
index c07b0bca92..a7a6a2d195 100644
--- a/web/src/__tests__/server/evals-trpc.servertest.ts
+++ b/web/src/__tests__/server/evals-trpc.servertest.ts
@@ -1,3 +1,33 @@
+import { beforeEach, vi } from "vitest";
+import type * as SharedEnvModule from "@langfuse/shared/src/env";
+
+const { runCodeEvalTestForJobConfigMock } = vi.hoisted(() => {
+ process.env.LANGFUSE_CODE_EVAL_DISPATCHER = "insecure-local";
+ process.env.LANGFUSE_ENABLE_EVENTS_TABLE_UI = "true";
+
+ return {
+ runCodeEvalTestForJobConfigMock: vi.fn(),
+ };
+});
+
+vi.mock("@langfuse/shared/src/env", async (importOriginal) => {
+ const actual = await importOriginal<typeof SharedEnvModule>();
+
+ return {
+ ...actual,
+ env: {
+ ...actual.env,
+ LANGFUSE_CODE_EVAL_DISPATCHER: "insecure-local",
+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: undefined,
+ },
+ };
+});
+
+vi.mock("@/src/features/evals/server/codeEvalTestRun", () => ({
+ runCodeEvalTest: vi.fn(),
+ runCodeEvalTestForJobConfig: runCodeEvalTestForJobConfigMock,
+}));
+
import { appRouter } from "@/src/server/api/root";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
import {
@@ -14,21 +44,6 @@ import {
EvaluatorBlockReason,
} from "@langfuse/shared";
import type { Session } from "next-auth";
-import { beforeEach, vi } from "vitest";
-
-const { runCodeEvalTestForJobConfigMock } = vi.hoisted(() => {
- process.env.NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED = "true";
- process.env.LANGFUSE_ENABLE_EVENTS_TABLE_UI = "true";
-
- return {
- runCodeEvalTestForJobConfigMock: vi.fn(),
- };
-});
-
-vi.mock("@/src/features/evals/server/codeEvalTestRun", () => ({
- runCodeEvalTest: vi.fn(),
- runCodeEvalTestForJobConfig: runCodeEvalTestForJobConfigMock,
-}));
beforeEach(() => {
runCodeEvalTestForJobConfigMock.mockReset();
@@ -430,6 +445,25 @@ describe("evals trpc", () => {
});
});
+ describe("evals.createTemplate", () => {
+ it("rejects Python code evaluators for the insecure-local dispatcher", async () => {
+ const { project, caller } = await prepare();
+
+ await expect(
+ caller.evals.createTemplate({
+ projectId: project.id,
+ name: `python-code-template-${project.id}`,
+ type: EvalTemplateType.CODE,
+ sourceCode:
+ 'def evaluate(ctx):\n return { "scores": [{ "name": "python-score", "value": 1 }] }',
+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.PYTHON,
+ }),
+ ).rejects.toThrow(
+ "This code evaluator language is not supported by the configured dispatcher.",
+ );
+ });
+ });
+
describe("evals.createJob", () => {
it("saves experiment code evaluator configs without a matching observation", async () => {
const { project, caller } = await prepare();
diff --git a/web/src/__tests__/server/unit/code-eval-capabilities.servertest.ts b/web/src/__tests__/server/unit/code-eval-capabilities.servertest.ts
new file mode 100644
index 0000000000..3b1e67aaf0
--- /dev/null
+++ b/web/src/__tests__/server/unit/code-eval-capabilities.servertest.ts
@@ -0,0 +1,81 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const originalEnv = { ...process.env };
+
+async function getCapabilitiesForEnv(
+ overrides: Record<string, string | undefined>,
+) {
+ vi.resetModules();
+
+ process.env = { ...originalEnv };
+ delete process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+ delete process.env.LANGFUSE_CODE_EVAL_DISPATCHER;
+
+ for (const [key, value] of Object.entries(overrides)) {
+ if (value === undefined) {
+ delete process.env[key];
+ } else {
+ process.env[key] = value;
+ }
+ }
+
+ const { getCodeEvalCapabilities } =
+ await import("@/src/features/evals/server/isCodeEvalEnabled");
+
+ return getCodeEvalCapabilities();
+}
+
+afterEach(() => {
+ vi.resetModules();
+ process.env = { ...originalEnv };
+});
+
+describe("getCodeEvalCapabilities", () => {
+ it("enables TypeScript and Python on cloud deployments", async () => {
+ await expect(
+ getCapabilitiesForEnv({ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: "US" }),
+ ).resolves.toEqual({
+ enabled: true,
+ supportedSourceCodeLanguages: ["TYPESCRIPT", "PYTHON"],
+ });
+ });
+
+ it("disables code evals for self-hosted deployments without a dispatcher", async () => {
+ await expect(getCapabilitiesForEnv({})).resolves.toEqual({
+ enabled: false,
+ supportedSourceCodeLanguages: [],
+ });
+ });
+
+ it("treats an empty cloud region as self-hosted", async () => {
+ await expect(
+ getCapabilitiesForEnv({
+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: "",
+ LANGFUSE_CODE_EVAL_DISPATCHER: "insecure-local",
+ }),
+ ).resolves.toEqual({
+ enabled: true,
+ supportedSourceCodeLanguages: ["TYPESCRIPT"],
+ });
+ });
+
+ it("enables TypeScript and Python for self-hosted aws-lambda dispatching", async () => {
+ await expect(
+ getCapabilitiesForEnv({ LANGFUSE_CODE_EVAL_DISPATCHER: "aws-lambda" }),
+ ).resolves.toEqual({
+ enabled: true,
+ supportedSourceCodeLanguages: ["TYPESCRIPT", "PYTHON"],
+ });
+ });
+
+ it("enables only TypeScript for self-hosted insecure-local dispatching", async () => {
+ await expect(
+ getCapabilitiesForEnv({
+ LANGFUSE_CODE_EVAL_DISPATCHER: "insecure-local",
+ }),
+ ).resolves.toEqual({
+ enabled: true,
+ supportedSourceCodeLanguages: ["TYPESCRIPT"],
+ });
+ });
+});
diff --git a/web/src/components/onboarding/EvaluatorsOnboarding.tsx b/web/src/components/onboarding/EvaluatorsOnboarding.tsx
index 81b4b56591..6e65b3c941 100644
--- a/web/src/components/onboarding/EvaluatorsOnboarding.tsx
+++ b/web/src/components/onboarding/EvaluatorsOnboarding.tsx
@@ -5,13 +5,18 @@ import {
} from "@/src/components/ui/splash-screen";
import { Bot, Gauge, Zap, BarChart4, Code2 } from "lucide-react";
import { useIsCodeEvalEnabled } from "@/src/features/evals/hooks/useIsCodeEvalEnabled";
+import { EvalTemplateSourceCodeLanguage } from "@langfuse/shared";
interface EvaluatorsOnboardingProps {
projectId: string;
}
export function EvaluatorsOnboarding({ projectId }: EvaluatorsOnboardingProps) {
- const { enabled } = useIsCodeEvalEnabled();
+ const { enabled, supportedSourceCodeLanguages } = useIsCodeEvalEnabled();
+ const codeEvaluatorLanguageDescription =
+ supportedSourceCodeLanguages.includes(EvalTemplateSourceCodeLanguage.PYTHON)
+ ? "TypeScript or Python"
+ : "TypeScript";
const llmAsJudgeValuePropositions: ValueProposition[] = [
{
@@ -50,8 +55,7 @@ export function EvaluatorsOnboarding({ projectId }: EvaluatorsOnboardingProps) {
},
{
title: "Code evaluators",
- description:
- "Write TypeScript or Python logic for deterministic, custom scoring.",
+ description: `Write ${codeEvaluatorLanguageDescription} logic for deterministic, custom scoring.`,
icon: <Code2 className="h-4 w-4" />,
},
];
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 3127cef1fe..fa3c401cdc 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -490,11 +490,6 @@ 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"),
},
/**
@@ -783,9 +778,6 @@ export const env = createEnv({
// Playground
NEXT_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 License
LANGFUSE_EE_LICENSE_KEY: process.env.LANGFUSE_EE_LICENSE_KEY,
ADMIN_API_KEY: process.env.ADMIN_API_KEY,
diff --git a/web/src/features/evals/components/eval-template-type-selector.tsx b/web/src/features/evals/components/eval-template-type-selector.tsx
index 98d1b03026..7c2abc7a65 100644
--- a/web/src/features/evals/components/eval-template-type-selector.tsx
+++ b/web/src/features/evals/components/eval-template-type-selector.tsx
@@ -28,18 +28,22 @@ type EvalTemplateFormReturn = UseFormReturn<
EvalTemplateFormOutput
>;
type CodeEvalSourceDrafts = Partial<Record<CodeEvalSourceCodeLanguage, string>>;
+type CodeEvalCapabilities = {
+ enabled: boolean;
+ supportedSourceCodeLanguages: EvalTemplateSourceCodeLanguage[];
+};
export type EvalTemplateTypeSelectorMode = "all" | "code-only" | "hidden";
export function EvalTemplateTypeSelector({
form,
- enabled,
+ codeEvalCapabilities,
mode,
hasExistingTemplate,
onChange,
}: {
form: EvalTemplateFormReturn;
- enabled: boolean;
+ codeEvalCapabilities: CodeEvalCapabilities;
mode: EvalTemplateTypeSelectorMode;
hasExistingTemplate: boolean;
onChange?: () => void;
@@ -49,7 +53,8 @@ export function EvalTemplateTypeSelector({
const sourceCodeLanguage =
form.watch("sourceCodeLanguage") ??
EvalTemplateSourceCodeLanguage.TYPESCRIPT;
- const shouldShow = enabled && !hasExistingTemplate && mode !== "hidden";
+ const shouldShow =
+ codeEvalCapabilities.enabled && !hasExistingTemplate && mode !== "hidden";
if (!shouldShow) return null;
@@ -123,12 +128,16 @@ export function EvalTemplateTypeSelector({
>
TypeScript
</TabsTrigger>
- <TabsTrigger
- value={EvalTemplateSourceCodeLanguage.PYTHON}
- className="min-w-[100px]"
- >
- Python
- </TabsTrigger>
+ {codeEvalCapabilities.supportedSourceCodeLanguages.includes(
+ EvalTemplateSourceCodeLanguage.PYTHON,
+ ) ? (
+ <TabsTrigger
+ value={EvalTemplateSourceCodeLanguage.PYTHON}
+ className="min-w-[100px]"
+ >
+ Python
+ </TabsTrigger>
+ ) : null}
</TabsList>
</Tabs>
</FormControl>
diff --git a/web/src/features/evals/components/eval-templates-table.tsx b/web/src/features/evals/components/eval-templates-table.tsx
index 373ffba4a3..3d3d66a7f3 100644
--- a/web/src/features/evals/components/eval-templates-table.tsx
+++ b/web/src/features/evals/components/eval-templates-table.tsx
@@ -29,7 +29,10 @@ import { showSuccessToast } from "@/src/features/notifications/showSuccessToast"
import { EvalReferencedEvaluators } from "@/src/features/evals/types";
import { showErrorToast } from "@/src/features/notifications/showErrorToast";
import { type RouterInput } from "@/src/utils/types";
-import { useSingleTemplateValidation } from "@/src/features/evals/hooks/useSingleTemplateValidation";
+import {
+ type TemplateValidationInput,
+ useSingleTemplateValidation,
+} from "@/src/features/evals/hooks/useSingleTemplateValidation";
import { getMaintainer } from "@/src/features/evals/utils/typeHelpers";
import { MaintainerTooltip } from "@/src/features/evals/components/maintainer-tooltip";
import { ActionButton } from "@/src/components/ActionButton";
@@ -58,11 +61,7 @@ export type EvalsTemplateRow = {
id?: string;
usageCount?: number;
actions?: string;
- provider?: string;
- model?: string;
- type?: EvalTemplateType;
- sourceCodeLanguage?: EvalTemplate["sourceCodeLanguage"];
-};
+} & TemplateValidationInput;
const getMaintainerLabel = (maintainer: string) =>
maintainer.replace(/ maintained$/, "");
@@ -119,7 +118,9 @@ export default function EvalsTemplateTable({
projectId: string;
}) {
const router = useRouter();
- const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();
+ const codeEvalCapabilities = useIsCodeEvalEnabled();
+ const { enabled: isCodeEvalEnabled, supportedSourceCodeLanguages } =
+ codeEvalCapabilities;
const { setDetailPageList } = useDetailPageLists();
const [paginationState, setPaginationState] = usePaginationState(0, 50, {
page: "pageIndex",
@@ -216,13 +217,21 @@ export default function EvalsTemplateTable({
"eval-templates",
templateList
.filter((template) =>
- shouldShowEvalTemplate(template, isCodeEvalEnabled),
+ shouldShowEvalTemplate(template, {
+ enabled: isCodeEvalEnabled,
+ supportedSourceCodeLanguages,
+ }),
)
.map((template) => ({ id: template.latestId })),
);
}
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [templates.isSuccess, templates.data, isCodeEvalEnabled]);
+ }, [
+ templates.isSuccess,
+ templates.data,
+ isCodeEvalEnabled,
+ supportedSourceCodeLanguages,
+ setDetailPageList,
+ ]);
const columnHelper = createColumnHelper<EvalsTemplateRow>();
@@ -318,11 +327,8 @@ export default function EvalsTemplateTable({
size: 100,
cell: ({ row }) => {
const id = row.original.id;
- const provider = row.original.provider ?? null;
- const model = row.original.model ?? null;
- const type = row.original.type;
- const isInvalid = isTemplateInvalid({ provider, model, type });
- const isCodeTemplate = type === EvalTemplateType.CODE;
+ const isInvalid = isTemplateInvalid(row.original);
+ const isCodeTemplate = row.original.type === EvalTemplateType.CODE;
const isUserMaintained = row.original.maintainer.includes("User");
return (
@@ -427,8 +433,8 @@ export default function EvalsTemplateTable({
latestVersion: template.version,
id: template.latestId,
usageCount: template.usageCount,
- provider: template.provider,
- model: template.model,
+ provider: template.provider ?? null,
+ model: template.model ?? null,
type: template.type,
sourceCodeLanguage: template.sourceCodeLanguage,
};
@@ -471,7 +477,10 @@ export default function EvalsTemplateTable({
isError: false,
data: safeExtract(templates.data, "templates", [])
.filter((template) =>
- shouldShowEvalTemplate(template, isCodeEvalEnabled),
+ shouldShowEvalTemplate(
+ template,
+ codeEvalCapabilities,
+ ),
)
.map((t) => convertToTableRow(t)),
}
diff --git a/web/src/features/evals/components/evaluator-form.tsx b/web/src/features/evals/components/evaluator-form.tsx
index fe9ce0d992..4903a4fd11 100644
--- a/web/src/features/evals/components/evaluator-form.tsx
+++ b/web/src/features/evals/components/evaluator-form.tsx
@@ -27,12 +27,14 @@ export const EvaluatorForm = (props: {
hidePreviewTable?: boolean;
defaultTarget?: EvalTargetObject;
}) => {
- const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();
+ const codeEvalCapabilities = useIsCodeEvalEnabled();
const currentTemplate =
props.existingEvaluator?.evalTemplate ??
props.evalTemplates
- .filter((template) => shouldShowEvalTemplate(template, isCodeEvalEnabled))
+ .filter((template) =>
+ shouldShowEvalTemplate(template, codeEvalCapabilities),
+ )
.find((t) => t.id === props.templateId);
const evalCapabilities = useEvalCapabilities(props.projectId, {
@@ -42,7 +44,8 @@ export const EvaluatorForm = (props: {
if (
!currentTemplate ||
- (isCodeEvalTemplate(currentTemplate) && !isCodeEvalEnabled)
+ (isCodeEvalTemplate(currentTemplate) &&
+ !shouldShowEvalTemplate(currentTemplate, codeEvalCapabilities))
) {
return null;
}
diff --git a/web/src/features/evals/components/evaluator-selector.tsx b/web/src/features/evals/components/evaluator-selector.tsx
index 1117d89522..01cbf655fe 100644
--- a/web/src/features/evals/components/evaluator-selector.tsx
+++ b/web/src/features/evals/components/evaluator-selector.tsx
@@ -115,9 +115,9 @@ export function EvaluatorSelector({
onTemplateSelect,
}: EvaluatorSelectorProps) {
const [search, setSearch] = useState("");
- const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();
+ const codeEvalCapabilities = useIsCodeEvalEnabled();
const visibleEvalTemplates = evalTemplates.filter((template) =>
- shouldShowEvalTemplate(template, isCodeEvalEnabled),
+ shouldShowEvalTemplate(template, codeEvalCapabilities),
);
// Group templates by name and whether they are managed by Langfuse
diff --git a/web/src/features/evals/components/select-evaluator-list.tsx b/web/src/features/evals/components/select-evaluator-list.tsx
index 996236972f..7cb229bbad 100644
--- a/web/src/features/evals/components/select-evaluator-list.tsx
+++ b/web/src/features/evals/components/select-evaluator-list.tsx
@@ -35,7 +35,8 @@ export function SelectEvaluatorList({ projectId }: SelectEvaluatorListProps) {
const [customEvaluatorType, setCustomEvaluatorType] = useState<
typeof EvalTemplateType.LLM_AS_JUDGE | typeof EvalTemplateType.CODE | null
>(null);
- const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();
+ const codeEvalCapabilities = useIsCodeEvalEnabled();
+ const { enabled: isCodeEvalEnabled } = codeEvalCapabilities;
const handleSelectEvaluator = (template: EvalTemplate) => {
router.push(`/project/${projectId}/evals/new?evaluator=${template.id}`);
@@ -90,7 +91,7 @@ export function SelectEvaluatorList({ projectId }: SelectEvaluatorListProps) {
<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.
+ Use code to create Langfuse scores.
</span>
</span>
</Button>
diff --git a/web/src/features/evals/components/template-form.tsx b/web/src/features/evals/components/template-form.tsx
index b046f6d6d6..daad6c2d7b 100644
--- a/web/src/features/evals/components/template-form.tsx
+++ b/web/src/features/evals/components/template-form.tsx
@@ -206,7 +206,8 @@ export const InnerEvalTemplateForm = (props: {
}) => {
const capture = usePostHogClientCapture();
const [formError, setFormError] = useState<string | null>(null);
- const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();
+ const codeEvalCapabilities = useIsCodeEvalEnabled();
+ const { enabled: isCodeEvalEnabled } = codeEvalCapabilities;
const templateTypeSelectorMode = props.templateTypeSelectorMode ?? "all";
// Determine if we should use default model or custom model
@@ -558,7 +559,7 @@ export const InnerEvalTemplateForm = (props: {
<EvalTemplateTypeSelector
form={form}
- enabled={isCodeEvalEnabled}
+ codeEvalCapabilities={codeEvalCapabilities}
mode={templateTypeSelectorMode}
hasExistingTemplate={Boolean(props.existingEvalTemplateId)}
onChange={() => {
diff --git a/web/src/features/evals/components/template-selector.tsx b/web/src/features/evals/components/template-selector.tsx
index 46c9e5e423..e3472a53c3 100644
--- a/web/src/features/evals/components/template-selector.tsx
+++ b/web/src/features/evals/components/template-selector.tsx
@@ -70,9 +70,9 @@ export const TemplateSelector = ({
}: TemplateSelectorProps) => {
const [isPopoverOpen, setIsPopoverOpen] = useState(false);
const [search, setSearch] = useState("");
- const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();
+ const codeEvalCapabilities = useIsCodeEvalEnabled();
const visibleEvalTemplates = evalTemplates.filter((template) =>
- shouldShowEvalTemplate(template, isCodeEvalEnabled),
+ shouldShowEvalTemplate(template, codeEvalCapabilities),
);
const {
activeTemplates,
diff --git a/web/src/features/evals/hooks/useIsCodeEvalEnabled.ts b/web/src/features/evals/hooks/useIsCodeEvalEnabled.ts
index ca05e70444..488cd8149d 100644
--- a/web/src/features/evals/hooks/useIsCodeEvalEnabled.ts
+++ b/web/src/features/evals/hooks/useIsCodeEvalEnabled.ts
@@ -1,7 +1,37 @@
-import { isCodeEvalEnabled } from "@/src/features/evals/server/isCodeEvalEnabled";
+import { EvalTemplateSourceCodeLanguage } from "@langfuse/shared";
+import { env } from "@/src/env.mjs";
+import { api } from "@/src/utils/api";
+
+const EMPTY_SUPPORTED_SOURCE_CODE_LANGUAGES: EvalTemplateSourceCodeLanguage[] =
+ [];
+const CLOUD_SUPPORTED_SOURCE_CODE_LANGUAGES = [
+ EvalTemplateSourceCodeLanguage.TYPESCRIPT,
+ EvalTemplateSourceCodeLanguage.PYTHON,
+] satisfies EvalTemplateSourceCodeLanguage[];
+
+export function useIsCodeEvalEnabled(): {
+ enabled: boolean;
+ supportedSourceCodeLanguages: EvalTemplateSourceCodeLanguage[];
+ isLoading: boolean;
+} {
+ if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
+ return {
+ enabled: true,
+ supportedSourceCodeLanguages: CLOUD_SUPPORTED_SOURCE_CODE_LANGUAGES,
+ isLoading: false,
+ };
+ }
+
+ const capabilities = api.evals.codeEvalCapabilities.useQuery(undefined, {
+ staleTime: Infinity,
+ });
+ const supportedSourceCodeLanguages =
+ capabilities.data?.supportedSourceCodeLanguages ??
+ EMPTY_SUPPORTED_SOURCE_CODE_LANGUAGES;
-export function useIsCodeEvalEnabled(): { enabled: boolean } {
return {
- enabled: isCodeEvalEnabled(),
+ enabled: capabilities.data?.enabled ?? false,
+ supportedSourceCodeLanguages,
+ isLoading: capabilities.isLoading,
};
}
diff --git a/web/src/features/evals/hooks/useSingleTemplateValidation.ts b/web/src/features/evals/hooks/useSingleTemplateValidation.ts
index 4448204fbe..eb932a5788 100644
--- a/web/src/features/evals/hooks/useSingleTemplateValidation.ts
+++ b/web/src/features/evals/hooks/useSingleTemplateValidation.ts
@@ -1,30 +1,38 @@
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";
+import {
+ isCodeEvalTemplate,
+ shouldShowEvalTemplate,
+} from "@/src/features/evals/utils/code-eval-template-utils";
+
+export type TemplateValidationInput = Pick<
+ EvalTemplate,
+ "provider" | "model" | "type" | "sourceCodeLanguage"
+>;
export function useSingleTemplateValidation({
projectId,
}: {
projectId: string;
}) {
- const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();
+ const codeEvalCapabilities = useIsCodeEvalEnabled();
const { data: defaultModel } = api.defaultLlmModel.fetchDefaultModel.useQuery(
{ projectId },
);
const templateRequiresDefaultModel = (
- template: Partial<Pick<EvalTemplate, "provider" | "model" | "type">>,
+ template: Pick<TemplateValidationInput, "provider" | "model" | "type">,
): boolean => {
if (isCodeEvalTemplate(template)) return false;
return !template.provider || !template.model;
};
- const isTemplateInvalid = (
- template: Partial<Pick<EvalTemplate, "provider" | "model" | "type">>,
- ): boolean => {
- if (isCodeEvalTemplate(template)) return !isCodeEvalEnabled;
+ const isTemplateInvalid = (template: TemplateValidationInput): boolean => {
+ if (isCodeEvalTemplate(template)) {
+ return !shouldShowEvalTemplate(template, codeEvalCapabilities);
+ }
return templateRequiresDefaultModel(template) && !defaultModel;
};
diff --git a/web/src/features/evals/hooks/useTemplateValidation.ts b/web/src/features/evals/hooks/useTemplateValidation.ts
index 939cb13ed6..9943d8bb3d 100644
--- a/web/src/features/evals/hooks/useTemplateValidation.ts
+++ b/web/src/features/evals/hooks/useTemplateValidation.ts
@@ -3,7 +3,10 @@ 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";
+import {
+ isCodeEvalTemplate,
+ shouldShowEvalTemplate,
+} from "@/src/features/evals/utils/code-eval-template-utils";
export function useTemplateValidation({
projectId,
@@ -12,7 +15,7 @@ export function useTemplateValidation({
projectId: string;
onValidSelection?: (template: EvalTemplate) => void;
}) {
- const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();
+ const codeEvalCapabilities = useIsCodeEvalEnabled();
const [selectedTemplate, setSelectedTemplate] = useState<EvalTemplate | null>(
null,
);
@@ -26,8 +29,12 @@ export function useTemplateValidation({
useEffect(() => {
if (selectedTemplate) {
if (isCodeEvalTemplate(selectedTemplate)) {
- setIsSelectionValid(isCodeEvalEnabled);
- if (isCodeEvalEnabled) {
+ const isCodeEvalTemplateAvailable = shouldShowEvalTemplate(
+ selectedTemplate,
+ codeEvalCapabilities,
+ );
+ setIsSelectionValid(isCodeEvalTemplateAvailable);
+ if (isCodeEvalTemplateAvailable) {
onValidSelection?.(selectedTemplate);
}
return;
@@ -48,7 +55,7 @@ export function useTemplateValidation({
onValidSelection?.(selectedTemplate);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [selectedTemplate?.id, onValidSelection, isCodeEvalEnabled]);
+ }, [selectedTemplate?.id, onValidSelection, codeEvalCapabilities.enabled]);
return { isSelectionValid, selectedTemplate, setSelectedTemplate };
}
diff --git a/web/src/features/evals/hooks/useTemplatesValidation.ts b/web/src/features/evals/hooks/useTemplatesValidation.ts
index f161c0c5c9..decd7e3ead 100644
--- a/web/src/features/evals/hooks/useTemplatesValidation.ts
+++ b/web/src/features/evals/hooks/useTemplatesValidation.ts
@@ -1,7 +1,10 @@
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";
+import {
+ isCodeEvalTemplate,
+ shouldShowEvalTemplate,
+} from "@/src/features/evals/utils/code-eval-template-utils";
export function useTemplatesValidation({
projectId,
@@ -11,7 +14,9 @@ export function useTemplatesValidation({
selectedTemplateIds?: string[];
}) {
const [isSelectionValid, setIsSelectionValid] = useState(true);
- const { enabled: isCodeEvalEnabled } = useIsCodeEvalEnabled();
+ const codeEvalCapabilities = useIsCodeEvalEnabled();
+ const { enabled: isCodeEvalEnabled, supportedSourceCodeLanguages } =
+ codeEvalCapabilities;
// Fetch default model
const { data: defaultModel, isLoading: isLoadingDefaultModel } =
@@ -36,7 +41,11 @@ export function useTemplatesValidation({
if (
selectedTemplates.some(
- (template) => isCodeEvalTemplate(template) && !isCodeEvalEnabled,
+ (template) =>
+ !shouldShowEvalTemplate(template, {
+ enabled: isCodeEvalEnabled,
+ supportedSourceCodeLanguages,
+ }),
)
) {
setIsSelectionValid(false);
@@ -60,6 +69,7 @@ export function useTemplatesValidation({
defaultModel,
isLoadingDefaultModel,
isCodeEvalEnabled,
+ supportedSourceCodeLanguages,
selectedTemplateIds,
templatesData?.templates,
]);
@@ -73,7 +83,9 @@ export function useTemplatesValidation({
// Find the template
const template = templatesData.templates.find((t) => t.id === templateId);
if (!template) return true;
- if (isCodeEvalTemplate(template)) return isCodeEvalEnabled;
+ if (isCodeEvalTemplate(template)) {
+ return shouldShowEvalTemplate(template, codeEvalCapabilities);
+ }
// If we have a default model, all LLM-as-a-judge templates are valid
if (defaultModel) return true;
diff --git a/web/src/features/evals/pages/new-evaluator.tsx b/web/src/features/evals/pages/new-evaluator.tsx
index aad82b9c18..1b1eaff12e 100644
--- a/web/src/features/evals/pages/new-evaluator.tsx
+++ b/web/src/features/evals/pages/new-evaluator.tsx
@@ -27,7 +27,8 @@ 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 codeEvalCapabilities = useIsCodeEvalEnabled();
+ const { enabled: isCodeEvalEnabled } = codeEvalCapabilities;
const hasDefaultModelReadAccess = useHasProjectAccess({
projectId,
@@ -58,7 +59,9 @@ export default function NewEvaluatorPage() {
);
const currentTemplate = evalTemplates.data?.templates
- .filter((template) => shouldShowEvalTemplate(template, isCodeEvalEnabled))
+ .filter((template) =>
+ shouldShowEvalTemplate(template, codeEvalCapabilities),
+ )
.find((t) => t.id === evaluatorId);
const templatesForCurrentName = api.evals.allTemplatesForName.useQuery(
diff --git a/web/src/features/evals/server/codeEvalTestRun.ts b/web/src/features/evals/server/codeEvalTestRun.ts
index 0ae975ef9d..2c8ac489c1 100644
--- a/web/src/features/evals/server/codeEvalTestRun.ts
+++ b/web/src/features/evals/server/codeEvalTestRun.ts
@@ -32,6 +32,7 @@ import {
isEventTarget,
isExperimentTarget,
} from "@/src/features/evals/utils/typeHelpers";
+import { isCodeEvalSourceCodeLanguageSupported } from "@/src/features/evals/server/isCodeEvalEnabled";
type CodeEvalTestRunError = Omit<CodeEvalUserVisibleError, "retryable">;
@@ -138,6 +139,14 @@ async function runCodeEvalTestForObservation(params: {
});
}
+ if (!isCodeEvalSourceCodeLanguageSupported(codeTemplate.sourceCodeLanguage)) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message:
+ "This code evaluator language is not supported by the configured dispatcher.",
+ });
+ }
+
const extractedVariables = extractObservationVariables({
observation: params.observation,
variableMapping: params.mapping,
diff --git a/web/src/features/evals/server/evalTemplateCreation.ts b/web/src/features/evals/server/evalTemplateCreation.ts
index 1d9df0fad5..48e429ad77 100644
--- a/web/src/features/evals/server/evalTemplateCreation.ts
+++ b/web/src/features/evals/server/evalTemplateCreation.ts
@@ -14,7 +14,10 @@ import {
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";
+import {
+ isCodeEvalEnabled,
+ isCodeEvalSourceCodeLanguageSupported,
+} from "@/src/features/evals/server/isCodeEvalEnabled";
export const CODE_EVAL_TEMPLATE_VARIABLES = [
"input",
@@ -143,6 +146,13 @@ export async function validateEvalTemplateCreation(
message: "Code evals are not enabled",
});
}
+ if (!isCodeEvalSourceCodeLanguageSupported(input.sourceCodeLanguage)) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message:
+ "This code evaluator language is not supported by the configured dispatcher.",
+ });
+ }
return;
default:
assertUnreachable(input);
diff --git a/web/src/features/evals/server/isCodeEvalEnabled.ts b/web/src/features/evals/server/isCodeEvalEnabled.ts
index acc2777432..2379e827a3 100644
--- a/web/src/features/evals/server/isCodeEvalEnabled.ts
+++ b/web/src/features/evals/server/isCodeEvalEnabled.ts
@@ -1,5 +1,55 @@
-import { env } from "@/src/env.mjs";
+import { EvalTemplateSourceCodeLanguage } from "@langfuse/shared";
+import { env } from "@langfuse/shared/src/env";
+
+export type CodeEvalCapabilities = {
+ enabled: boolean;
+ supportedSourceCodeLanguages: EvalTemplateSourceCodeLanguage[];
+};
+
+const ALL_CODE_EVAL_SOURCE_LANGUAGES = [
+ EvalTemplateSourceCodeLanguage.TYPESCRIPT,
+ EvalTemplateSourceCodeLanguage.PYTHON,
+] satisfies EvalTemplateSourceCodeLanguage[];
+
+export function getCodeEvalCapabilities(): CodeEvalCapabilities {
+ if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
+ return {
+ enabled: true,
+ supportedSourceCodeLanguages: ALL_CODE_EVAL_SOURCE_LANGUAGES,
+ };
+ }
+
+ switch (env.LANGFUSE_CODE_EVAL_DISPATCHER) {
+ case "aws-lambda":
+ return {
+ enabled: true,
+ supportedSourceCodeLanguages: ALL_CODE_EVAL_SOURCE_LANGUAGES,
+ };
+ case "insecure-local":
+ return {
+ enabled: true,
+ supportedSourceCodeLanguages: [
+ EvalTemplateSourceCodeLanguage.TYPESCRIPT,
+ ],
+ };
+ default:
+ return {
+ enabled: false,
+ supportedSourceCodeLanguages: [],
+ };
+ }
+}
export function isCodeEvalEnabled(): boolean {
- return env.NEXT_PUBLIC_LANGFUSE_CODE_EVAL_ENABLED === "true";
+ return getCodeEvalCapabilities().enabled;
+}
+
+export function isCodeEvalSourceCodeLanguageSupported(
+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage | null | undefined,
+): boolean {
+ if (!sourceCodeLanguage) return false;
+
+ return getCodeEvalCapabilities().supportedSourceCodeLanguages.includes(
+ sourceCodeLanguage,
+ );
}
diff --git a/web/src/features/evals/server/router.ts b/web/src/features/evals/server/router.ts
index 434e1f1644..acb3d57e4d 100644
--- a/web/src/features/evals/server/router.ts
+++ b/web/src/features/evals/server/router.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
import {
+ authenticatedProcedure,
createTRPCRouter,
protectedProjectProcedure,
} from "@/src/server/api/trpc";
@@ -74,7 +75,11 @@ import {
CreateEvalTemplateInputSchema,
validateEvalTemplateCreation,
} from "@/src/features/evals/server/evalTemplateCreation";
-import { isCodeEvalEnabled } from "@/src/features/evals/server/isCodeEvalEnabled";
+import {
+ getCodeEvalCapabilities,
+ isCodeEvalEnabled,
+ isCodeEvalSourceCodeLanguageSupported,
+} 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
@@ -180,6 +185,77 @@ const CodeEvalTestRunSchema = z.object({
shouldReadFromObservationsTable: z.boolean().optional().default(false),
});
+const getSupportedCodeEvalTemplateLanguages =
+ (): EvalTemplateSourceCodeLanguage[] => {
+ const capabilities = getCodeEvalCapabilities();
+
+ return capabilities.enabled
+ ? capabilities.supportedSourceCodeLanguages
+ : [];
+ };
+
+const getCodeEvalTemplateWhere = (): Prisma.EvalTemplateWhereInput => {
+ const supportedLanguages = getSupportedCodeEvalTemplateLanguages();
+
+ if (supportedLanguages.length === 0) {
+ return { type: { not: EvalTemplateType.CODE } };
+ }
+
+ return {
+ AND: [
+ {
+ OR: [
+ { type: { not: EvalTemplateType.CODE } },
+ {
+ sourceCodeLanguage: {
+ in: supportedLanguages,
+ },
+ },
+ ],
+ },
+ ],
+ };
+};
+
+const assertCodeEvalEnabled = () => {
+ if (!isCodeEvalEnabled()) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "Code evals are not enabled",
+ });
+ }
+};
+
+const getCodeEvalTemplateRawSqlCondition = () => {
+ const supportedLanguages = getSupportedCodeEvalTemplateLanguages();
+
+ if (supportedLanguages.length === 0) {
+ return Prisma.sql`AND type != ${EvalTemplateType.CODE}::"EvalTemplateType"`;
+ }
+
+ const supportedLanguageSql = Prisma.join(
+ supportedLanguages.map(
+ (language) => Prisma.sql`${language}::"EvalTemplateSourceCodeLanguage"`,
+ ),
+ );
+
+ return Prisma.sql`AND (type != ${EvalTemplateType.CODE}::"EvalTemplateType" OR source_code_language IN (${supportedLanguageSql}))`;
+};
+
+const assertCodeEvalTemplateCanRun = (params: {
+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage | null;
+}) => {
+ assertCodeEvalEnabled();
+
+ if (!isCodeEvalSourceCodeLanguageSupported(params.sourceCodeLanguage)) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message:
+ "This code evaluator language is not supported by the configured dispatcher.",
+ });
+ }
+};
+
const UpdateEvalJobSchema = z.object({
scoreName: z.string().min(1).optional(),
filter: z.array(singleFilter).optional(),
@@ -332,6 +408,10 @@ const assertCodeEvalJobConfigTestSucceeds = async ({
};
export const evalRouter = createTRPCRouter({
+ codeEvalCapabilities: authenticatedProcedure.query(() =>
+ getCodeEvalCapabilities(),
+ ),
+
globalJobConfigs: protectedProjectProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
@@ -559,9 +639,7 @@ export const evalRouter = createTRPCRouter({
...(input.isUserManaged
? { projectId: input.projectId }
: { projectId: null }),
- ...(isCodeEvalEnabled()
- ? {}
- : { type: { not: EvalTemplateType.CODE } }),
+ ...getCodeEvalTemplateWhere(),
},
orderBy: [{ version: "desc" }],
});
@@ -591,9 +669,7 @@ 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 typeCondition = getCodeEvalTemplateRawSqlCondition();
const [templates, count] = await Promise.all([
ctx.prisma.$queryRaw<
@@ -697,13 +773,11 @@ export const evalRouter = createTRPCRouter({
scope: "evalTemplate:read",
});
- const template = await ctx.prisma.evalTemplate.findUnique({
+ const template = await ctx.prisma.evalTemplate.findFirst({
where: {
id: input.id,
OR: [{ projectId: input.projectId }, { projectId: null }],
- ...(isCodeEvalEnabled()
- ? {}
- : { type: { not: EvalTemplateType.CODE } }),
+ ...getCodeEvalTemplateWhere(),
},
});
@@ -729,9 +803,7 @@ export const evalRouter = createTRPCRouter({
where: {
OR: [{ projectId: input.projectId }, { projectId: null }],
...(input.id ? { id: input.id } : undefined),
- ...(isCodeEvalEnabled()
- ? {}
- : { type: { not: EvalTemplateType.CODE } }),
+ ...getCodeEvalTemplateWhere(),
},
...(input.limit && input.page
? { take: input.limit, skip: input.page * input.limit }
@@ -742,9 +814,7 @@ export const evalRouter = createTRPCRouter({
where: {
OR: [{ projectId: input.projectId }, { projectId: null }],
...(input.id ? { id: input.id } : undefined),
- ...(isCodeEvalEnabled()
- ? {}
- : { type: { not: EvalTemplateType.CODE } }),
+ ...getCodeEvalTemplateWhere(),
},
});
return {
@@ -865,10 +935,9 @@ 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",
+ if (evalTemplate.type === EvalTemplateType.CODE) {
+ assertCodeEvalTemplateCanRun({
+ sourceCodeLanguage: evalTemplate.sourceCodeLanguage,
});
}
@@ -982,12 +1051,7 @@ export const evalRouter = createTRPCRouter({
scope: "evalJob:CUD",
});
- if (!isCodeEvalEnabled()) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "Code evals are not enabled",
- });
- }
+ assertCodeEvalEnabled();
validateVariableMappingForTarget({
targetObject: input.target,
@@ -1376,12 +1440,9 @@ 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",
- });
- }
+ assertCodeEvalTemplateCanRun({
+ sourceCodeLanguage: existingJob.evalTemplate.sourceCodeLanguage,
+ });
await assertCodeEvalJobConfigTestSucceeds({
prisma: ctx.prisma,
diff --git a/web/src/features/evals/utils/code-eval-template-utils.ts b/web/src/features/evals/utils/code-eval-template-utils.ts
index 32f02bcb8d..8daf765607 100644
--- a/web/src/features/evals/utils/code-eval-template-utils.ts
+++ b/web/src/features/evals/utils/code-eval-template-utils.ts
@@ -1,5 +1,6 @@
import {
EvalTargetObject,
+ type EvalTemplateSourceCodeLanguage,
EvalTemplateType,
type EvalTemplate,
type ObservationVariableMapping,
@@ -9,10 +10,27 @@ export const isCodeEvalTemplate = (
template: Partial<Pick<EvalTemplate, "type">> | null | undefined,
) => template?.type === EvalTemplateType.CODE;
+type CodeEvalCapabilities = {
+ enabled: boolean;
+ supportedSourceCodeLanguages: EvalTemplateSourceCodeLanguage[];
+};
+
export const shouldShowEvalTemplate = (
- template: Pick<EvalTemplate, "type">,
- codeEvalEnabled: boolean,
-) => !isCodeEvalTemplate(template) || codeEvalEnabled;
+ template: Partial<Pick<EvalTemplate, "type" | "sourceCodeLanguage">>,
+ codeEvalCapabilities: CodeEvalCapabilities,
+) => {
+ if (!isCodeEvalTemplate(template)) return true;
+
+ return (
+ codeEvalCapabilities.enabled &&
+ Boolean(
+ template.sourceCodeLanguage &&
+ codeEvalCapabilities.supportedSourceCodeLanguages.includes(
+ template.sourceCodeLanguage,
+ ),
+ )
+ );
+};
export const CODE_EVAL_ESCAPE_CONFIRM_MESSAGE =
"Close code editor? Unsaved changes will be lost.";
diff --git a/web/src/features/navigate-detail-pages/context.tsx b/web/src/features/navigate-detail-pages/context.tsx
index dfd720ea05..68c4fce1a8 100644
--- a/web/src/features/navigate-detail-pages/context.tsx
+++ b/web/src/features/navigate-detail-pages/context.tsx
@@ -1,7 +1,9 @@
import React, {
type PropsWithChildren,
createContext,
+ useCallback,
useContext,
+ useMemo,
useState,
} from "react";
@@ -68,15 +70,20 @@ export function DetailPageListsProvider(props: PropsWithChildren) {
Record<string, Array<ListEntry>>
>({});
- const setDetailPageList = <TEntry extends ListEntry>(
- key: string,
- list: Array<TEntry>,
- ) => {
- setLists((prevLists) => ({ ...prevLists, [key]: list }));
- };
+ const setDetailPageList = useCallback<ListContextType["setDetailPageList"]>(
+ (key, list) => {
+ setLists((prevLists) => ({ ...prevLists, [key]: list }));
+ },
+ [],
+ );
+
+ const contextValue = useMemo(
+ () => ({ detailPagelists, setDetailPageList }),
+ [detailPagelists, setDetailPageList],
+ );
return (
- <DetailPageLists.Provider value={{ detailPagelists, setDetailPageList }}>
+ <DetailPageLists.Provider value={contextValue}>
{props.children}
</DetailPageLists.Provider>
);
diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
index 74637deabe..8fd3b61a86 100644
--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
@@ -987,7 +987,7 @@ describe("Ingestion end-to-end tests", () => {
? null
: getModelId(testConfig.expectedInternalModelId);
expect(generation.internal_model_id).toBe(expectedModelId);
- });
+ }, 15_000);
});
it("should create and update all events", async () => {
@@ -1342,11 +1342,15 @@ describe("Ingestion end-to-end tests", () => {
// Verify that invalid scores were silently rejected (not inserted)
await expect(
- getClickhouseRecord(TableName.Scores, invalidScoreId1),
+ getClickhouseRecord(TableName.Scores, invalidScoreId1, {
+ waitForRecord: false,
+ }),
).rejects.toThrow();
await expect(
- getClickhouseRecord(TableName.Scores, invalidScoreId2),
+ getClickhouseRecord(TableName.Scores, invalidScoreId2, {
+ waitForRecord: false,
+ }),
).rejects.toThrow();
});
@@ -2909,44 +2913,59 @@ describe("Ingestion end-to-end tests", () => {
async function getClickhouseRecord<T extends TableName>(
tableName: T,
entityId: string,
+ options: { waitForRecord?: boolean } = {},
): Promise<RecordReadType<T>> {
- let query = await clickhouseClient().query({
- query: `SELECT * FROM ${tableName} FINAL WHERE project_id = '${projectId}' AND id = '${entityId}'`,
- format: "JSONEachRow",
- });
+ let result: unknown;
+ const waitForRecord = options.waitForRecord ?? true;
- if (
- tableName === "traces" &&
- env.LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT === "true"
- ) {
- await new Promise((resolve) => setTimeout(resolve, 100));
- query = await clickhouseClient().query({
- query: `SELECT
- id,
- name as name,
- user_id as user_id,
- metadata as metadata,
- release as release,
- version as version,
- project_id,
- environment,
- public as public,
- bookmarked as bookmarked,
- tags,
- input as input,
- output as output,
- session_id as session_id,
- 0 as is_deleted,
- start_time as timestamp,
- created_at,
- updated_at,
- updated_at as event_ts
- FROM traces_all_amt FINAL WHERE project_id = '${projectId}' AND id = '${entityId}'`,
+ const loadResult = async () => {
+ let query = await clickhouseClient().query({
+ query: `SELECT * FROM ${tableName} FINAL WHERE project_id = '${projectId}' AND id = '${entityId}'`,
format: "JSONEachRow",
});
- }
- const result = (await query.json())[0];
+ if (
+ tableName === "traces" &&
+ env.LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT === "true"
+ ) {
+ query = await clickhouseClient().query({
+ query: `SELECT
+ id,
+ name as name,
+ user_id as user_id,
+ metadata as metadata,
+ release as release,
+ version as version,
+ project_id,
+ environment,
+ public as public,
+ bookmarked as bookmarked,
+ tags,
+ input as input,
+ output as output,
+ session_id as session_id,
+ 0 as is_deleted,
+ start_time as timestamp,
+ created_at,
+ updated_at,
+ updated_at as event_ts
+ FROM traces_all_amt FINAL WHERE project_id = '${projectId}' AND id = '${entityId}'`,
+ format: "JSONEachRow",
+ });
+ }
+
+ result = (await query.json())[0];
+ };
+
+ if (waitForRecord) {
+ await waitForExpect(async () => {
+ await loadResult();
+ expect(result).toBeDefined();
+ }, 1_500);
+ } else {
+ await loadResult();
+ expect(result).toBeDefined();
+ }
return (
tableName === TableName.Traces