Skip to content

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

fix(evals): align code evaluator editor and runtime globals (#13891)

Tobias Wochinger37b16fd56feb
diff --git a/packages/shared/src/server/evals/localCodeEvalDispatcher.ts b/packages/shared/src/server/evals/localCodeEvalDispatcher.ts
index c0d98c2fb1..a2feaae236 100644
--- a/packages/shared/src/server/evals/localCodeEvalDispatcher.ts
+++ b/packages/shared/src/server/evals/localCodeEvalDispatcher.ts
@@ -40,7 +40,20 @@ export class LocalCodeEvalDispatcher implements CodeEvalDispatcher {
);
}
- const context = vm.createContext({ payload: input.payload });
+ const context = vm.createContext({
+ payload: input.payload,
+ console,
+ setTimeout,
+ clearTimeout,
+ setInterval,
+ clearInterval,
+ queueMicrotask,
+ structuredClone,
+ TextEncoder,
+ TextDecoder,
+ URL,
+ URLSearchParams,
+ });
try {
vm.runInContext(
`${source}
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 f4795ce8d8..98d1b03026 100644
--- a/web/src/features/evals/components/eval-template-type-selector.tsx
+++ b/web/src/features/evals/components/eval-template-type-selector.tsx
@@ -1,3 +1,4 @@
+import { useRef } from "react";
import { type UseFormReturn } from "react-hook-form";
import { type z } from "zod";
import {
@@ -17,7 +18,6 @@ import { type templateFormSchema } from "@/src/features/evals/utils/template-for
import {
type CodeEvalSourceCodeLanguage,
getDefaultCodeEvalSource,
- isDefaultCodeEvalSource,
} from "@/src/features/evals/utils/code-eval-template-validation";
type EvalTemplateFormInput = z.input<typeof templateFormSchema>;
@@ -27,6 +27,7 @@ type EvalTemplateFormReturn = UseFormReturn<
unknown,
EvalTemplateFormOutput
>;
+type CodeEvalSourceDrafts = Partial<Record<CodeEvalSourceCodeLanguage, string>>;
export type EvalTemplateTypeSelectorMode = "all" | "code-only" | "hidden";
@@ -43,6 +44,7 @@ export function EvalTemplateTypeSelector({
hasExistingTemplate: boolean;
onChange?: () => void;
}) {
+ const sourceCodeDraftsRef = useRef<CodeEvalSourceDrafts>({});
const evalTemplateType = form.watch("type");
const sourceCodeLanguage =
form.watch("sourceCodeLanguage") ??
@@ -61,23 +63,29 @@ export function EvalTemplateTypeSelector({
| typeof EvalTemplateType.LLM_AS_JUDGE
| CodeEvalSourceCodeLanguage,
) => {
+ const currentSourceCode = form.getValues("sourceCode") ?? "";
+ const currentSourceCodeLanguage =
+ form.getValues("sourceCodeLanguage") ??
+ EvalTemplateSourceCodeLanguage.TYPESCRIPT;
+
+ if (evalTemplateType === EvalTemplateType.CODE) {
+ sourceCodeDraftsRef.current[currentSourceCodeLanguage] =
+ currentSourceCode;
+ }
+
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));
- }
+ form.setValue(
+ "sourceCode",
+ sourceCodeDraftsRef.current[nextValue] ??
+ getDefaultCodeEvalSource(nextValue),
+ );
onChange?.();
};
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.ts
index b6993cb81c..e512858f5c 100644
--- a/web/src/features/evals/utils/code-eval-template-validation.clienttest.ts
+++ b/web/src/features/evals/utils/code-eval-template-validation.clienttest.ts
@@ -107,17 +107,107 @@ describe("code eval template validation", () => {
expect(result.hasErrors).toBe(false);
});
- it("rejects async TypeScript evaluate functions", async () => {
+ it("accepts async TypeScript evaluate functions with timers", async () => {
const result = await validateCodeEvalSourceWithLanguage({
source: `${TYPESCRIPT_CODE_EVAL_CONTRACT}
+type TimerHandle = unknown;
+type URLSearchParamsInit = string;
+
async function evaluate(ctx: EvaluationContext): Promise<EvaluationResult> {
- return { scores: [] };
+ const timer: TimerHandle = setTimeout(() => {}, 1);
+ clearTimeout(timer);
+ const interval: TimerHandle = setInterval(() => {}, 1);
+ clearInterval(interval);
+ const paramsInit: URLSearchParamsInit = "source=eval";
+ const params = new URLSearchParams(paramsInit);
+ await new Promise((resolve) => setTimeout(resolve, params.has("source") ? 1 : 2));
+ const allValues = await Promise.all([Promise.resolve(1), Promise.resolve(2)]);
+ const settled = await Promise.allSettled([Promise.resolve("ok"), Promise.reject("no")]);
+ const raced = await Promise.race([Promise.resolve(3)]);
+ const anyValue = await Promise.any([Promise.reject("no"), Promise.resolve(4)]);
+ const slicedValues = allValues.slice(0, 2);
+ const firstLargeValue = slicedValues.find((value) => value > 1) ?? 0;
+ let iteratedTotal = 0;
+ slicedValues.forEach((value) => {
+ iteratedTotal = iteratedTotal + value;
+ });
+ const arrayScore =
+ slicedValues.reduce((total, value) => total + value, 0) +
+ (slicedValues.every((value) => value > 0) ? 1 : 0) +
+ (slicedValues.some((value) => value > 1) ? 1 : 0) +
+ (Array.isArray(slicedValues) ? 1 : 0) +
+ firstLargeValue +
+ iteratedTotal;
+
+ return {
+ scores: [{
+ name: "async helpers",
+ value: arrayScore + settled.length + raced + anyValue,
+ dataType: "NUMERIC",
+ }],
+ };
}
`,
sourceCodeLanguage: "TYPESCRIPT",
});
- expect(result.hasErrors).toBe(true);
+ expect(result.hasErrors).toBe(false);
+ });
+
+ it("accepts simple Node runtime globals and keeps process unavailable", async () => {
+ const result = await validateCodeEvalSourceWithLanguage({
+ source: `${TYPESCRIPT_CODE_EVAL_CONTRACT}
+function evaluate(ctx: EvaluationContext): EvaluationResult {
+ const url = new URL("https://user:[email protected]:443/docs?source=eval#section");
+ const urlScore =
+ url.origin.length +
+ url.protocol.length +
+ url.host.length +
+ url.port.length +
+ url.username.length +
+ url.password.length +
+ url.hash.length;
+ const params = new URLSearchParams([["source", "eval"]]);
+ const paramsCopy = new URLSearchParams(params);
+ paramsCopy.append("next", "true");
+ paramsCopy.set("source", "code");
+ paramsCopy.delete("missing");
+ let paramsScore = paramsCopy.has("source") ? (paramsCopy.get("source") ?? "").length : 0;
+ paramsCopy.forEach((value, key) => {
+ paramsScore = paramsScore + value.length + key.length;
+ });
+ const encoded = new TextEncoder().encode(url.hostname);
+ const sliced = encoded.slice(0, 4).subarray(0, 2);
+ let byteTotal = 0;
+ sliced.forEach((value) => {
+ byteTotal = byteTotal + value;
+ });
+ const copy = structuredClone({ length: encoded.length });
+ queueMicrotask(() => {});
+
+ return { scores: [{ name: "encoded", value: copy.length + byteTotal + paramsScore + urlScore, dataType: "NUMERIC" }] };
+}
+`,
+ sourceCodeLanguage: "TYPESCRIPT",
+ });
+
+ expect(result.hasErrors).toBe(false);
+
+ const processResult = await validateCodeEvalSourceWithLanguage({
+ source: `${TYPESCRIPT_CODE_EVAL_CONTRACT}
+function evaluate(ctx: EvaluationContext): EvaluationResult {
+ return { scores: [{ name: "env", value: process.env.NODE_ENV ?? "", dataType: "TEXT" }] };
+}
+`,
+ sourceCodeLanguage: "TYPESCRIPT",
+ });
+
+ expect(processResult.hasErrors).toBe(true);
+ expect(
+ processResult.diagnostics.some((diagnostic) =>
+ diagnostic.message.includes("Cannot find name 'process'"),
+ ),
+ ).toBe(true);
});
it("rejects exported TypeScript evaluate functions", async () => {
diff --git a/web/src/features/evals/utils/code-eval-template-validation.ts b/web/src/features/evals/utils/code-eval-template-validation.ts
index 6d9e8be7cc..67326b637b 100644
--- a/web/src/features/evals/utils/code-eval-template-validation.ts
+++ b/web/src/features/evals/utils/code-eval-template-validation.ts
@@ -44,18 +44,41 @@ type RuffWorkspace = {
const SYNTHETIC_ASSERTION_PREFIX = `
type __LangfuseExpectedEvaluate = (
ctx: EvaluationContext,
-) => EvaluationResult;
+) => EvaluationResult | Promise<EvaluationResult>;
const __langfuseEvaluateCheck: __LangfuseExpectedEvaluate = evaluate;
`;
const CONTRACT_DECLARATIONS = `
+type Awaited<T> = T extends PromiseLike<infer U> ? Awaited<U> : T;
+type PromiseSettledResult<T> =
+ | { status: "fulfilled"; value: T }
+ | { status: "rejected"; reason: any };
+
interface Array<T> {
length: number;
[n: number]: T;
+ every(callbackfn: (value: T, index: number, array: T[]) => unknown): boolean;
map<U>(callbackfn: (value: T, index: number, array: T[]) => U): U[];
filter(callbackfn: (value: T, index: number, array: T[]) => unknown): T[];
+ find(callbackfn: (value: T, index: number, array: T[]) => unknown): T | undefined;
+ forEach(callbackfn: (value: T, index: number, array: T[]) => void): void;
includes(searchElement: T, fromIndex?: number): boolean;
join(separator?: string): string;
+ reduce<U>(
+ callbackfn: (
+ previousValue: U,
+ currentValue: T,
+ currentIndex: number,
+ array: T[],
+ ) => U,
+ initialValue: U,
+ ): U;
+ slice(start?: number, end?: number): T[];
+ some(callbackfn: (value: T, index: number, array: T[]) => unknown): boolean;
+}
+
+interface ArrayConstructor {
+ isArray(value: unknown): value is unknown[];
}
interface Boolean {}
@@ -84,15 +107,43 @@ interface PromiseLike<T> {
): PromiseLike<TResult1 | TResult2>;
}
+interface PromiseConstructor {
+ new <T>(
+ executor: (
+ resolve: (value: T | PromiseLike<T>) => void,
+ reject: (reason?: any) => void,
+ ) => void,
+ ): Promise<T>;
+ all<T>(values: T[]): Promise<Awaited<T>[]>;
+ allSettled<T>(values: T[]): Promise<PromiseSettledResult<Awaited<T>>[]>;
+ any<T>(values: T[]): Promise<Awaited<T>>;
+ race<T>(values: T[]): Promise<Awaited<T>>;
+ resolve<T>(value: T | PromiseLike<T>): Promise<T>;
+ reject<T = never>(reason?: any): Promise<T>;
+}
+
interface String {
+ readonly length: number;
includes(searchString: string, position?: number): boolean;
trim(): string;
toLowerCase(): string;
toString(): string;
}
+interface Uint8Array {
+ readonly length: number;
+ [n: number]: number;
+ forEach(
+ callbackfn: (value: number, index: number, array: Uint8Array) => void,
+ ): void;
+ slice(start?: number, end?: number): Uint8Array;
+ subarray(begin?: number, end?: number): Uint8Array;
+}
+
type Record<K extends string, T> = { [P in K]: T };
+declare const Promise: PromiseConstructor;
+declare const Array: ArrayConstructor;
declare const String: (value?: unknown) => string;
declare const Number: (value?: unknown) => number;
declare const Boolean: (value?: unknown) => boolean;
@@ -112,6 +163,54 @@ declare const console: {
warn(...args: unknown[]): void;
error(...args: unknown[]): void;
};
+declare function setTimeout(
+ callback: (...args: any[]) => void,
+ delay?: number,
+ ...args: any[]
+): unknown;
+declare function clearTimeout(handle?: unknown): void;
+declare function setInterval(
+ callback: (...args: any[]) => void,
+ delay?: number,
+ ...args: any[]
+): unknown;
+declare function clearInterval(handle?: unknown): void;
+declare function queueMicrotask(callback: () => void): void;
+declare function structuredClone<T>(value: T): T;
+declare class TextEncoder {
+ encode(input?: string): Uint8Array;
+}
+declare class TextDecoder {
+ decode(input?: Uint8Array): string;
+}
+declare class URL {
+ constructor(url: string, base?: string | URL);
+ hash: string;
+ host: string;
+ href: string;
+ hostname: string;
+ origin: string;
+ pathname: string;
+ password: string;
+ port: string;
+ protocol: string;
+ search: string;
+ searchParams: URLSearchParams;
+ username: string;
+ toString(): string;
+}
+declare class URLSearchParams {
+ constructor(init?: string | Record<string, string> | string[][] | URLSearchParams);
+ append(name: string, value: string): void;
+ delete(name: string): void;
+ forEach(
+ callbackfn: (value: string, key: string, parent: URLSearchParams) => void,
+ ): void;
+ get(name: string): string | null;
+ has(name: string): boolean;
+ set(name: string, value: string): void;
+ toString(): string;
+}
`;
const IGNORED_DIAGNOSTIC_CODES = new Set([2318]);
diff --git a/worker/src/features/evaluation/codeBased/localCodeEvalDispatcher.test.ts b/worker/src/features/evaluation/codeBased/localCodeEvalDispatcher.test.ts
index 691f21ec9e..62943dd489 100644
--- a/worker/src/features/evaluation/codeBased/localCodeEvalDispatcher.test.ts
+++ b/worker/src/features/evaluation/codeBased/localCodeEvalDispatcher.test.ts
@@ -55,6 +55,35 @@ describe("LocalCodeEvalDispatcher", () => {
});
});
+ it("exposes the supported Node-like evaluator globals", async () => {
+ const dispatcher = new LocalCodeEvalDispatcher();
+
+ const result = await dispatcher.dispatch({
+ ...baseInput,
+ runtime: { language: "TYPESCRIPT" },
+ code: {
+ source: `
+ async function evaluate() {
+ await new Promise((resolve) => setTimeout(resolve, 1));
+
+ const encoded = new TextEncoder().encode(
+ new URL("https://langfuse.com/docs").hostname,
+ );
+ const copy = structuredClone({ length: encoded.length });
+
+ return {
+ scores: [{ name: "encoded", value: copy.length, dataType: "NUMERIC" }],
+ };
+ }
+ `,
+ },
+ });
+
+ expect(result).toEqual({
+ scores: [{ name: "encoded", value: 12, dataType: "NUMERIC" }],
+ });
+ });
+
it("rejects unsupported TypeScript syntax with a docs link", async () => {
const dispatcher = new LocalCodeEvalDispatcher();