🪢 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): improve code evaluator editing experience (#14757)
Tobias Wochinger7989611f8482
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.tsxindex 7efa46ea7f..7f3c1e5203 100644--- a/web/src/features/evals/components/code-eval-template-form-body.tsx+++ b/web/src/features/evals/components/code-eval-template-form-body.tsx@@ -1,23 +1,11 @@-import CodeMirror, {- EditorView,- ExternalChange,- hoverTooltip,-} from "@uiw/react-codemirror";+import CodeMirror, { EditorView, hoverTooltip } from "@uiw/react-codemirror";import { EditorState, Prec } from "@codemirror/state";import { linter, type Diagnostic } from "@codemirror/lint";import { javascript } from "@codemirror/lang-javascript";import { python } from "@codemirror/lang-python";-import { foldEffect, foldable } from "@codemirror/language";import { EvalTemplateSourceCodeLanguage } from "@langfuse/shared";import { useTheme } from "next-themes";-import {- type ReactNode,- useCallback,- useEffect,- useMemo,- useRef,- useState,-} from "react";+import { type ReactNode, useCallback, useMemo, useState } from "react";import { Loader2 } from "lucide-react";import { Button } from "@/src/components/ui/button";@@ -30,8 +18,6 @@ import {} from "@/src/features/evals/utils/code-eval-template-hover-docs";import {formatPythonCodeEvalSourceWithRuff,- PYTHON_CODE_EVAL_CONTRACT,- TYPESCRIPT_CODE_EVAL_CONTRACT,type CodeEvalSourceCodeLanguage,type CodeEvalValidationResult,} from "@/src/features/evals/utils/code-eval-template-validation";@@ -45,19 +31,9 @@ type CodeEvalTemplateFormBodyProps = {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_ARIA = "Alt+Shift+F";+const FUNCTION_CONTRACT_DOCS_URL =+ "https://langfuse.com/docs/evaluation/evaluation-methods/code-evaluators#function-contract";function createCodeEvalHoverExtension(hoverDocs: CodeEvalHoverDocs) {return hoverTooltip((view, pos) => {@@ -87,81 +63,6 @@ function createCodeEvalHoverExtension(hoverDocs: CodeEvalHoverDocs) {});}-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;-});--const contractReadOnlyExtensions = [contractReadOnlyExtension];-async function formatTypeScriptSource(source: string) {// babel-ts instead of the typescript plugin: the latter embeds the// TypeScript compiler, which the SWC minifier miscompiles (dropped@@ -172,89 +73,12 @@ async function formatTypeScriptSource(source: string) {import("prettier/plugins/estree"),]);- const ranges = findTypeScriptContractRanges(source);- if (!ranges?.prelude) {- return format(source, {- parser: "babel-ts",- plugins: [babelPlugin, estreePlugin],- });- }-- const formattedEditableSource = await format(- source.slice(ranges.prelude.to),- {- parser: "babel-ts",- plugins: [babelPlugin, estreePlugin],- },- );-- return `${source.slice(0, ranges.prelude.to)}\n${formattedEditableSource.trimStart()}`;-}--async function formatPythonSource(source: string) {- const ranges = findPythonContractRanges(source);- if (!ranges?.prelude) {- return formatPythonCodeEvalSourceWithRuff(source);- }-- const formattedEditableSource = await formatPythonCodeEvalSourceWithRuff(- source.slice(ranges.prelude.to),- );-- return `${source.slice(0, ranges.prelude.to).trimEnd()}\n\n\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" }),- });+ return format(source, {+ parser: "babel-ts",+ plugins: [babelPlugin, estreePlugin],});}-function foldContractTypes(- view: EditorView,- sourceCodeLanguage: CodeEvalSourceCodeLanguage,-) {- if (typeof window === "undefined") return;-- const contractLength =- sourceCodeLanguage === "PYTHON"- ? PYTHON_CODE_EVAL_CONTRACT.length- : TYPESCRIPT_CODE_EVAL_CONTRACT.length;-- const doFold = () => {- if (!view.dom.isConnected) return;-- const effects: ReturnType<typeof foldEffect.of>[] = [];- const state = view.state;-- // Find all foldable ranges within the contract section- let pos = 0;- while (pos < contractLength && pos < state.doc.length) {- const line = state.doc.lineAt(pos);- const range = foldable(state, line.from, line.to);- if (range && range.from < contractLength) {- effects.push(foldEffect.of({ from: range.from, to: range.to }));- }- pos = line.to + 1;- }-- if (effects.length > 0) {- view.dispatch({ effects });- }- };-- // Delay to ensure the language parser has time to analyze the document.- // Python parsing may need more time than TypeScript.- const delay = sourceCodeLanguage === "PYTHON" ? 100 : 50;- setTimeout(doFold, delay);-}-export function CodeEvalTemplateFormBody({sourceCode,sourceCodeLanguage,@@ -264,7 +88,6 @@ export function CodeEvalTemplateFormBody({headerAction,}: CodeEvalTemplateFormBodyProps) {const { resolvedTheme } = useTheme();- const codeMirrorViewRef = useRef<EditorView | null>(null);const [isFormatting, setIsFormatting] = useState(false);const codeMirrorTheme = resolvedTheme === "dark" ? darkTheme : lightTheme;const languageLabel =@@ -273,32 +96,6 @@ export function CodeEvalTemplateFormBody({: "TypeScript";const shouldShowFormatButton = editable;- const handleCreateEditor = useCallback(- (view: EditorView) => {- codeMirrorViewRef.current = view;- foldContractTypes(view, sourceCodeLanguage);- scrollCodeMirrorToBottom(view);- },- [sourceCodeLanguage],- );-- useEffect(() => {- const view = codeMirrorViewRef.current;- if (!view) return;-- // Don't re-fold on every sourceCode change, only on language change- scrollCodeMirrorToBottom(view);- }, [sourceCode]);-- useEffect(() => {- const view = codeMirrorViewRef.current;- if (!view) return;-- // Re-fold when language changes- foldContractTypes(view, sourceCodeLanguage);- scrollCodeMirrorToBottom(view);- }, [sourceCodeLanguage]);-const diagnostics = useMemo(() => validationResult?.diagnostics ?? [],[validationResult?.diagnostics],@@ -311,9 +108,11 @@ export function CodeEvalTemplateFormBody({try {const formatted =sourceCodeLanguage === EvalTemplateSourceCodeLanguage.PYTHON- ? await formatPythonSource(sourceCode)+ ? await formatPythonCodeEvalSourceWithRuff(sourceCode): await formatTypeScriptSource(sourceCode);- onSourceCodeChange(formatted);+ // Prettier and Ruff always emit a trailing newline, which CodeMirror+ // would render as an empty final line.+ onSourceCodeChange(formatted.trimEnd());} catch (error) {console.error(error);} finally {@@ -378,10 +177,6 @@ export function CodeEvalTemplateFormBody({createCodeEvalHoverExtension(getCodeEvalHoverDocs(sourceCodeLanguage)),[sourceCodeLanguage],);- const protectedContractExtensions = useMemo(- () => contractReadOnlyExtensions,- [],- );return (<div className="space-y-2">@@ -427,7 +222,6 @@ export function CodeEvalTemplateFormBody({extensions={[...(!editable ? [EditorState.readOnly.of(true)] : []),languageExtension,- ...protectedContractExtensions,codeEvalHoverExtension,linterExtension,...(shouldShowFormatButton ? [formatShortcutExtension] : []),@@ -436,20 +230,27 @@ export function CodeEvalTemplateFormBody({"&.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"/>+ <p className="text-muted-foreground text-xs">+ The evaluate function receives an EvaluationContext and returns an+ EvaluationResult with one or more scores.{" "}+ <a+ href={FUNCTION_CONTRACT_DOCS_URL}+ target="_blank"+ rel="noopener noreferrer"+ className="underline"+ >+ See type definitions.+ </a>+ </p></div>);}diff --git a/web/src/features/evals/components/template-form.tsx b/web/src/features/evals/components/template-form.tsxindex 14b8dbe4d2..02c6a06f39 100644--- a/web/src/features/evals/components/template-form.tsx+++ b/web/src/features/evals/components/template-form.tsx@@ -959,7 +959,7 @@ export const InnerEvalTemplateForm = (props: {{props.useDialog ? <DialogBody>{formBody}</DialogBody> : formBody}{props.useDialog ? (- <DialogFooter>{formFooter}</DialogFooter>+ <DialogFooter variant="action">{formFooter}</DialogFooter>) : (formFooter)}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.tsindex 08e6e21757..7ac640bb4a 100644--- a/web/src/features/evals/utils/code-eval-template-hover-docs.ts+++ b/web/src/features/evals/utils/code-eval-template-hover-docs.ts@@ -15,7 +15,7 @@ type ScoreBase = {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.`;+A Langfuse score returned by a TypeScript evaluator.`;const PYTHON_SCORE_DOC = `@dataclassclass Score:@@ -49,7 +49,7 @@ The TypeScript value Langfuse passes to evaluate.`,| undefined;}-The data Langfuse passes to a TypeScript evaluator. The definition is locked at the top of the editor.`,+The data Langfuse passes to a TypeScript evaluator.`,observation: `property EvaluationContext.observation: {input: any;output: any;diff --git a/web/src/features/evals/utils/code-eval-template-starter-examples.clienttest.ts b/web/src/features/evals/utils/code-eval-template-starter-examples.clienttest.tsnew file mode 100644index 0000000000..75dd0d0dc0--- /dev/null+++ b/web/src/features/evals/utils/code-eval-template-starter-examples.clienttest.ts@@ -0,0 +1,86 @@+import { readFileSync } from "node:fs";+import { createRequire } from "node:module";+import { beforeAll, describe, expect, it } from "vitest";+import { initSync } from "@astral-sh/ruff-wasm-web";+import {+ DEFAULT_PYTHON_CODE_EVAL_SOURCE,+ DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE,+ formatAndStripCodeEvalSourceForSubmit,+} from "@/src/features/evals/utils/code-eval-template-starter-examples";+import { validateCodeEvalSourceWithPython } from "@/src/features/evals/utils/code-eval-template-validation";++// This suite runs the real formatters (Prettier and the Ruff wasm build), so+// the starter sources are guaranteed to be format-canonical: clicking Format+// or submitting untouched starter code must not change it.+describe("code eval starter examples are format-canonical", () => {+ beforeAll(() => {+ // The web wasm build initializes itself via fetch(), which cannot load+ // file:// URLs in Node, so feed it the wasm bytes up front. Later init+ // calls in production code short-circuit once the wasm is loaded.+ const require = createRequire(import.meta.url);+ initSync({+ module: readFileSync(+ require.resolve("@astral-sh/ruff-wasm-web/ruff_wasm_bg.wasm"),+ ),+ });+ });++ it("keeps the default TypeScript source unchanged when formatted", async () => {+ await expect(+ formatAndStripCodeEvalSourceForSubmit({+ sourceCode: DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE,+ sourceCodeLanguage: "TYPESCRIPT",+ }),+ ).resolves.toBe(DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE);+ });++ it("keeps the default Python source unchanged when formatted", async () => {+ await expect(+ formatAndStripCodeEvalSourceForSubmit({+ sourceCode: DEFAULT_PYTHON_CODE_EVAL_SOURCE,+ sourceCodeLanguage: "PYTHON",+ }),+ ).resolves.toBe(DEFAULT_PYTHON_CODE_EVAL_SOURCE);+ });++ it("keeps Python helpers defined above evaluate on submit", async () => {+ const source = `def helper(value):+ return bool(value)+++def evaluate(ctx: EvaluationContext) -> EvaluationResult:+ is_valid = helper(ctx.observation.output)+ return EvaluationResult(scores=[Score(name="ok", value=is_valid)])`;++ await expect(+ formatAndStripCodeEvalSourceForSubmit({+ sourceCode: source,+ sourceCodeLanguage: "PYTHON",+ }),+ ).resolves.toBe(source);+ });++ it("still injects the hidden contract when the source imports dataclass itself", async () => {+ // Regression: the contract-presence check must not mistake a user-owned+ // `from dataclasses import dataclass` for the full hidden contract,+ // otherwise the contract types raise blocking F821 errors.+ const source = `from dataclasses import dataclass+++@dataclass+class Helper:+ flag: bool+++def evaluate(ctx: EvaluationContext) -> EvaluationResult:+ return EvaluationResult(scores=[Score(name="ok", value=True)])`;++ const result = await validateCodeEvalSourceWithPython(source);++ expect(+ result.diagnostics.filter(+ (diagnostic) => diagnostic.severity === "error",+ ),+ ).toEqual([]);+ });+});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.tsindex 479075525c..9639d1b6a4 100644--- a/web/src/features/evals/utils/code-eval-template-starter-examples.ts+++ b/web/src/features/evals/utils/code-eval-template-starter-examples.ts@@ -31,12 +31,11 @@ type EvaluationResult = {};`;-export const DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE = `${TYPESCRIPT_CODE_EVAL_CONTRACT}--function evaluate(ctx: EvaluationContext): EvaluationResult {+// Keep in sync with the Prettier output so the Format button is a no-op on+// the untouched starter code.+export const DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE = `function evaluate(ctx: EvaluationContext): EvaluationResult {const input = ctx.observation.input;- const matchesOutput =- input !== undefined && ctx.observation.output === input;+ const matchesOutput = input !== undefined && ctx.observation.output === input;return {scores: [@@ -50,8 +49,7 @@ function evaluate(ctx: EvaluationContext): EvaluationResult {},],};-}-`;+}`;export const PYTHON_CODE_EVAL_CONTRACT = `from dataclasses import dataclassfrom typing import Any@@ -91,29 +89,25 @@ 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 const DEFAULT_PYTHON_CODE_EVAL_SOURCE = `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";@@ -132,6 +126,33 @@ export function isDefaultCodeEvalSource(sourceCode: string) {);}+// The contract type declarations are not shown in the editor; they are+// documented at+// https://langfuse.com/docs/evaluation/evaluation-methods/code-evaluators#function-contract+// and only prepended behind the scenes for validation.+//+// Stripping is still required because sources can contain the contract via+// two paths the UI does not control: templates created through the public+// API (sourceCode is stored verbatim) and full docs examples pasted into the+// editor.+function stripCodeEvalContract({+ sourceCode,+ sourceCodeLanguage,+}: {+ sourceCode: string;+ sourceCodeLanguage: CodeEvalSourceCodeLanguage;+}) {+ const contract =+ sourceCodeLanguage === "PYTHON"+ ? PYTHON_CODE_EVAL_CONTRACT+ : TYPESCRIPT_CODE_EVAL_CONTRACT;+ const source = sourceCode.trimStart();++ return source.startsWith(contract)+ ? source.slice(contract.length).trimStart()+ : source;+}+export function getCodeEvalSourceForEditor({sourceCode,sourceCodeLanguage,@@ -141,15 +162,7 @@ export function getCodeEvalSourceForEditor({}) {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()}`;+ return stripCodeEvalContract({ sourceCode, sourceCodeLanguage });}async function formatTypeScriptSource(source: string): Promise<string> {@@ -175,7 +188,7 @@ async function formatPythonSource(source: string): Promise<string> {const workspace = new ruffModule.Workspace({"line-length": 88,- "indent-width": 4,+ "indent-width": 2,},ruffModule.PositionEncoding.Utf16,);@@ -184,9 +197,8 @@ async function formatPythonSource(source: string): Promise<string> {}/**- * 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.+ * Formats the source code for submission and strips the contract types in+ * case they were pasted into the editor.*/export async function formatAndStripCodeEvalSourceForSubmit({sourceCode,@@ -195,31 +207,18 @@ export async function formatAndStripCodeEvalSourceForSubmit({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();+ const strippedSource = stripCodeEvalContract({+ sourceCode,+ sourceCodeLanguage,+ }).trim();try {- return (await formatTypeScriptSource(strippedSource)).trimEnd();+ const formattedSource =+ sourceCodeLanguage === "PYTHON"+ ? await formatPythonSource(strippedSource)+ : await formatTypeScriptSource(strippedSource);++ return formattedSource.trimEnd();} catch {return strippedSource;}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.tsindex 81bb80ac84..12951c173f 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@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";import {DEFAULT_PYTHON_CODE_EVAL_SOURCE,DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE,+ PYTHON_CODE_EVAL_CONTRACT,TYPESCRIPT_CODE_EVAL_CONTRACT,formatAndStripCodeEvalSourceForSubmit,formatPythonCodeEvalSourceWithRuff,@@ -50,43 +51,35 @@ describe("code eval template validation", () => {);expect(isDefaultCodeEvalSource(DEFAULT_PYTHON_CODE_EVAL_SOURCE)).toBe(true);expect(DEFAULT_PYTHON_CODE_EVAL_SOURCE).toMatch(- /^from dataclasses import dataclass/,+ /^def evaluate\(ctx: EvaluationContext\) -> EvaluationResult:/,);- expect(DEFAULT_PYTHON_CODE_EVAL_SOURCE).toContain(- "def evaluate(ctx: EvaluationContext) -> EvaluationResult:",+ expect(DEFAULT_PYTHON_CODE_EVAL_SOURCE).not.toContain(+ "from dataclasses import dataclass",);- 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).toMatch(+ /^function evaluate\(ctx: EvaluationContext\): EvaluationResult/,);- expect(DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE).toContain(- "function evaluate(ctx: EvaluationContext): EvaluationResult",+ expect(DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE).not.toContain(+ "type EvaluationContext =",);});- it("strips editor-only contracts before submit", async () => {+ it("strips pasted contracts before submit", async () => {expect(await formatAndStripCodeEvalSourceForSubmit({- sourceCode: DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE,+ sourceCode: `${TYPESCRIPT_CODE_EVAL_CONTRACT}\n\n${DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE}`,sourceCodeLanguage: "TYPESCRIPT",}),- ).toContain("function evaluate(ctx: EvaluationContext): EvaluationResult");+ ).toMatch(/^function evaluate\(ctx: EvaluationContext\)/);expect(await formatAndStripCodeEvalSourceForSubmit({- sourceCode: DEFAULT_PYTHON_CODE_EVAL_SOURCE,+ sourceCode: `${PYTHON_CODE_EVAL_CONTRACT}\n\n${DEFAULT_PYTHON_CODE_EVAL_SOURCE}`,sourceCodeLanguage: "PYTHON",}),).toMatch(/^def evaluate\(ctx: EvaluationContext\)/);});- it("rehydrates stored evaluator functions for the editor", () => {+ it("hydrates the editor without the contract types", () => {const source ="function evaluate(ctx: EvaluationContext): EvaluationResult { return { scores: [] }; }";@@ -95,7 +88,13 @@ describe("code eval template validation", () => {sourceCode: source,sourceCodeLanguage: "TYPESCRIPT",}),- ).toContain(TYPESCRIPT_CODE_EVAL_CONTRACT);+ ).toBe(source);+ expect(+ getCodeEvalSourceForEditor({+ sourceCode: `${TYPESCRIPT_CODE_EVAL_CONTRACT}\n\n${source}`,+ sourceCodeLanguage: "TYPESCRIPT",+ }),+ ).toBe(source);});it("accepts the default TypeScript source", async () => {diff --git a/web/src/features/evals/utils/code-eval-template-validation.ts b/web/src/features/evals/utils/code-eval-template-validation.tsindex bc1a555c7d..1bc803b158 100644--- a/web/src/features/evals/utils/code-eval-template-validation.ts+++ b/web/src/features/evals/utils/code-eval-template-validation.ts@@ -576,7 +576,7 @@ declare class URLSearchParams {const IGNORED_DIAGNOSTIC_CODES = new Set([2318]);const PYTHON_RUFF_SETTINGS = {"line-length": 88,- "indent-width": 4,+ "indent-width": 2,lint: {select: ["E4", "E7", "E9", "F"],},@@ -587,7 +587,6 @@ const PYTHON_ERROR_DIAGNOSTIC_CODES = new Set(["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;@@ -618,7 +617,7 @@ export async function validateCodeEvalSourceWithPython(): Promise<CodeEvalValidationResult> {const sourceBytes = getUtf8ByteLength(source);const diagnostics: CodeEvalDiagnostic[] = [];- const validationSource = source.trimStart().startsWith(PYTHON_CONTRACT_PREFIX)+ const validationSource = hasPythonContractDeclarations(source)? source: `${PYTHON_CODE_EVAL_CONTRACT}\n\n${source}`;@@ -828,6 +827,17 @@ function hasTypeScriptContractDeclarations(source: string) {);}+// Like hasTypeScriptContractDeclarations: detect the declarations themselves+// instead of an exact contract prefix, so user code that happens to share the+// contract's first line still gets the hidden contract injected.+function hasPythonContractDeclarations(source: string) {+ return (+ /\bclass\s+EvaluationContext\b/.test(source) &&+ /\bclass\s+Score\b/.test(source) &&+ /\bclass\s+EvaluationResult\b/.test(source)+ );+}+function mapValidationOffsetToSourceOffset({offset,contractOffset,@@ -1001,15 +1011,6 @@ function collectPythonContractDiagnostics() {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)