🪢 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
refactor(code-evaluators): TS and python code formatting to auto-collapse comments (#13972)
marliessophiedc2f057ac406
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2323918d88..deafce9965 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -64,7 +64,7 @@ importers:version: 16.2.6(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])next-auth:specifier: ^4.24.13- version: 4.24.13(patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 4.24.13(patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])zod:specifier: 4.3.6version: 4.3.6@@ -283,7 +283,7 @@ importers:version: 11.2.7next-auth:specifier: ^4.24.13- version: 4.24.13(patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 4.24.13(patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])nodemailer:specifier: ^7.0.11version: 7.0.11@@ -381,6 +381,9 @@ importers:'@baselime/trpc-opentelemetry-middleware':specifier: ^0.1.2+ '@codemirror/lang-javascript':+ specifier: ^6.2.5+ version: 6.2.5'@codemirror/lang-json':specifier: ^6.0.2version: 6.0.2@@ -674,7 +677,7 @@ importers:version: 16.2.6(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])next-auth:specifier: ^4.24.13- version: 4.24.13(patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 4.24.13(patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])next-query-params:specifier: ^5.1.0version: 5.1.0([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]([email protected]))([email protected]))@@ -1597,6 +1600,9 @@ packages:'@codemirror/[email protected]':resolution: {integrity: sha512-JFRiqhKu+bvSkDLI+rUhJwSxQxYb759W5GBezE8Uc8mHLqC9aV/9aTC7yJSqCtB3F00pylrLCwnyS91Ap5ej4Q==}+ '@codemirror/[email protected]':+ resolution: {integrity: sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==}+'@codemirror/[email protected]':resolution: {integrity: sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ==}@@ -2445,6 +2451,9 @@ packages:'@lezer/[email protected]':resolution: {integrity: sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==}+ '@lezer/[email protected]':+ resolution: {integrity: sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==}+'@lezer/[email protected]':resolution: {integrity: sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ==}@@ -11845,6 +11854,16 @@ snapshots:'@codemirror/view': 6.42.0'@lezer/common': 1.5.1+ '@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/lint': 6.9.6+ '@codemirror/state': 6.6.0+ '@codemirror/view': 6.42.0+ '@lezer/common': 1.5.1+ '@lezer/javascript': 1.5.4+'@codemirror/[email protected]':dependencies:'@codemirror/language': 6.12.3@@ -12646,6 +12665,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+'@lezer/[email protected]':dependencies:'@lezer/common': 1.5.1@@ -12742,7 +12767,7 @@ snapshots:'@next-auth/[email protected](@prisma/[email protected]([email protected]([email protected])([email protected]))([email protected]))([email protected](patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]))':dependencies:'@prisma/client': 6.19.3([email protected]([email protected])([email protected]))([email protected])- next-auth: 4.24.13(patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ next-auth: 4.24.13(patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])'@next/[email protected]': {}@@ -17435,7 +17460,7 @@ snapshots:tinyglobby: 0.2.16unrs-resolver: 1.11.1optionalDependencies:- eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))transitivePeerDependencies:- supports-color@@ -19512,7 +19537,7 @@ snapshots:dependencies:type-fest: 2.19.0- [email protected](patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]):+ [email protected](patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]):dependencies:'@babel/runtime': 7.29.2'@panva/hkdf': 1.2.1diff --git a/web/package.json b/web/package.jsonindex ecd8a90085..d0390256e2 100644--- a/web/package.json+++ b/web/package.json@@ -36,6 +36,7 @@"@appsignal/opentelemetry-instrumentation-bullmq": "^0.8.0","@astral-sh/ruff-wasm-web": "0.15.13","@baselime/trpc-opentelemetry-middleware": "^0.1.2",+ "@codemirror/lang-javascript": "^6.2.5","@codemirror/lang-json": "^6.0.2","@codemirror/lang-python": "^6.2.1","@codemirror/language": "^6.12.3",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 452f49b252..67328c1223 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@@ -5,8 +5,9 @@ import CodeMirror, {} from "@uiw/react-codemirror";import { EditorState, Prec } from "@codemirror/state";import { linter, type Diagnostic } from "@codemirror/lint";-import { StreamLanguage, type StringStream } from "@codemirror/language";+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 {@@ -28,6 +29,7 @@ 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,@@ -55,79 +57,6 @@ type ContractRanges = {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 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) => {@@ -283,6 +212,45 @@ function scrollCodeMirrorToBottom(view: EditorView) {});}+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,@@ -301,17 +269,31 @@ export function CodeEvalTemplateFormBody({: "TypeScript";const shouldShowFormatButton = editable;- const handleCreateEditor = useCallback((view: EditorView) => {- codeMirrorViewRef.current = view;+ 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 changescrollCodeMirrorToBottom(view);- }, []);+ }, [sourceCode]);useEffect(() => {const view = codeMirrorViewRef.current;if (!view) return;+ // Re-fold when language changes+ foldContractTypes(view, sourceCodeLanguage);scrollCodeMirrorToBottom(view);- }, [sourceCode, sourceCodeLanguage]);+ }, [sourceCodeLanguage]);const diagnostics = useMemo(() => validationResult?.diagnostics ?? [],@@ -384,7 +366,7 @@ export function CodeEvalTemplateFormBody({() =>sourceCodeLanguage === EvalTemplateSourceCodeLanguage.PYTHON? python()- : typescriptCodeEvalLanguage,+ : javascript({ typescript: true }),[sourceCodeLanguage],);const codeEvalHoverExtension = useMemo(diff --git a/web/src/features/evals/hooks/useCodeEvalSourceValidation.ts b/web/src/features/evals/hooks/useCodeEvalSourceValidation.tsindex d6f696781b..0d8f05052a 100644--- a/web/src/features/evals/hooks/useCodeEvalSourceValidation.ts+++ b/web/src/features/evals/hooks/useCodeEvalSourceValidation.ts@@ -106,7 +106,7 @@ export function useCodeEvalSourceValidation({.finally(() => {if (isActive) setIsPending(false);});- }, 250);+ }, 300);return () => {isActive = false;@@ -115,8 +115,7 @@ export function useCodeEvalSourceValidation({}, [enabled, reset, sourceCode, sourceCodeLanguage]);return {- isValid:- Boolean(validationResult) && !isPending && !validationResult?.hasErrors,+ isValid: Boolean(validationResult) && !validationResult?.hasErrors,isPending,validationResult,validate,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 dd68df318d..815aaf1169 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@@ -1,125 +1,38 @@-export const TYPESCRIPT_CODE_EVAL_CONTRACT = `/**- * The data Langfuse passes to a code evaluator.- */-type EvaluationContext = {- /**- * The observation selected by the evaluator target.- */+export const TYPESCRIPT_CODE_EVAL_CONTRACT = `type EvaluationContext = {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 NumericScore = ScoreBase & { dataType: "NUMERIC"; value: number };+type BooleanScore = ScoreBase & { dataType: "BOOLEAN"; value: boolean };+type CategoricalScore = ScoreBase & { dataType: "CATEGORICAL"; value: string };+type TextScore = ScoreBase & { dataType: "TEXT"; 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 =