Skip to content

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

feat(evals): pass tool calls to code and LLM-as-a-judge evaluators (#14927)

Tobias Wochingera44d88cbbbf0
diff --git a/fern/apis/server/definition/unstable/commons.yml b/fern/apis/server/definition/unstable/commons.yml
index 9f3437929b..619512002e 100644
--- a/fern/apis/server/definition/unstable/commons.yml
+++ b/fern/apis/server/definition/unstable/commons.yml
@@ -31,7 +31,7 @@ types:
Choose the target first, because it changes both the valid filter columns and the valid variable-mapping sources:
- `observation` evaluates live-ingested observations such as generations, spans, and events.
- It supports mapping from `input`, `output`, and `metadata`.
+ It supports mapping from `input`, `output`, `metadata`, and `tool_calls`.
- `experiment` evaluates live experiment executions and can additionally map `expected_output` and `experiment_item_metadata`.
It currently supports filtering by `datasetId`.
Discover valid dataset IDs with `GET /api/public/v2/datasets`, then use the returned dataset `id` values in your filter.
@@ -58,19 +58,21 @@ types:
Use these values when mapping evaluator prompt variables to live data.
Target-specific rules:
- - `target=observation` supports `input`, `output`, and `metadata`
- - `target=experiment` supports `input`, `output`, `metadata`, `expected_output`, and `experiment_item_metadata`
+ - `target=observation` supports `input`, `output`, `metadata`, and `tool_calls`
+ - `target=experiment` supports `input`, `output`, `metadata`, `tool_calls`, `expected_output`, and `experiment_item_metadata`
Source semantics:
- `input`: the observation or experiment input payload
- `output`: the observation or experiment output payload
- `metadata`: the metadata object for the target. Combine with `jsonPath` when you need one nested field instead of the whole object.
+ - `tool_calls`: the tool calls recorded on the observation, as an array of `{id, name, arguments, type, index}` objects in the order the model emitted them. Combine with `jsonPath` (for example `$[*].name`) to select parts of each call.
- `expected_output`: the experiment item's expected output. Only valid for `target=experiment`.
- `experiment_item_metadata`: the experiment item's metadata object. Only valid for `target=experiment`.
enum:
- input
- output
- metadata
+ - tool_calls
- expected_output
- experiment_item_metadata
@@ -447,8 +449,8 @@ types:
Source field that should populate the prompt variable.
Quick reference:
- - `target=observation`: `input`, `output`, `metadata`
- - `target=experiment`: `input`, `output`, `metadata`, `expected_output`, `experiment_item_metadata`
+ - `target=observation`: `input`, `output`, `metadata`, `tool_calls`
+ - `target=experiment`: `input`, `output`, `metadata`, `tool_calls`, `expected_output`, `experiment_item_metadata`
jsonPath:
type: optional<string>
docs: |
diff --git a/fern/apis/server/definition/unstable/evaluators.yml b/fern/apis/server/definition/unstable/evaluators.yml
index e3c2597098..bfe182f22f 100644
--- a/fern/apis/server/definition/unstable/evaluators.yml
+++ b/fern/apis/server/definition/unstable/evaluators.yml
@@ -150,6 +150,7 @@ service:
- input
- output
- metadata
+ - toolCalls
- experimentItemExpectedOutput
- experimentItemMetadata
sourceCode: |
@@ -217,6 +218,7 @@ service:
- input
- output
- metadata
+ - toolCalls
- experimentItemExpectedOutput
- experimentItemMetadata
sourceCode: |
diff --git a/packages/shared/src/features/evals/observationForEval.test.ts b/packages/shared/src/features/evals/observationForEval.test.ts
new file mode 100644
index 0000000000..9270a89a0e
--- /dev/null
+++ b/packages/shared/src/features/evals/observationForEval.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from "vitest";
+import { zipObservationToolCalls } from "./observationForEval";
+
+describe("zipObservationToolCalls", () => {
+ it("zips ClickHouse parallel arrays into named tool calls with parsed arguments", () => {
+ const result = zipObservationToolCalls({
+ tool_calls: [
+ '{"id":"call_1","arguments":"{\\"query\\":\\"weather\\"}","type":"function","index":0}',
+ '{"id":"toolu_2","arguments":"{\\"city\\":\\"Berlin\\"}","type":"tool_use","index":1}',
+ ],
+ tool_call_names: ["search", "get_weather"],
+ });
+
+ expect(result).toEqual([
+ {
+ id: "call_1",
+ name: "search",
+ arguments: { query: "weather" },
+ type: "function",
+ index: 0,
+ },
+ {
+ id: "toolu_2",
+ name: "get_weather",
+ arguments: { city: "Berlin" },
+ type: "tool_use",
+ index: 1,
+ },
+ ]);
+ });
+
+ it("returns an empty array for observations without tool calls", () => {
+ expect(
+ zipObservationToolCalls({ tool_calls: [], tool_call_names: [] }),
+ ).toEqual([]);
+ });
+
+ it("keeps unparsable arguments as the raw string", () => {
+ const result = zipObservationToolCalls({
+ tool_calls: [
+ '{"id":"call_1","arguments":"not json","type":"","index":0}',
+ ],
+ tool_call_names: ["search"],
+ });
+
+ expect(result[0]?.arguments).toBe("not json");
+ });
+
+ it("falls back to defaults when an entry is missing or malformed", () => {
+ const result = zipObservationToolCalls({
+ tool_calls: ["not json at all"],
+ tool_call_names: ["search", "unmatched"],
+ });
+
+ expect(result).toEqual([
+ { id: "", name: "search", arguments: {}, type: "", index: 0 },
+ { id: "", name: "unmatched", arguments: {}, type: "", index: 0 },
+ ]);
+ });
+
+ it("accepts entries that are already objects", () => {
+ const result = zipObservationToolCalls({
+ tool_calls: [
+ { id: "call_1", arguments: { a: 1 }, type: "function", index: 2 },
+ ],
+ tool_call_names: ["search"],
+ });
+
+ expect(result).toEqual([
+ {
+ id: "call_1",
+ name: "search",
+ arguments: { a: 1 },
+ type: "function",
+ index: 2,
+ },
+ ]);
+ });
+});
diff --git a/packages/shared/src/features/evals/observationForEval.ts b/packages/shared/src/features/evals/observationForEval.ts
index a33e649af1..ab031bf331 100644
--- a/packages/shared/src/features/evals/observationForEval.ts
+++ b/packages/shared/src/features/evals/observationForEval.ts
@@ -6,6 +6,7 @@ import { metadataArraysToRecord } from "../../server/utils/metadata_conversion";
import { SingleValueOption } from "../../tableDefinitions";
import { ColumnDefinition } from "../../tableDefinitions";
import { formatColumnOptions } from "../../tableDefinitions/typeHelpers";
+import { parseJsonIfString } from "../../utils/json";
const flexibleUsageCostSchema = z.record(
z.string(),
@@ -74,6 +75,68 @@ export const observationForEvalSchema = z.object({
export type ObservationForEval = z.infer<typeof observationForEvalSchema>;
+/**
+ * Self-contained tool call shape handed to evaluators. Rebuilt from the
+ * ClickHouse storage layout, which keeps names in a parallel array
+ * (`tool_call_names`) so ClickHouse can filter without JSON parsing.
+ */
+export const toolCallForEvalSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ arguments: z.unknown(),
+ type: z.string(),
+ index: z.number(),
+});
+
+export type ToolCallForEval = z.infer<typeof toolCallForEvalSchema>;
+
+/**
+ * zipObservationToolCalls for camelCase records with loosely typed arrays
+ * (tRPC/domain shapes: events batchIO, legacy observations.byId). Malformed
+ * names map to "" instead of being dropped — filtering would shift the zip
+ * and misattribute every later call's name.
+ */
+export function zipToolCallsFromRecord(record: object): ToolCallForEval[] {
+ const { toolCalls, toolCallNames } = record as {
+ toolCalls?: unknown;
+ toolCallNames?: unknown;
+ };
+
+ return zipObservationToolCalls({
+ tool_calls: Array.isArray(toolCalls) ? toolCalls : [],
+ tool_call_names: Array.isArray(toolCallNames)
+ ? toolCallNames.map((name) => (typeof name === "string" ? name : ""))
+ : [],
+ });
+}
+
+/**
+ * Zips the parallel arrays back into named tool call objects.
+ * `tool_call_names` is authoritative for count and order: ingestion writes
+ * both arrays in lockstep (`convertCallsToArrays`), and stored entries carry
+ * no name. `arguments` arrives double-encoded (a JSON string inside the entry
+ * JSON) and is parsed to an object; unparsable values stay raw strings.
+ */
+export function zipObservationToolCalls(
+ observation: Pick<ObservationForEval, "tool_calls" | "tool_call_names">,
+): ToolCallForEval[] {
+ return observation.tool_call_names.map((name, i) => {
+ const parsed = parseJsonIfString(observation.tool_calls[i]);
+ const entry =
+ typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
+ ? (parsed as Record<string, unknown>)
+ : {};
+
+ return {
+ id: typeof entry.id === "string" ? entry.id : "",
+ name,
+ arguments: parseJsonIfString(entry.arguments) ?? {},
+ type: typeof entry.type === "string" ? entry.type : "",
+ index: typeof entry.index === "number" ? entry.index : 0,
+ };
+ });
+}
+
export function convertEventRecordToObservationForEval(
record: EventRecordBaseType,
): ObservationForEval {
@@ -127,6 +190,7 @@ export type ObservationEvalMappingColumnInternal = keyof Pick<
| "input"
| "output"
| "metadata"
+ | "tool_calls"
| "experiment_item_expected_output"
| "experiment_item_metadata"
>;
@@ -143,7 +207,29 @@ export interface ObservationEvalVariableColumn {
internal: ObservationEvalMappingColumnInternal;
}
-export const eventTargetEvalVariableColumns: ObservationEvalVariableColumn[] = [
+/**
+ * Canonical variable set for code evaluators — one entry per experiment
+ * target column below (the id annotation on the column arrays pins them to
+ * this list). Web synthesizes rule mappings from it
+ * (getCodeEvalVariableMapping) and buildCodeEvalPayload (codeEvalExecution)
+ * places each variable in the evaluator payload — see the
+ * CODE_EVAL_PAYLOAD_SECTION_BY_VARIABLE tripwire in codeEvalDispatcherTypes.
+ */
+export const CODE_EVAL_TEMPLATE_VARIABLES = [
+ "input",
+ "output",
+ "metadata",
+ "toolCalls",
+ "experimentItemExpectedOutput",
+ "experimentItemMetadata",
+] as const;
+
+export type CodeEvalTemplateVariable =
+ (typeof CODE_EVAL_TEMPLATE_VARIABLES)[number];
+
+export const eventTargetEvalVariableColumns: (ObservationEvalVariableColumn & {
+ id: CodeEvalTemplateVariable;
+})[] = [
{
id: "input",
name: "Input",
@@ -163,25 +249,33 @@ export const eventTargetEvalVariableColumns: ObservationEvalVariableColumn[] = [
type: "stringObject",
internal: "metadata",
},
+ {
+ id: "toolCalls",
+ name: "Tool Calls",
+ description:
+ "Tool calls recorded on the observation ({id, name, arguments, type, index})",
+ internal: "tool_calls",
+ },
];
-export const experimentTargetEvalVariableColumns: ObservationEvalVariableColumn[] =
- [
- ...eventTargetEvalVariableColumns,
- {
- id: "experimentItemExpectedOutput",
- name: "Expected Output",
- description: "Expected output from experiment item",
- internal: "experiment_item_expected_output",
- },
- {
- id: "experimentItemMetadata",
- name: "Experiment Item Metadata",
- description: "Metadata from experiment item",
- type: "stringObject",
- internal: "experiment_item_metadata",
- },
- ];
+export const experimentTargetEvalVariableColumns: (ObservationEvalVariableColumn & {
+ id: CodeEvalTemplateVariable;
+})[] = [
+ ...eventTargetEvalVariableColumns,
+ {
+ id: "experimentItemExpectedOutput",
+ name: "Expected Output",
+ description: "Expected output from experiment item",
+ internal: "experiment_item_expected_output",
+ },
+ {
+ id: "experimentItemMetadata",
+ name: "Experiment Item Metadata",
+ description: "Metadata from experiment item",
+ type: "stringObject",
+ internal: "experiment_item_metadata",
+ },
+];
/**
* Columns available for variable extraction in observation-based evals.
@@ -194,52 +288,6 @@ export const observationEvalVariableColumns: ObservationEvalVariableColumn[] = [
...experimentTargetEvalVariableColumns,
];
-export const availableObservationEvalVariableColumns = [
- ...observationEvalVariableColumns,
- {
- id: "toolCalls", // Needs to match the `ID` from `mapObservationsTable.ts`
- name: "Tool Calls",
- description: "Tool calls",
- internal: "tool_calls",
- },
- {
- id: "toolDefinitions",
- name: "Tool Definitions",
- description: "Tool definitions",
- internal: "tool_definitions",
- },
- {
- id: "toolCallNames",
- name: "Tool Call Names",
- description: "Tool call names",
- internal: "tool_call_names",
- },
- {
- id: "providedModelName",
- name: "Model",
- description: "Model",
- internal: "provided_model_name",
- },
- {
- id: "modelParameters",
- name: "Model Parameters",
- description: "Model parameters",
- internal: "model_parameters",
- },
- {
- id: "usageDetails",
- name: "Usage Details",
- description: "Usage details",
- internal: "usage_details",
- },
- {
- id: "costDetails",
- name: "Cost Details",
- description: "Cost details",
- internal: "cost_details",
- },
-];
-
type ObservationEvalColumnDef = ColumnDefinition & {
internal: ObservationEvalFilterColumnInternal;
};
diff --git a/packages/shared/src/server/evals/awsLambdaCodeEvalDispatcher.test.ts b/packages/shared/src/server/evals/awsLambdaCodeEvalDispatcher.test.ts
index ce31fb050d..3bdaca21bc 100644
--- a/packages/shared/src/server/evals/awsLambdaCodeEvalDispatcher.test.ts
+++ b/packages/shared/src/server/evals/awsLambdaCodeEvalDispatcher.test.ts
@@ -41,6 +41,7 @@ const baseInput: DispatchInput = {
input: null,
output: null,
metadata: null,
+ toolCalls: [],
},
},
};
diff --git a/packages/shared/src/server/evals/codeEvalDispatcherTypes.ts b/packages/shared/src/server/evals/codeEvalDispatcherTypes.ts
index f9061f8e0a..bec59d4324 100644
--- a/packages/shared/src/server/evals/codeEvalDispatcherTypes.ts
+++ b/packages/shared/src/server/evals/codeEvalDispatcherTypes.ts
@@ -1,5 +1,9 @@
import { z } from "zod";
import { ScoreDataTypeEnum, TEXT_SCORE_MAX_LENGTH } from "../../domain/scores";
+import type {
+ CodeEvalTemplateVariable,
+ ToolCallForEval,
+} from "../../features/evals/observationForEval";
export const CODE_EVAL_SOURCE_MAX_BYTES = 256 * 1024;
export const CODE_EVAL_DISPATCH_PAYLOAD_MAX_BYTES = 5.5 * 1024 * 1024;
@@ -30,6 +34,7 @@ export type CodeEvalPayload = {
input: unknown;
output: unknown;
metadata: unknown;
+ toolCalls: ToolCallForEval[];
};
experiment?: {
itemExpectedOutput: unknown;
@@ -37,6 +42,21 @@ export type CodeEvalPayload = {
};
};
+/**
+ * Compile-time lockstep between the canonical code-eval variable list and the
+ * payload contract: adding a variable to CODE_EVAL_TEMPLATE_VARIABLES fails
+ * here until it is assigned a payload section — the reminder to extend
+ * CodeEvalPayload and buildCodeEvalPayload (codeEvalExecution.ts) with it.
+ */
+export const CODE_EVAL_PAYLOAD_SECTION_BY_VARIABLE = {
+ input: "observation",
+ output: "observation",
+ metadata: "observation",
+ toolCalls: "observation",
+ experimentItemExpectedOutput: "experiment",
+ experimentItemMetadata: "experiment",
+} as const satisfies Record<CodeEvalTemplateVariable, keyof CodeEvalPayload>;
+
export type DispatchInput = {
scope: CodeEvalScope;
runtime: { language: CodeEvalRuntimeLanguage };
diff --git a/packages/shared/src/server/evals/codeEvalExecution.ts b/packages/shared/src/server/evals/codeEvalExecution.ts
index 0529d1657d..7943bc4970 100644
--- a/packages/shared/src/server/evals/codeEvalExecution.ts
+++ b/packages/shared/src/server/evals/codeEvalExecution.ts
@@ -23,7 +23,9 @@ import {
type CodeEvalScoreWithName,
type DispatchResult,
} from "./codeEvalDispatcherTypes";
+import { z } from "zod";
import type { ExtractedVariable } from "./extractObservationVariables";
+import { toolCallForEvalSchema } from "../../features/evals/observationForEval";
const INTERNAL_CODE_EVAL_ERROR_MESSAGE = "An internal error occurred";
const INTERNAL_CODE_EVAL_ERROR_CODE = "INTERNAL_ERROR" as const;
@@ -109,11 +111,28 @@ function buildCodeEvalPayload(params: {
const byName = new Map(
params.extractedVariables.map((v) => [v.var, v.value]),
);
+ // Extraction zips tool calls into named objects (extractObservationVariables).
+ // Configs saved before "toolCalls" entered the code eval mapping extract
+ // nothing for it, so those evaluators see empty arrays. Parse rather than
+ // cast: a mapping row with a jsonSelector on toolCalls (or a corrupted row)
+ // would otherwise ship wrong-shaped elements into user evaluator code.
+ const rawToolCalls = byName.get("toolCalls");
+ const parsedToolCalls = z
+ .array(toolCallForEvalSchema)
+ .safeParse(rawToolCalls ?? []);
+ if (!parsedToolCalls.success) {
+ logger.warn(
+ "Extracted toolCalls variable is not ToolCallForEval[]; evaluator receives an empty array",
+ { error: parsedToolCalls.error.message },
+ );
+ }
+ const toolCalls = parsedToolCalls.success ? parsedToolCalls.data : [];
const payload: CodeEvalPayload = {
observation: {
input: byName.get("input") ?? null,
output: byName.get("output") ?? null,
metadata: byName.get("metadata") ?? null,
+ toolCalls,
},
};
diff --git a/packages/shared/src/server/evals/extractObservationVariables.ts b/packages/shared/src/server/evals/extractObservationVariables.ts
index 28452ed78c..3be09134db 100644
--- a/packages/shared/src/server/evals/extractObservationVariables.ts
+++ b/packages/shared/src/server/evals/extractObservationVariables.ts
@@ -1,5 +1,7 @@
import {
observationEvalVariableColumns,
+ zipObservationToolCalls,
+ type ObservationEvalMappingColumnInternal,
type ObservationEvalVariableColumn,
type ObservationForEval,
} from "../../features/evals/observationForEval";
@@ -24,6 +26,14 @@ export function extractObservationVariables(
const { observation, variableMapping } = params;
const variables: ExtractedVariable[] = [];
+ // Tool calls are stored as name-less JSON strings with names in a parallel
+ // array; zip them into self-contained objects so JSONPath selectors like
+ // $[*].name work and prompts see named calls.
+ const resolveFieldValue = (internal: ObservationEvalMappingColumnInternal) =>
+ internal === "tool_calls"
+ ? zipObservationToolCalls(observation)
+ : observation[internal];
+
const parsedFields = new Map<string, unknown>();
for (const mapping of variableMapping) {
const fieldId = mapping.selectedColumnId;
@@ -31,10 +41,19 @@ export function extractObservationVariables(
const internal = columns.find((col) => col.id === fieldId)?.internal;
if (internal && observation[internal] !== undefined) {
+ const fieldValue = resolveFieldValue(internal);
+ // Zipped tool calls are fully parsed already (arguments via
+ // parseJsonIfString); deepParseJson would only coerce top-level id/name/
+ // type strings that happen to be JSON literals ("true"/"null") into
+ // primitives, corrupting the calls.
+ if (internal === "tool_calls") {
+ parsedFields.set(fieldId, fieldValue);
+ continue;
+ }
try {
- parsedFields.set(fieldId, deepParseJson(observation[internal]));
+ parsedFields.set(fieldId, deepParseJson(fieldValue));
} catch {
- parsedFields.set(fieldId, observation[internal]);
+ parsedFields.set(fieldId, fieldValue);
}
}
}
@@ -57,7 +76,7 @@ export function extractObservationVariables(
const fieldValue = parsedFields.has(mapping.selectedColumnId)
? parsedFields.get(mapping.selectedColumnId)
- : observation[internal];
+ : resolveFieldValue(internal);
const { value, error } = extractValueFromObject(
{ [mapping.selectedColumnId]: fieldValue },
diff --git a/packages/shared/src/server/ingestion/extractToolsBackend.ts b/packages/shared/src/server/ingestion/extractToolsBackend.ts
index 44dbbeb11d..763d8eb2c8 100644
--- a/packages/shared/src/server/ingestion/extractToolsBackend.ts
+++ b/packages/shared/src/server/ingestion/extractToolsBackend.ts
@@ -2,6 +2,25 @@ import { z } from "zod";
type IngestionJsonValue = string | object | number | boolean | null | undefined;
+/**
+ * Parse input that might be a JSON string or already an object.
+ *
+ * Deliberately native JSON.parse, not the shared parseJsonIfString: this runs
+ * over full observation input/output for every ingested span, and the shared
+ * helper's lossless-json slow path triggers on any digit followed by e/E
+ * (most UUIDs) or 13+ consecutive digits (ms timestamps).
+ */
+function parseIfString(data: unknown): unknown {
+ if (typeof data === "string") {
+ try {
+ return JSON.parse(data);
+ } catch {
+ return data; // Return original if not valid JSON
+ }
+ }
+ return data;
+}
+
/**
* ClickHouse storage schema for tool definitions.
*
@@ -381,20 +400,6 @@ function extractToolCallsFromMessage(
}
}
-/**
- * Parse input that might be a JSON string or already an object.
- */
-function parseIfString(data: unknown): unknown {
- if (typeof data === "string") {
- try {
- return JSON.parse(data);
- } catch {
- return data; // Return original if not valid JSON
- }
- }
- return data;
-}
-
function isPlainRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index ff06ed9a12..ab8b793e9e 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -129,18 +129,32 @@ import {
import { tracesTableCols } from "../../tableDefinitions/tracesTable";
import { parseMetadataCHRecordToDomain } from "../utils/metadata_conversion";
-type EventBatchIOStringOutput = {
+export type EventBatchIOStringOutput = {
id: string;
input: string | null;
output: string | null;
metadata: MetadataDomain;
};
-type EventBatchIOWithExperimentOutput = EventBatchIOStringOutput & {
+/** Raw ClickHouse storage shape: name-less JSON strings, names in the parallel toolCallNames array. */
+export type EventBatchIOToolCallFields = {
+ toolCalls: string[];
+ toolCallNames: string[];
+};
+
+export type EventBatchIOWithExperimentOutput = EventBatchIOStringOutput & {
experimentItemExpectedOutput: string | null;
experimentItemMetadata: MetadataDomain;
};
+export type EventBatchIOResult<
+ TIncludeExperiment extends boolean,
+ TIncludeToolCalls extends boolean,
+> = (TIncludeExperiment extends true
+ ? EventBatchIOWithExperimentOutput
+ : EventBatchIOStringOutput) &
+ (TIncludeToolCalls extends true ? EventBatchIOToolCallFields : object);
+
const BATCH_IO_STRING_RENDERING_PROPS: RenderingProps = {
// Batch I/O truncation is handled in SQL via leftUTF8 for performance.
truncated: false,
@@ -2489,6 +2503,7 @@ export const deleteEventsOlderThanDays = async (
export const getObservationsBatchIOFromEventsTable = async <
TIncludeExperiment extends boolean = false,
+ TIncludeToolCalls extends boolean = false,
>(opts: {
projectId: string;
observations: Array<{
@@ -2499,12 +2514,10 @@ export const getObservationsBatchIOFromEventsTable = async <
maxStartTime: Date;
truncated?: boolean; // Default true for performance, false for full data
includeExperimentFields?: TIncludeExperiment;
+ /** Opt-in: tool-call arrays can be large; only eval consumers need them. */
+ includeToolCallFields?: TIncludeToolCalls;
}): Promise<
- Array<
- TIncludeExperiment extends true
- ? EventBatchIOWithExperimentOutput
- : EventBatchIOStringOutput
- >
+ Array<EventBatchIOResult<TIncludeExperiment, TIncludeToolCalls>>
> => {
if (opts.observations.length === 0) {
return [];
@@ -2534,6 +2547,12 @@ export const getObservationsBatchIOFromEventsTable = async <
mapFromArrays(arrayReverse(e.experiment_item_metadata_names), arrayReverse(e.experiment_item_metadata_values)) as experiment_item_metadata,
`
: "";
+ const toolCallFieldsSelect = opts.includeToolCallFields
+ ? `
+ e.tool_calls as tool_calls,
+ e.tool_call_names as tool_call_names,
+ `
+ : "";
const query = `
SELECT
@@ -2541,6 +2560,7 @@ export const getObservationsBatchIOFromEventsTable = async <
${inputSelect},
${outputSelect},
${experimentFieldsSelect}
+ ${toolCallFieldsSelect}
mapFromArrays(arrayReverse(e.metadata_names), arrayReverse(e.metadata_values)) as metadata
FROM ${tableName} e
WHERE e.project_id = {projectId: String}
@@ -2555,6 +2575,8 @@ export const getObservationsBatchIOFromEventsTable = async <
input: string | null;
output: string | null;
metadata: Record<string, string>;
+ tool_calls?: string[];
+ tool_call_names?: string[];
experiment_item_expected_output?: string | null;
experiment_item_metadata?: Record<string, string>;
}>({
@@ -2576,6 +2598,12 @@ export const getObservationsBatchIOFromEventsTable = async <
output: applyBatchIOStringRendering(r.output),
metadata:
r.metadata !== undefined ? parseMetadataCHRecordToDomain(r.metadata) : {},
+ ...(opts.includeToolCallFields
+ ? {
+ toolCalls: r.tool_calls ?? [],
+ toolCallNames: r.tool_call_names ?? [],
+ }
+ : {}),
...(opts.includeExperimentFields
? {
experimentItemExpectedOutput: r.experiment_item_expected_output,
@@ -2585,11 +2613,7 @@ export const getObservationsBatchIOFromEventsTable = async <
: {},
}
: {}),
- })) as Array<
- TIncludeExperiment extends true
- ? EventBatchIOWithExperimentOutput
- : EventBatchIOStringOutput
- >;
+ })) as Array<EventBatchIOResult<TIncludeExperiment, TIncludeToolCalls>>;
};
/**
diff --git a/packages/shared/src/utils/chatml/helpers.ts b/packages/shared/src/utils/chatml/helpers.ts
index 2947ae9ee4..94d8909ea1 100644
--- a/packages/shared/src/utils/chatml/helpers.ts
+++ b/packages/shared/src/utils/chatml/helpers.ts
@@ -1,3 +1,5 @@
+import { parseJsonIfString as parseIfString } from "../json";
+
export function removeNullFields(obj: unknown): Record<string, unknown> {
if (!obj || typeof obj !== "object") return {};
@@ -98,16 +100,6 @@ export function getNestedProperty(
return current;
}
-function parseIfString(value: unknown): unknown {
- if (typeof value !== "string") return value;
-
- try {
- return JSON.parse(value);
- } catch {
- return value;
- }
-}
-
function parseArrayIfString(value: unknown): unknown[] | undefined {
if (Array.isArray(value)) return value;
const parsed = parseIfString(value);
diff --git a/packages/shared/src/utils/json.ts b/packages/shared/src/utils/json.ts
index 24f98cd247..d231f5356c 100644
--- a/packages/shared/src/utils/json.ts
+++ b/packages/shared/src/utils/json.ts
@@ -440,3 +440,11 @@ export const parseJsonPrioritised = (
return json;
}
};
+
+/**
+ * Parses a value that may be a JSON string. Non-strings and unparsable
+ * strings pass through unchanged; parsing preserves big-integer precision
+ * (parseJsonPrioritised).
+ */
+export const parseJsonIfString = (value: unknown): unknown =>
+ typeof value === "string" ? parseJsonPrioritised(value) : value;
diff --git a/scripts/code-eval-runners/python/code_based_eval_handler.py b/scripts/code-eval-runners/python/code_based_eval_handler.py
index 8e80a80a66..d4b4b3f551 100644
--- a/scripts/code-eval-runners/python/code_based_eval_handler.py
+++ b/scripts/code-eval-runners/python/code_based_eval_handler.py
@@ -6,11 +6,32 @@ from dataclasses import dataclass, field
from typing import Any
+@dataclass
+class ToolCall:
+ id: str = ""
+ name: str = ""
+ arguments: Any = None
+ type: str = ""
+ index: int = 0
+
+ @classmethod
+ def from_payload(cls, raw: Any):
+ entry = raw if isinstance(raw, dict) else {}
+ return cls(
+ id=entry.get("id") or "",
+ name=entry.get("name") or "",
+ arguments=entry.get("arguments"),
+ type=entry.get("type") or "",
+ index=entry.get("index") or 0,
+ )
+
+
@dataclass
class ObservationContext:
input: Any = None
output: Any = None
metadata: Any = None
+ tool_calls: list[ToolCall] = field(default_factory=list)
@dataclass
@@ -33,6 +54,10 @@ class EvaluationContext:
input=observation.get("input"),
output=observation.get("output"),
metadata=observation.get("metadata"),
+ tool_calls=[
+ ToolCall.from_payload(call)
+ for call in observation.get("toolCalls") or []
+ ],
),
experiment=ExperimentContext(
item_expected_output=experiment.get("itemExpectedOutput"),
@@ -77,6 +102,7 @@ def handler(event, context):
"EvaluationContext": EvaluationContext,
"EvaluationResult": EvaluationResult,
"Score": Score,
+ "ToolCall": ToolCall,
}
try:
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index a58867f47a..96da15dbfe 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -13205,7 +13205,7 @@ components:
- `observation` evaluates live-ingested observations such as
generations, spans, and events.
- It supports mapping from `input`, `output`, and `metadata`.
+ It supports mapping from `input`, `output`, `metadata`, and `tool_calls`.
- `experiment` evaluates live experiment executions and can additionally
map `expected_output` and `experiment_item_metadata`.
It currently supports filtering by `datasetId`.
@@ -13234,6 +13234,7 @@ components:
- input
- output
- metadata
+ - tool_calls
- expected_output
- experiment_item_metadata
description: >-
@@ -13245,10 +13246,11 @@ components:
Target-specific rules:
- - `target=observation` supports `input`, `output`, and `metadata`
+ - `target=observation` supports `input`, `output`, `metadata`, and
+ `tool_calls`
- `target=experiment` supports `input`, `output`, `metadata`,
- `expected_output`, and `experiment_item_metadata`
+ `tool_calls`, `expected_output`, and `experiment_item_metadata`
Source semantics:
@@ -13260,6 +13262,11 @@ components:
- `metadata`: the metadata object for the target. Combine with
`jsonPath` when you need one nested field instead of the whole object.
+ - `tool_calls`: the tool calls recorded on the observation, as an array
+ of `{id, name, arguments, type, index}` objects in the order the model
+ emitted them. Combine with `jsonPath` (for example `$[*].name`) to
+ select parts of each call.
+
- `expected_output`: the experiment item's expected output. Only valid
for `target=experiment`.
@@ -13802,9 +13809,9 @@ components:
Quick reference:
- - `target=observation`: `input`, `output`, `metadata`
+ - `target=observation`: `input`, `output`, `metadata`, `tool_calls`
- - `target=experiment`: `input`, `output`, `metadata`,
+ - `target=experiment`: `input`, `output`, `metadata`, `tool_calls`,
`expected_output`, `experiment_item_metadata`
jsonPath:
type: string
diff --git a/web/src/__tests__/server/evals-trpc.servertest.ts b/web/src/__tests__/server/evals-trpc.servertest.ts
index db231a5622..654fe064aa 100644
--- a/web/src/__tests__/server/evals-trpc.servertest.ts
+++ b/web/src/__tests__/server/evals-trpc.servertest.ts
@@ -43,7 +43,8 @@ import {
EvalTargetObject,
EvaluatorBlockReason,
} from "@langfuse/shared";
-import { CODE_EVAL_TEMPLATE_VARIABLES } from "@/src/features/evals/utils/code-eval-template-utils";
+import { CODE_EVAL_TEMPLATE_VARIABLES } from "@langfuse/shared";
+import { getCodeEvalVariableMapping } from "@/src/features/evals/utils/code-eval-template-utils";
import type { Session } from "next-auth";
beforeEach(() => {
@@ -560,6 +561,63 @@ describe("evals trpc", () => {
"This code evaluator language is not supported by the configured dispatcher.",
);
});
+
+ it("adopts the canonical mapping on re-pointed code-eval rules when saving a new version", async () => {
+ const { project, caller } = await prepare();
+ const templateName = `code-template-repoint-${project.id}`;
+
+ const templateV1 = await prisma.evalTemplate.create({
+ data: {
+ projectId: project.id,
+ name: templateName,
+ version: 1,
+ type: EvalTemplateType.CODE,
+ prompt: null,
+ outputDefinition: undefined,
+ sourceCode:
+ 'function evaluate() { return { scores: [{ name: "s", value: 1 }] }; }',
+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.TYPESCRIPT,
+ },
+ });
+
+ // Stored snapshot predating a canonical-variable addition (toolCalls).
+ const staleMapping = getCodeEvalVariableMapping().filter(
+ (mapping) => mapping.templateVariable !== "toolCalls",
+ );
+ const jobConfig = await prisma.jobConfiguration.create({
+ data: {
+ projectId: project.id,
+ jobType: "EVAL",
+ evalTemplateId: templateV1.id,
+ scoreName: "code-score",
+ filter: [],
+ targetObject: EvalTargetObject.EVENT,
+ variableMapping: staleMapping,
+ sampling: 1,
+ delay: 0,
+ status: "ACTIVE",
+ },
+ });
+
+ const newVersion = await caller.evals.createTemplate({
+ projectId: project.id,
+ name: templateName,
+ intent: "new-version",
+ sourceTemplateId: templateV1.id,
+ type: EvalTemplateType.CODE,
+ sourceCode:
+ 'function evaluate(ctx) { return { scores: [{ name: "s", value: ctx.observation.toolCalls.length }] }; }',
+ sourceCodeLanguage: EvalTemplateSourceCodeLanguage.TYPESCRIPT,
+ });
+
+ const updatedConfig = await prisma.jobConfiguration.findUniqueOrThrow({
+ where: { id: jobConfig.id },
+ });
+ expect(updatedConfig.evalTemplateId).toBe(newVersion.template.id);
+ expect(updatedConfig.variableMapping).toEqual(
+ getCodeEvalVariableMapping(),
+ );
+ });
});
describe("evals.createJob", () => {
diff --git a/web/src/__tests__/server/repositories/event-repository.servertest.ts b/web/src/__tests__/server/repositories/event-repository.servertest.ts
index d7aab13067..10c890e779 100644
--- a/web/src/__tests__/server/repositories/event-repository.servertest.ts
+++ b/web/src/__tests__/server/repositories/event-repository.servertest.ts
@@ -3390,6 +3390,56 @@ describe("Clickhouse Events Repository Test", () => {
expect(result).toBeDefined();
expect(result.length).toBe(0);
});
+
+ it("should fetch tool call fields only when includeToolCallFields is set", async () => {
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const nowMicro = Date.now() * 1000;
+ const timestamp = new Date(nowMicro / 1000);
+ const storedToolCall = JSON.stringify({
+ id: "call_1",
+ arguments: JSON.stringify({ city: "Berlin" }),
+ type: "function",
+ index: 0,
+ });
+
+ await createEventsCh([
+ createEvent({
+ id: observationId,
+ span_id: observationId,
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "test-tool-calls",
+ input: "tool call input",
+ output: "tool call output",
+ tool_calls: [storedToolCall],
+ tool_call_names: ["get_weather"],
+ start_time: nowMicro,
+ }),
+ ]);
+
+ const baseParams = {
+ projectId,
+ observations: [{ id: observationId, traceId }],
+ minStartTime: timestamp,
+ maxStartTime: timestamp,
+ };
+
+ const withoutToolCalls =
+ await getObservationsBatchIOFromEventsTable(baseParams);
+ expect(withoutToolCalls.length).toBe(1);
+ expect(withoutToolCalls[0]).not.toHaveProperty("toolCalls");
+ expect(withoutToolCalls[0]).not.toHaveProperty("toolCallNames");
+
+ const withToolCalls = await getObservationsBatchIOFromEventsTable({
+ ...baseParams,
+ includeToolCallFields: true,
+ });
+ expect(withToolCalls.length).toBe(1);
+ expect(withToolCalls[0]?.toolCalls).toEqual([storedToolCall]);
+ expect(withToolCalls[0]?.toolCallNames).toEqual(["get_weather"]);
+ });
});
maybe("getLatestSdkVersionInfoFromEvents", () => {
diff --git a/web/src/__tests__/server/unit/code-eval-python-runner-contract.servertest.ts b/web/src/__tests__/server/unit/code-eval-python-runner-contract.servertest.ts
new file mode 100644
index 0000000000..2b7cb04129
--- /dev/null
+++ b/web/src/__tests__/server/unit/code-eval-python-runner-contract.servertest.ts
@@ -0,0 +1,34 @@
+import { readFileSync } from "fs";
+import path from "path";
+import { describe, expect, it } from "vitest";
+import { PYTHON_CODE_EVAL_CONTRACT } from "@/src/features/evals/utils/code-eval-template-starter-examples";
+
+// The Python Lambda runner reconstructs the payload into dataclasses (unlike
+// the Node runner, which passes it through verbatim), so the contract shown
+// in the editor can silently drift from what deployed evaluator code sees.
+// Pin every dataclass field block of the displayed contract to the runner
+// source: the runner may extend a block (from_payload helpers, defaults), but
+// each block's field section must appear verbatim.
+describe("python code eval runner contract", () => {
+ it("contains every dataclass block of the displayed contract verbatim", () => {
+ const runnerSource = readFileSync(
+ path.join(
+ __dirname,
+ "../../../../..",
+ "scripts/code-eval-runners/python/code_based_eval_handler.py",
+ ),
+ "utf8",
+ );
+
+ const dataclassBlocks = PYTHON_CODE_EVAL_CONTRACT.split(/\n\n+/)
+ .map((block) => block.trim())
+ .filter((block) => block.startsWith("@dataclass"));
+
+ // ToolCall, ObservationContext, ExperimentContext, EvaluationContext,
+ // Score, EvaluationResult
+ expect(dataclassBlocks).toHaveLength(6);
+ for (const block of dataclassBlocks) {
+ expect(runnerSource).toContain(block);
+ }
+ });
+});
diff --git a/web/src/__tests__/server/unit/unstable-evals-contract.servertest.ts b/web/src/__tests__/server/unit/unstable-evals-contract.servertest.ts
index 590833c6a5..ac4aba2c9b 100644
--- a/web/src/__tests__/server/unit/unstable-evals-contract.servertest.ts
+++ b/web/src/__tests__/server/unit/unstable-evals-contract.servertest.ts
@@ -28,10 +28,8 @@ import {
PUBLIC_EVALUATOR_TYPE_CODE,
PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
} from "@/src/features/public-api/types/unstable-public-evals-contract";
-import {
- CODE_EVAL_TEMPLATE_VARIABLES,
- getCodeEvalVariableMapping,
-} from "@/src/features/evals/utils/code-eval-template-utils";
+import { CODE_EVAL_TEMPLATE_VARIABLES } from "@langfuse/shared";
+import { getCodeEvalVariableMapping } from "@/src/features/evals/utils/code-eval-template-utils";
const numericOutputDefinition = createNumericEvalOutputDefinition({
reasoningDescription: "Why the score was assigned",
@@ -471,6 +469,83 @@ describe("unstable public eval adapters", () => {
]);
});
+ it("reads a toolCalls mapping column id as the tool_calls source", () => {
+ const evaluationRule = toApiEvaluationRule({
+ id: "ceval_123",
+ projectId: "project_123",
+ evalTemplateId: "tmpl_project_v2",
+ scoreName: "tool_call_check",
+ targetObject: EvalTargetObject.EVENT,
+ filter: [],
+ variableMapping: [
+ {
+ templateVariable: "calls",
+ selectedColumnId: "toolCalls",
+ jsonSelector: "$[*].name",
+ },
+ ],
+ sampling: 1,
+ status: JobConfigState.ACTIVE,
+ blockedAt: null,
+ blockReason: null,
+ blockMessage: null,
+ createdAt: new Date("2026-03-30T08:00:00.000Z"),
+ updatedAt: new Date("2026-03-30T08:00:00.000Z"),
+ evalTemplate: {
+ id: "tmpl_project_v2",
+ projectId: "project_123",
+ name: "Tool call check",
+ vars: ["calls"],
+ prompt: "Judge {{calls}}",
+ },
+ } as unknown as StoredPublicEvaluationRuleConfig);
+
+ expect(evaluationRule.mapping).toEqual([
+ {
+ variable: "calls",
+ source: "tool_calls",
+ jsonPath: "$[*].name",
+ },
+ ]);
+ });
+
+ it("rejects a stored snake_case tool_calls mapping column id as corrupted", () => {
+ // Deliberate asymmetry with expected_output: no legacy snake_case rows
+ // exist for tool calls, so an accidental "tool_calls" write must surface
+ // at the corrupted-mapping boundary instead of being absorbed.
+ expect(() =>
+ toApiEvaluationRule({
+ id: "ceval_123",
+ projectId: "project_123",
+ evalTemplateId: "tmpl_project_v2",
+ scoreName: "tool_call_check",
+ targetObject: EvalTargetObject.EVENT,
+ filter: [],
+ variableMapping: [
+ {
+ templateVariable: "calls",
+ selectedColumnId: "tool_calls",
+ jsonSelector: null,
+ },
+ ],
+ sampling: 1,
+ status: JobConfigState.ACTIVE,
+ blockedAt: null,
+ blockReason: null,
+ blockMessage: null,
+ createdAt: new Date("2026-03-30T08:00:00.000Z"),
+ updatedAt: new Date("2026-03-30T08:00:00.000Z"),
+ evalTemplate: {
+ id: "tmpl_project_v2",
+ projectId: "project_123",
+ name: "Tool call check",
+ vars: ["calls"],
+ prompt: "Judge {{calls}}",
+ },
+ } as unknown as StoredPublicEvaluationRuleConfig),
+ ).toThrow("Evaluation rule mapping is corrupted");
+ });
+
it("rejects invalid static filter option values", () => {
expectUnstablePublicApiError(
() =>
@@ -563,6 +638,33 @@ describe("unstable public eval adapters", () => {
);
});
+ it("accepts tool_calls mappings for both targets", () => {
+ for (const target of ["observation", "experiment"] as const) {
+ const writeModel = toJobConfigurationInput({
+ input: {
+ name: "tool_call_check",
+ target,
+ enabled: true,
+ sampling: 1,
+ filter: [],
+ mapping: [
+ { variable: "calls", source: "tool_calls", jsonPath: "$[*].name" },
+ ],
+ },
+ evaluatorVariables: ["calls"],
+ evaluatorType: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
+ });
+
+ expect(writeModel.variableMapping).toEqual([
+ {
+ templateVariable: "calls",
+ selectedColumnId: "toolCalls",
+ jsonSelector: "$[*].name",
+ },
+ ]);
+ }
+ });
+
it("rejects missing evaluator variable mappings", () => {
expectUnstablePublicApiError(
() =>
diff --git a/web/src/__tests__/server/unit/unstable-evals-service.servertest.ts b/web/src/__tests__/server/unit/unstable-evals-service.servertest.ts
index d5297368d2..f0c59c4a80 100644
--- a/web/src/__tests__/server/unit/unstable-evals-service.servertest.ts
+++ b/web/src/__tests__/server/unit/unstable-evals-service.servertest.ts
@@ -127,10 +127,8 @@ import {
PUBLIC_EVALUATOR_TYPE_CODE,
PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
} from "@/src/features/public-api/types/unstable-public-evals-contract";
-import {
- CODE_EVAL_TEMPLATE_VARIABLES,
- getCodeEvalVariableMapping,
-} from "@/src/features/evals/utils/code-eval-template-utils";
+import { CODE_EVAL_TEMPLATE_VARIABLES } from "@langfuse/shared";
+import { getCodeEvalVariableMapping } from "@/src/features/evals/utils/code-eval-template-utils";
import { PostUnstableEvaluationRuleBody } from "@/src/features/public-api/types/unstable-evaluation-rules";
const numericOutputDefinition = createNumericEvalOutputDefinition({
@@ -658,6 +656,61 @@ describe("unstable public eval services", () => {
expect(mockJobConfigurationUpdate).not.toHaveBeenCalled();
});
+ it("adopts the canonical mapping when upgrading rules linked to a code evaluator", async () => {
+ // Code-eval mappings are synthesized, never user-authored: a stored
+ // snapshot predating a canonical-variable addition (e.g. toolCalls) must
+ // be overwritten on upgrade, not validated against nextVariables (which
+ // would 409 even though there is nothing the user could supply).
+ mockEvalTemplateFindMany.mockResolvedValueOnce([
+ {
+ id: "tmpl_code_v1",
+ version: 1,
+ },
+ ]);
+ mockJobConfigurationFindMany.mockResolvedValueOnce([
+ {
+ id: "ceval_code_stale",
+ scoreName: "exact_match",
+ targetObject: EvalTargetObject.EVENT,
+ // pre-toolCalls snapshot
+ variableMapping: getCodeEvalVariableMapping().filter(
+ (mapping) => mapping.templateVariable !== "toolCalls",
+ ),
+ },
+ ]);
+ mockEvalTemplateCreate.mockResolvedValueOnce({
+ ...projectTemplate,
+ id: "tmpl_code_v2",
+ type: EvalTemplateType.CODE,
+ prompt: null,
+ vars: [...CODE_EVAL_TEMPLATE_VARIABLES],
+ sourceCode: codeEvaluatorSourceCode,
+ sourceCodeLanguage: "TYPESCRIPT",
+ version: 2,
+ });
+
+ await createPublicEvaluator({
+ projectId: "project_123",
+ input: {
+ name: "Exact match",
+ type: PUBLIC_EVALUATOR_TYPE_CODE,
+ sourceCode: codeEvaluatorSourceCode,
+ sourceCodeLanguage: "TYPESCRIPT",
+ },
+ });
+
+ expect(mockJobConfigurationUpdate).toHaveBeenCalledWith({
+ where: {
+ id: "ceval_code_stale",
+ projectId: "project_123",
+ },
+ data: {
+ evalTemplateId: "tmpl_code_v2",
+ variableMapping: getCodeEvalVariableMapping(),
+ },
+ });
+ });
+
it("resolves an older evaluator version to the latest version when creating an evaluation rule", async () => {
mockLoadEvaluatorForEvaluationRule.mockResolvedValueOnce({
template: {
diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx b/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx
index 6e31af0f11..198ef743d5 100644
--- a/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx
+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx
@@ -117,6 +117,7 @@ export function RunEvaluationDialog(props: RunEvaluationDialogProps) {
minStartTime: props.exampleObservation?.startTime as Date,
maxStartTime: props.exampleObservation?.startTime as Date,
truncated: false,
+ includeToolCalls: true,
},
{
...sendAsPostOption,
diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/utils.ts b/web/src/features/batch-actions/components/RunEvaluationDialog/utils.ts
index c3bf2f2880..6361e7d3b7 100644
--- a/web/src/features/batch-actions/components/RunEvaluationDialog/utils.ts
+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/utils.ts
@@ -1,5 +1,6 @@
import {
extractValueFromObjectAsString,
+ zipToolCallsFromRecord,
type BatchActionQuery,
type ObservationVariableMapping,
} from "@langfuse/shared";
@@ -39,11 +40,21 @@ export function renderPromptPreviewFromObservation(params: {
return "Template has no prompt.";
}
+ // Both source records carry tool calls in the raw storage shape (name-less
+ // JSON strings + parallel names); zip so a toolCalls mapping previews the
+ // named objects the evaluator runtime receives. Zipped lazily: this runs
+ // per evaluator row per render, and most mappings never reference toolCalls.
+ const observationWithToolCalls = variableMapping.some(
+ (mapping) => mapping.selectedColumnId === "toolCalls",
+ )
+ ? { ...observation, toolCalls: zipToolCallsFromRecord(observation) }
+ : observation;
+
const variableValues = new Map<string, string>();
for (const mapping of variableMapping) {
const { value } = extractValueFromObjectAsString(
- observation,
+ observationWithToolCalls,
mapping.selectedColumnId,
mapping.jsonSelector ?? undefined,
);
diff --git a/web/src/features/evals/components/code-eval-test-run-card.tsx b/web/src/features/evals/components/code-eval-test-run-card.tsx
index bc07d318f3..65abf98eb6 100644
--- a/web/src/features/evals/components/code-eval-test-run-card.tsx
+++ b/web/src/features/evals/components/code-eval-test-run-card.tsx
@@ -247,6 +247,8 @@ function CodeEvalTestRunInputCards({
previewData: CodeEvalInputPreviewData;
includeExperimentVariables: boolean;
}) {
+ // Mirrors the payload shape buildCodeEvalPayload hands to the evaluator,
+ // so the preview shows exactly what the code receives.
const inputPreviewJson = useMemo(() => {
const data = previewData.data;
@@ -255,6 +257,10 @@ function CodeEvalTestRunInputCards({
input: deepParseJson(data.input),
output: deepParseJson(data.output),
metadata: deepParseJson(data.metadata),
+ // No deepParseJson, matching variable extraction: the zipped calls are
+ // fully parsed already, and it would coerce id/name/type strings that
+ // are JSON literals ("true"/"null") into primitives.
+ toolCalls: data.toolCalls,
},
...(includeExperimentVariables
? {
diff --git a/web/src/features/evals/hooks/useEvaluatorTarget.ts b/web/src/features/evals/hooks/useEvaluatorTarget.ts
index 5c5a24fddf..4d1b0032fc 100644
--- a/web/src/features/evals/hooks/useEvaluatorTarget.ts
+++ b/web/src/features/evals/hooks/useEvaluatorTarget.ts
@@ -77,9 +77,9 @@ export const useEvaluatorTargetState = () => {
// Get valid column IDs for the target
const validColumnIds = isEventTarget(targetObject)
- ? new Set(eventTargetEvalVariableColumns.map((c) => c.id))
+ ? new Set<string>(eventTargetEvalVariableColumns.map((c) => c.id))
: isExperimentTarget(targetObject)
- ? new Set(experimentTargetEvalVariableColumns.map((c) => c.id))
+ ? new Set<string>(experimentTargetEvalVariableColumns.map((c) => c.id))
: null;
return currentMapping.map((field) => {
diff --git a/web/src/features/evals/hooks/usePreviewData.ts b/web/src/features/evals/hooks/usePreviewData.ts
index d48e121650..c9d670ef9e 100644
--- a/web/src/features/evals/hooks/usePreviewData.ts
+++ b/web/src/features/evals/hooks/usePreviewData.ts
@@ -1,3 +1,5 @@
+import { useMemo } from "react";
+
import {
isEventTarget,
isExperimentTarget,
@@ -7,13 +9,16 @@ import { api, sendAsPostOption, type RouterOutputs } from "@/src/utils/api";
import {
EvalTargetObject,
extractValueFromObject,
+ zipToolCallsFromRecord,
type EvalTargetObject as EvalTargetObjectType,
+ type ToolCallForEval,
} from "@langfuse/shared";
export type PreviewDataFields = {
input: unknown;
output: unknown;
metadata: unknown;
+ toolCalls: ToolCallForEval[];
experimentItemExpectedOutput: unknown;
experimentItemMetadata: unknown;
};
@@ -75,6 +80,20 @@ function getPreviewMode({
return "none";
}
+/**
+ * Memoized on the query result reference: normalization deep-parses full
+ * untruncated payloads and zips tool calls, and downstream consumers memoize
+ * on the returned object's identity (code-eval-test-run-card).
+ */
+function useNormalizedPreviewDataFields(
+ record: Record<string, unknown> | null | undefined,
+): PreviewDataFields | null {
+ return useMemo(
+ () => (record ? normalizePreviewDataFields(record) : null),
+ [record],
+ );
+}
+
function normalizePreviewDataFields(
record: Record<string, unknown> | null | undefined,
): PreviewDataFields {
@@ -82,6 +101,9 @@ function normalizePreviewDataFields(
input: getRecordValue(record, "input"),
output: getRecordValue(record, "output"),
metadata: getRecordValue(record, "metadata"),
+ // Source records carry the raw storage shape; zip so the preview matches
+ // what the evaluator runtime produces.
+ toolCalls: zipToolCallsFromRecord(record ?? {}),
experimentItemExpectedOutput: getRecordValue(
record,
"experimentItemExpectedOutput",
@@ -157,17 +179,19 @@ function useObservationPreview({
},
);
+ const normalized = useNormalizedPreviewDataFields(
+ observationDetails.data as Record<string, unknown> | undefined,
+ );
+
return {
previewData:
- observationDetails.data && traceId && observationId
+ observationDetails.data && normalized && traceId && observationId
? {
type: EvalTargetObject.EVENT,
traceId,
observationId,
timestamp: observationDetails.data.startTime ?? null,
- data: normalizePreviewDataFields(
- observationDetails.data as Record<string, unknown>,
- ),
+ data: normalized,
}
: null,
isLoading: observationDetails.isLoading,
@@ -198,6 +222,7 @@ function useEventPreview({
minStartTime: timestamp as Date,
maxStartTime: timestamp as Date,
truncated: false,
+ includeToolCalls: true,
},
{
...sendAsPostOption,
@@ -205,17 +230,19 @@ function useEventPreview({
},
);
+ const normalized = useNormalizedPreviewDataFields(
+ eventDetails.data?.[0] as Record<string, unknown> | undefined,
+ );
+
return {
previewData:
- observationId && traceId && timestamp && eventDetails.data?.[0]
+ observationId && traceId && timestamp && normalized
? {
type: EvalTargetObject.EVENT,
traceId,
observationId,
timestamp,
- data: normalizePreviewDataFields(
- eventDetails.data[0] as Record<string, unknown>,
- ),
+ data: normalized,
}
: null,
isLoading: eventDetails.isLoading,
@@ -246,6 +273,7 @@ function useExperimentPreview({
minStartTime: timestamp as Date,
maxStartTime: timestamp as Date,
truncated: false,
+ includeToolCalls: true,
},
{
...sendAsPostOption,
@@ -253,17 +281,19 @@ function useExperimentPreview({
},
);
+ const normalized = useNormalizedPreviewDataFields(
+ experimentDetails.data?.[0] as Record<string, unknown> | undefined,
+ );
+
return {
previewData:
- observationId && traceId && timestamp && experimentDetails.data?.[0]
+ observationId && traceId && timestamp && normalized
? {
type: EvalTargetObject.EVENT,
traceId,
observationId,
timestamp,
- data: normalizePreviewDataFields(
- experimentDetails.data[0] as Record<string, unknown>,
- ),
+ data: normalized,
}
: null,
isLoading: experimentDetails.isLoading,
diff --git a/web/src/features/evals/server/evaluatorUpgrade.ts b/web/src/features/evals/server/evaluatorUpgrade.ts
index eed0bc7585..fc8d4d0c7f 100644
--- a/web/src/features/evals/server/evaluatorUpgrade.ts
+++ b/web/src/features/evals/server/evaluatorUpgrade.ts
@@ -2,11 +2,12 @@ import {
EvalTargetObject,
EvalTemplateType,
InternalServerError,
+ CODE_EVAL_TEMPLATE_VARIABLES,
LangfuseConflictError,
observationVariableMappingList,
variableMappingList,
} from "@langfuse/shared";
-import { CODE_EVAL_TEMPLATE_VARIABLES } from "@/src/features/evals/utils/code-eval-template-utils";
+import { getCodeEvalVariableMapping } from "@/src/features/evals/utils/code-eval-template-utils";
// accepts both stored templates and createTemplate inputs (CODE inputs carry no vars)
export const getEvalTemplateVariables = (template: {
@@ -18,10 +19,22 @@ export const getEvalTemplateVariables = (template: {
: (template.vars ?? []);
export function prepareVariableMappingForEvaluatorUpgrade(params: {
+ templateType: EvalTemplateType;
targetObject: string;
variableMapping: unknown;
nextVariables: string[];
}) {
+ // Code-eval mappings are synthesized, never user-authored: adopt the
+ // current canonical mapping instead of validating the stored snapshot,
+ // which would conflict whenever the canonical variable set grows
+ // (e.g. toolCalls) even though there is nothing the user could supply.
+ if (params.templateType === EvalTemplateType.CODE) {
+ return {
+ variableMapping: getCodeEvalVariableMapping(),
+ missingVariables: [],
+ };
+ }
+
const mappingSchema =
params.targetObject === EvalTargetObject.EVENT ||
params.targetObject === EvalTargetObject.EXPERIMENT
@@ -50,6 +63,7 @@ export function prepareVariableMappingForEvaluatorUpgrade(params: {
}
export const prepareConfigsForTemplateUpgrade = (params: {
+ templateType: EvalTemplateType;
configs: {
id: string;
scoreName: string;
@@ -60,6 +74,7 @@ export const prepareConfigsForTemplateUpgrade = (params: {
}) =>
params.configs.map((config) => {
const preparedMapping = prepareVariableMappingForEvaluatorUpgrade({
+ templateType: params.templateType,
targetObject: config.targetObject,
variableMapping: config.variableMapping,
nextVariables: params.nextVariables,
diff --git a/web/src/features/evals/server/router.ts b/web/src/features/evals/server/router.ts
index 9a2af7d2e9..8280634472 100644
--- a/web/src/features/evals/server/router.ts
+++ b/web/src/features/evals/server/router.ts
@@ -83,7 +83,7 @@ import {
deleteEvalTemplateFamily,
findEvalTemplateFamilyUsage,
} from "@/src/features/evals/server/evalTemplateDeletion";
-import { CODE_EVAL_TEMPLATE_VARIABLES } from "@/src/features/evals/utils/code-eval-template-utils";
+import { CODE_EVAL_TEMPLATE_VARIABLES } from "@langfuse/shared";
import {
getCodeEvalCapabilities,
isCodeEvalEnabled,
@@ -1046,6 +1046,7 @@ export const evalRouter = createTRPCRouter({
}
const preparedMapping = prepareVariableMappingForEvaluatorUpgrade({
+ templateType: resolvedEvalTemplate.type,
targetObject: input.target,
variableMapping: variableMappingForTarget,
nextVariables: getEvalTemplateVariables(resolvedEvalTemplate),
@@ -1326,6 +1327,7 @@ export const evalRouter = createTRPCRouter({
})
: [];
const upgradedConfigs = prepareConfigsForTemplateUpgrade({
+ templateType: input.type,
configs: configsToUpgrade,
nextVariables,
});
diff --git a/web/src/features/evals/server/unstable-public-api/adapters.ts b/web/src/features/evals/server/unstable-public-api/adapters.ts
index 01bd703133..35f804fa47 100644
--- a/web/src/features/evals/server/unstable-public-api/adapters.ts
+++ b/web/src/features/evals/server/unstable-public-api/adapters.ts
@@ -28,10 +28,8 @@ import {
type PublicEvaluatorOutputDefinitionType,
type PublicEvaluatorTypeType,
} from "@/src/features/public-api/types/unstable-public-evals-contract";
-import {
- CODE_EVAL_TEMPLATE_VARIABLES,
- getCodeEvalVariableMapping,
-} from "@/src/features/evals/utils/code-eval-template-utils";
+import { CODE_EVAL_TEMPLATE_VARIABLES } from "@langfuse/shared";
+import { getCodeEvalVariableMapping } from "@/src/features/evals/utils/code-eval-template-utils";
import type {
ApiEvaluationRuleRecord,
ApiEvaluatorRecord,
@@ -80,6 +78,7 @@ const PUBLIC_MAPPING_SOURCE_TO_INTERNAL_COLUMN: Record<
input: "input",
output: "output",
metadata: "metadata",
+ tool_calls: "toolCalls",
expected_output: "experimentItemExpectedOutput",
experiment_item_metadata: "experimentItemMetadata",
};
@@ -91,6 +90,11 @@ const INTERNAL_MAPPING_COLUMN_TO_PUBLIC_SOURCE: Record<
input: "input",
output: "output",
metadata: "metadata",
+ // Only camelCase for tool calls: the column id is new with tool-call
+ // support, so unlike expected_output no legacy snake_case rows exist. An
+ // accidental "tool_calls" write should surface at the corrupted-mapping
+ // error boundary, not be absorbed here.
+ toolCalls: "tool_calls",
expected_output: "expected_output",
expectedOutput: "expected_output",
experiment_item_expected_output: "expected_output",
diff --git a/web/src/features/evals/server/unstable-public-api/evaluator-service.ts b/web/src/features/evals/server/unstable-public-api/evaluator-service.ts
index 2b288d4eae..004ea37055 100644
--- a/web/src/features/evals/server/unstable-public-api/evaluator-service.ts
+++ b/web/src/features/evals/server/unstable-public-api/evaluator-service.ts
@@ -13,7 +13,7 @@ import {
isCodeEvalEnabled,
isCodeEvalSourceCodeLanguageSupported,
} from "@/src/features/evals/server/isCodeEvalEnabled";
-import { CODE_EVAL_TEMPLATE_VARIABLES } from "@/src/features/evals/utils/code-eval-template-utils";
+import { CODE_EVAL_TEMPLATE_VARIABLES } from "@langfuse/shared";
import { auditLog } from "@/src/features/audit-logs/auditLog";
import { EVAL_TEMPLATE_AUDIT_LOG_RESOURCE_TYPE } from "@/src/features/evals/server/audit-log-resource-types";
import { deleteEvalTemplateFamily } from "@/src/features/evals/server/evalTemplateDeletion";
@@ -206,6 +206,7 @@ export async function createPublicEvaluator(params: {
: [];
const upgradedConfigs = configsToUpgrade.map((config) => {
const preparedMapping = prepareVariableMappingForEvaluatorUpgrade({
+ templateType: storedEvalTemplateType,
targetObject: config.targetObject,
variableMapping: config.variableMapping,
nextVariables,
diff --git a/web/src/features/evals/server/unstable-public-api/types.ts b/web/src/features/evals/server/unstable-public-api/types.ts
index 7866d75cb1..6662efec10 100644
--- a/web/src/features/evals/server/unstable-public-api/types.ts
+++ b/web/src/features/evals/server/unstable-public-api/types.ts
@@ -18,7 +18,7 @@ import type {
PUBLIC_EVALUATOR_TYPE_CODE,
PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
} from "@/src/features/public-api/types/unstable-public-evals-contract";
-import type { CODE_EVAL_TEMPLATE_VARIABLES } from "@/src/features/evals/utils/code-eval-template-utils";
+import type { CODE_EVAL_TEMPLATE_VARIABLES } from "@langfuse/shared";
export type PrismaClientLike =
| typeof prisma
diff --git a/web/src/features/evals/server/unstable-public-api/validation.ts b/web/src/features/evals/server/unstable-public-api/validation.ts
index dfab959d57..17df947274 100644
--- a/web/src/features/evals/server/unstable-public-api/validation.ts
+++ b/web/src/features/evals/server/unstable-public-api/validation.ts
@@ -4,10 +4,12 @@ import {
} from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import { JSONPath } from "jsonpath-plus";
-import type {
- PublicEvaluationRuleFilterType,
- PublicEvaluationRuleMappingType,
- PublicEvaluationRuleTargetType,
+import {
+ ExperimentEvaluationRuleMappingSource,
+ ObservationEvaluationRuleMappingSource,
+ type PublicEvaluationRuleFilterType,
+ type PublicEvaluationRuleMappingType,
+ type PublicEvaluationRuleTargetType,
} from "@/src/features/public-api/types/unstable-public-evals-contract";
import { getEvaluatorDefinitionPreflightError } from "@/src/features/evals/server/evaluator-preflight";
import { createUnstablePublicApiError } from "@/src/features/public-api/server/unstable-public-api-error-contract";
@@ -71,15 +73,12 @@ const SUPPORTED_FILTER_COLUMNS_BY_TARGET = {
),
} as const satisfies Record<PublicEvaluationRuleTargetType, Set<string>>;
+// Derived from the per-target request schemas so this runtime check (which
+// also guards paths that parse the target-agnostic mapping union) can never
+// drift from the documented contract.
const SUPPORTED_MAPPING_SOURCES_BY_TARGET = {
- observation: new Set(["input", "output", "metadata"]),
- experiment: new Set([
- "input",
- "output",
- "metadata",
- "expected_output",
- "experiment_item_metadata",
- ]),
+ observation: new Set<string>(ObservationEvaluationRuleMappingSource.options),
+ experiment: new Set<string>(ExperimentEvaluationRuleMappingSource.options),
} as const satisfies Record<PublicEvaluationRuleTargetType, Set<string>>;
export function validateEvaluationRuleFilters(params: {
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.ts
index 7ac640bb4a..321e19b88c 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
@@ -28,6 +28,28 @@ class Score:
A Langfuse score returned by a Python evaluator.`;
+const TYPESCRIPT_TOOL_CALL_DOC = `type ToolCall = {
+ id: string;
+ name: string;
+ arguments: unknown;
+ type: string;
+ index: number;
+}
+
+A tool call recorded on the observation. arguments is the parsed
+argument object when the recorded value was valid JSON.`;
+
+const PYTHON_TOOL_CALL_DOC = `@dataclass
+class ToolCall:
+ id: str = ""
+ name: str = ""
+ arguments: Any = None
+ type: str = ""
+ index: int = 0
+
+A tool call recorded on the observation. arguments is the parsed
+argument object when the recorded value was valid JSON.`;
+
export const TYPESCRIPT_CODE_EVAL_HOVER_DOCS = {
evaluate: `function evaluate(ctx: EvaluationContext): EvaluationResult
@@ -40,6 +62,7 @@ The TypeScript value Langfuse passes to evaluate.`,
input: any;
output: any;
metadata: any;
+ toolCalls: ToolCall[];
};
experiment:
| {
@@ -54,9 +77,14 @@ The data Langfuse passes to a TypeScript evaluator.`,
input: any;
output: any;
metadata: any;
+ toolCalls: ToolCall[];
}
The observation selected by the evaluator target.`,
+ ToolCall: TYPESCRIPT_TOOL_CALL_DOC,
+ toolCalls: `property observation.toolCalls: ToolCall[]
+
+The tool calls recorded on the observation, in the order the model emitted them.`,
experiment: `property EvaluationContext.experiment?: {
itemExpectedOutput: any;
itemMetadata: any;
@@ -123,8 +151,15 @@ class ObservationContext:
input: Any = None
output: Any = None
metadata: Any = None
+ tool_calls: list[ToolCall] = field(default_factory=list)
The observation selected by the evaluator target.`,
+ ToolCall: PYTHON_TOOL_CALL_DOC,
+ tool_calls: `property observation.tool_calls: list[ToolCall]
+
+The tool calls recorded on the observation, in the order the model emitted
+them. arguments is the parsed argument object when the recorded value was
+valid JSON.`,
ExperimentContext: `@dataclass
class ExperimentContext:
item_expected_output: Any = None
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.ts
index 9639d1b6a4..40215c4686 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,8 +1,17 @@
-export const TYPESCRIPT_CODE_EVAL_CONTRACT = `type EvaluationContext = {
+export const TYPESCRIPT_CODE_EVAL_CONTRACT = `type ToolCall = {
+ id: string;
+ name: string;
+ arguments: unknown;
+ type: string;
+ index: number;
+};
+
+type EvaluationContext = {
observation: {
input: any;
output: any;
metadata: any;
+ toolCalls: ToolCall[];
};
experiment:
| {
@@ -51,15 +60,25 @@ export const DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE = `function evaluate(ctx: Evalu
};
}`;
-export const PYTHON_CODE_EVAL_CONTRACT = `from dataclasses import dataclass
+export const PYTHON_CODE_EVAL_CONTRACT = `from dataclasses import dataclass, field
from typing import Any
+@dataclass
+class ToolCall:
+ id: str = ""
+ name: str = ""
+ arguments: Any = None
+ type: str = ""
+ index: int = 0
+
+
@dataclass
class ObservationContext:
input: Any = None
output: Any = None
metadata: Any = None
+ tool_calls: list[ToolCall] = field(default_factory=list)
@dataclass
@@ -109,6 +128,205 @@ export const DEFAULT_PYTHON_CODE_EVAL_SOURCE = `def evaluate(ctx: EvaluationCont
]
)`;
+// Contract versions previously shipped and possibly embedded verbatim in
+// stored template sources (the public API stores sourceCode as-is, and full
+// docs examples get pasted into the editor). When changing a contract above,
+// append the outgoing text here so sources saved under it keep stripping
+// cleanly in the editor.
+export const PREVIOUS_TYPESCRIPT_CODE_EVAL_CONTRACTS: string[] = [
+ // pre-ToolCall (before tool calls were passed to code evaluators)
+ `type EvaluationContext = {
+ observation: {
+ input: any;
+ output: any;
+ metadata: any;
+ };
+ experiment:
+ | {
+ itemExpectedOutput: any;
+ itemMetadata: any;
+ }
+ | undefined;
+};
+
+type ScoreBase = {
+ name: string;
+ comment?: string;
+ configId?: string | null;
+ metadata?: Record<string, unknown>;
+};
+
+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;
+
+type EvaluationResult = {
+ scores: Score[];
+};
+`,
+ // original code-eval release (JSDoc-annotated contract, cf24ee840)
+ `/**
+ * The data Langfuse passes to a code evaluator.
+ */
+type EvaluationContext = {
+ /**
+ * The observation selected by the evaluator target.
+ */
+ observation: {
+ /**
+ * The input recorded on the observation.
+ */
+ input: any;
+ /**
+ * The output recorded on the observation.
+ */
+ output: any;
+ /**
+ * The metadata recorded on the observation.
+ */
+ metadata: any;
+ };
+ /**
+ * Experiment item data. Present when the evaluator runs on an experiment.
+ */
+ experiment:
+ | {
+ /**
+ * The expected output from the experiment item.
+ */
+ itemExpectedOutput: any;
+ /**
+ * The metadata from the experiment item.
+ */
+ itemMetadata: any;
+ }
+ | undefined;
+};
+
+/**
+ * A Langfuse score returned by a code evaluator.
+ */
+type ScoreBase = {
+ /**
+ * The score name.
+ */
+ name: string;
+ /**
+ * The reasoning or explanation stored with the score.
+ */
+ comment?: string;
+ /**
+ * The score config id to attach to the score.
+ */
+ configId?: string | null;
+ /**
+ * Extra metadata stored with the score.
+ */
+ metadata?: Record<string, unknown>;
+};
+
+type NumericScore = ScoreBase & {
+ /**
+ * The Langfuse score data type.
+ */
+ dataType: "NUMERIC";
+ /**
+ * The score value.
+ */
+ value: number;
+};
+
+type BooleanScore = ScoreBase & {
+ /**
+ * The Langfuse score data type.
+ */
+ dataType: "BOOLEAN";
+ /**
+ * The score value.
+ */
+ value: boolean;
+};
+
+type CategoricalScore = ScoreBase & {
+ /**
+ * The Langfuse score data type.
+ */
+ dataType: "CATEGORICAL";
+ /**
+ * The score value.
+ */
+ value: string;
+};
+
+type TextScore = ScoreBase & {
+ /**
+ * The Langfuse score data type.
+ */
+ dataType: "TEXT";
+ /**
+ * The score value.
+ */
+ value: string;
+};
+
+type Score = NumericScore | BooleanScore | CategoricalScore | TextScore;
+
+/**
+ * The value returned by evaluate.
+ */
+type EvaluationResult = {
+ /**
+ * One or more Langfuse scores to create for the target observation.
+ */
+ scores: Score[];
+};
+`,
+];
+
+export const PREVIOUS_PYTHON_CODE_EVAL_CONTRACTS: string[] = [
+ // pre-ToolCall (before tool calls were passed to code evaluators)
+ `from dataclasses import dataclass
+from typing import Any
+
+
+@dataclass
+class ObservationContext:
+ input: Any = None
+ output: Any = None
+ metadata: Any = None
+
+
+@dataclass
+class ExperimentContext:
+ item_expected_output: Any = None
+ item_metadata: Any = None
+
+
+@dataclass
+class EvaluationContext:
+ observation: ObservationContext
+ experiment: ExperimentContext | None = None
+
+
+@dataclass
+class Score:
+ value: int | float | str | bool
+ name: str
+ data_type: str | None = None
+ comment: str | None = None
+ config_id: str | None = None
+ metadata: dict[str, Any] | None = None
+
+
+@dataclass
+class EvaluationResult:
+ scores: list[Score]
+`,
+];
+
export type CodeEvalSourceCodeLanguage = "PYTHON" | "TYPESCRIPT";
export function getDefaultCodeEvalSource(
@@ -142,14 +360,22 @@ function stripCodeEvalContract({
sourceCode: string;
sourceCodeLanguage: CodeEvalSourceCodeLanguage;
}) {
- const contract =
+ // Sources stored before a contract bump embed the outgoing contract text,
+ // so try every shipped version, newest first.
+ const contracts =
sourceCodeLanguage === "PYTHON"
- ? PYTHON_CODE_EVAL_CONTRACT
- : TYPESCRIPT_CODE_EVAL_CONTRACT;
+ ? [PYTHON_CODE_EVAL_CONTRACT, ...PREVIOUS_PYTHON_CODE_EVAL_CONTRACTS]
+ : [
+ TYPESCRIPT_CODE_EVAL_CONTRACT,
+ ...PREVIOUS_TYPESCRIPT_CODE_EVAL_CONTRACTS,
+ ];
const source = sourceCode.trimStart();
+ const matchedContract = contracts.find((contract) =>
+ source.startsWith(contract),
+ );
- return source.startsWith(contract)
- ? source.slice(contract.length).trimStart()
+ return matchedContract
+ ? source.slice(matchedContract.length).trimStart()
: source;
}
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 b1224e9091..00a135be0b 100644
--- a/web/src/features/evals/utils/code-eval-template-utils.ts
+++ b/web/src/features/evals/utils/code-eval-template-utils.ts
@@ -1,4 +1,5 @@
import {
+ CODE_EVAL_TEMPLATE_VARIABLES,
EvalTargetObject,
type EvalTemplateSourceCodeLanguage,
EvalTemplateType,
@@ -15,14 +16,6 @@ type CodeEvalCapabilities = {
supportedSourceCodeLanguages: EvalTemplateSourceCodeLanguage[];
};
-export const CODE_EVAL_TEMPLATE_VARIABLES = [
- "input",
- "output",
- "metadata",
- "experimentItemExpectedOutput",
- "experimentItemMetadata",
-] as const;
-
export const shouldShowEvalTemplate = (
template: Partial<Pick<EvalTemplate, "type" | "sourceCodeLanguage">>,
codeEvalCapabilities: CodeEvalCapabilities,
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 12951c173f..fd1f1997d6 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,8 @@ import { describe, expect, it, vi } from "vitest";
import {
DEFAULT_PYTHON_CODE_EVAL_SOURCE,
DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE,
+ PREVIOUS_PYTHON_CODE_EVAL_CONTRACTS,
+ PREVIOUS_TYPESCRIPT_CODE_EVAL_CONTRACTS,
PYTHON_CODE_EVAL_CONTRACT,
TYPESCRIPT_CODE_EVAL_CONTRACT,
formatAndStripCodeEvalSourceForSubmit,
@@ -97,6 +99,33 @@ describe("code eval template validation", () => {
).toBe(source);
});
+ it("hydrates the editor without previously shipped contract versions", () => {
+ const tsSource =
+ "function evaluate(ctx: EvaluationContext): EvaluationResult { return { scores: [] }; }";
+ const pySource =
+ "def evaluate(ctx: EvaluationContext) -> EvaluationResult:\n return EvaluationResult(scores=[])";
+
+ for (const previousContract of PREVIOUS_TYPESCRIPT_CODE_EVAL_CONTRACTS) {
+ expect(previousContract).not.toBe(TYPESCRIPT_CODE_EVAL_CONTRACT);
+ expect(
+ getCodeEvalSourceForEditor({
+ sourceCode: `${previousContract}\n\n${tsSource}`,
+ sourceCodeLanguage: "TYPESCRIPT",
+ }),
+ ).toBe(tsSource);
+ }
+
+ for (const previousContract of PREVIOUS_PYTHON_CODE_EVAL_CONTRACTS) {
+ expect(previousContract).not.toBe(PYTHON_CODE_EVAL_CONTRACT);
+ expect(
+ getCodeEvalSourceForEditor({
+ sourceCode: `${previousContract}\n\n${pySource}`,
+ sourceCodeLanguage: "PYTHON",
+ }),
+ ).toBe(pySource);
+ }
+ });
+
it("accepts the default TypeScript source", async () => {
const result = await validateCodeEvalSourceWithLanguage({
source: DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE,
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 0710d85c5b..5d7925525d 100644
--- a/web/src/features/evals/utils/code-eval-template-validation.ts
+++ b/web/src/features/evals/utils/code-eval-template-validation.ts
@@ -9,6 +9,8 @@ import {
export {
DEFAULT_PYTHON_CODE_EVAL_SOURCE,
DEFAULT_TYPESCRIPT_CODE_EVAL_SOURCE,
+ PREVIOUS_PYTHON_CODE_EVAL_CONTRACTS,
+ PREVIOUS_TYPESCRIPT_CODE_EVAL_CONTRACTS,
PYTHON_CODE_EVAL_CONTRACT,
TYPESCRIPT_CODE_EVAL_CONTRACT,
formatAndStripCodeEvalSourceForSubmit,
diff --git a/web/src/features/evals/utils/evaluator-form-utils.ts b/web/src/features/evals/utils/evaluator-form-utils.ts
index a76e1aac32..97b962ce8d 100644
--- a/web/src/features/evals/utils/evaluator-form-utils.ts
+++ b/web/src/features/evals/utils/evaluator-form-utils.ts
@@ -51,7 +51,8 @@ export const fieldHasJsonSelectorOption = (
selectedColumnId === "experiment_item_metadata" ||
selectedColumnId === "expectedOutput" ||
selectedColumnId === "experimentItemExpectedOutput" ||
- selectedColumnId === "experimentItemMetadata";
+ selectedColumnId === "experimentItemMetadata" ||
+ selectedColumnId === "toolCalls";
export const getTargetDisplayName = (target: string): string => {
switch (target) {
diff --git a/web/src/features/events/server/eventsRouter.ts b/web/src/features/events/server/eventsRouter.ts
index 9d4d836cd1..ba74c1b39d 100644
--- a/web/src/features/events/server/eventsRouter.ts
+++ b/web/src/features/events/server/eventsRouter.ts
@@ -70,15 +70,20 @@ export type GetEventFilterOptionsInput = z.infer<
export const BatchIOInput = zodSchema.object({
projectId: zodSchema.string(),
- observations: zodSchema.array(
- zodSchema.object({
- id: zodSchema.string(),
- traceId: zodSchema.string(),
- }),
- ),
+ observations: zodSchema
+ .array(
+ zodSchema.object({
+ id: zodSchema.string(),
+ traceId: zodSchema.string(),
+ }),
+ )
+ // Bounds the unbounded-LIMIT ClickHouse read; the largest legitimate
+ // caller is one table page (max 50 rows), eval previews send one row.
+ .max(500),
minStartTime: zodSchema.date(),
maxStartTime: zodSchema.date(),
truncated: zodSchema.boolean().optional(), // Defaults to true for performance
+ includeToolCalls: zodSchema.boolean().optional(), // Defaults to false; tool-call arrays can be large
// Opts into trace-level auth (public traces) in protectedGetTraceProcedure
traceId: zodSchema.string().optional(),
});
@@ -201,6 +206,7 @@ export const eventsRouter = createTRPCRouter({
minStartTime: input.minStartTime,
maxStartTime: input.maxStartTime,
truncated: input.truncated,
+ includeToolCallFields: input.includeToolCalls,
});
return batchIO.map(toDomainWithStringifiedMetadata);
@@ -223,6 +229,7 @@ export const eventsRouter = createTRPCRouter({
maxStartTime: input.maxStartTime,
truncated: input.truncated,
includeExperimentFields: true,
+ includeToolCallFields: input.includeToolCalls,
});
return batchIO.map(toDomainWithStringifiedMetadata);
diff --git a/web/src/features/events/server/eventsService.ts b/web/src/features/events/server/eventsService.ts
index 3026e08674..2b9ce557ab 100644
--- a/web/src/features/events/server/eventsService.ts
+++ b/web/src/features/events/server/eventsService.ts
@@ -20,6 +20,7 @@ import {
getScoresForTraces,
logger,
traceException,
+ type EventBatchIOResult,
type EventFilterOptionColumn,
} from "@langfuse/shared/src/server";
import { type timeFilter, type FilterState } from "@langfuse/shared";
@@ -649,7 +650,10 @@ export async function getEventFilterOptions(
};
}
-interface GetEventBatchIOParams<TIncludeExperiment extends boolean = false> {
+interface GetEventBatchIOParams<
+ TIncludeExperiment extends boolean = false,
+ TIncludeToolCalls extends boolean = false,
+> {
projectId: string;
observations: Array<{
id: string;
@@ -659,31 +663,19 @@ interface GetEventBatchIOParams<TIncludeExperiment extends boolean = false> {
maxStartTime: Date;
truncated?: boolean;
includeExperimentFields?: TIncludeExperiment;
+ /** Opt-in: tool-call arrays can be large; only eval consumers need them. */
+ includeToolCallFields?: TIncludeToolCalls;
}
-type EventBatchIOStringOutput = Awaited<
- ReturnType<typeof getObservationsBatchIOFromEventsTable>
->[number];
-
-type EventBatchIOWithExperimentOutput = EventBatchIOStringOutput & {
- experimentItemExpectedOutput: string | null;
- experimentItemMetadata: unknown;
-};
-
/**
* Batch fetch input/output and metadata for multiple observations
*/
export async function getEventBatchIO<
TIncludeExperiment extends boolean = false,
+ TIncludeToolCalls extends boolean = false,
>(
- params: GetEventBatchIOParams<TIncludeExperiment>,
-): Promise<
- Array<
- TIncludeExperiment extends true
- ? EventBatchIOWithExperimentOutput
- : EventBatchIOStringOutput
- >
-> {
+ params: GetEventBatchIOParams<TIncludeExperiment, TIncludeToolCalls>,
+): Promise<Array<EventBatchIOResult<TIncludeExperiment, TIncludeToolCalls>>> {
return getObservationsBatchIOFromEventsTable({
projectId: params.projectId,
observations: params.observations,
@@ -691,13 +683,6 @@ export async function getEventBatchIO<
maxStartTime: params.maxStartTime,
truncated: params.truncated,
includeExperimentFields: params.includeExperimentFields,
- } as Parameters<typeof getObservationsBatchIOFromEventsTable>[0] & {
- includeExperimentFields?: TIncludeExperiment;
- }) as Promise<
- Array<
- TIncludeExperiment extends true
- ? EventBatchIOWithExperimentOutput
- : EventBatchIOStringOutput
- >
- >;
+ includeToolCallFields: params.includeToolCallFields,
+ });
}
diff --git a/web/src/features/mcp/features/evals/schema.ts b/web/src/features/mcp/features/evals/schema.ts
index 578882b97e..dfc787a69a 100644
--- a/web/src/features/mcp/features/evals/schema.ts
+++ b/web/src/features/mcp/features/evals/schema.ts
@@ -43,7 +43,7 @@ export const EvaluatorModelConfigBaseSchema =
// Experiment mapping has the widest `source` enum, so it covers both targets.
export const RuleMappingBaseSchema = ExperimentEvaluationRuleMapping.describe(
- "Maps an evaluator variable to a data source. `observation` rules use `input`, `output`, `metadata`; `experiment` rules also allow `expected_output` and `experiment_item_metadata`. Required for `llm_as_judge` evaluators; omit for `code` evaluators (Langfuse manages their mapping).",
+ "Maps an evaluator variable to a data source. `observation` rules use `input`, `output`, `metadata`, `tool_calls`; `experiment` rules also allow `expected_output` and `experiment_item_metadata`. Required for `llm_as_judge` evaluators; omit for `code` evaluators (Langfuse manages their mapping).",
);
// Shared loose filter shape (the contract's per-column filter is a union the
diff --git a/web/src/features/public-api/types/unstable-public-evals-contract.ts b/web/src/features/public-api/types/unstable-public-evals-contract.ts
index d28260ac70..568feb5ba0 100644
--- a/web/src/features/public-api/types/unstable-public-evals-contract.ts
+++ b/web/src/features/public-api/types/unstable-public-evals-contract.ts
@@ -111,12 +111,14 @@ export const ObservationEvaluationRuleMappingSource = z.enum([
"input",
"output",
"metadata",
+ "tool_calls",
]);
export const ExperimentEvaluationRuleMappingSource = z.enum([
"input",
"output",
"metadata",
+ "tool_calls",
"expected_output",
"experiment_item_metadata",
]);
@@ -126,6 +128,7 @@ function createMappingSchema<
| "input"
| "output"
| "metadata"
+ | "tool_calls"
| "expected_output"
| "experiment_item_metadata"
>,
diff --git a/web/src/utils/chatml/extractTools.ts b/web/src/utils/chatml/extractTools.ts
index 74b1da240e..55c04e1909 100644
--- a/web/src/utils/chatml/extractTools.ts
+++ b/web/src/utils/chatml/extractTools.ts
@@ -1,22 +1,15 @@
import {
extractAdditionalInput,
normalizeToolDefinitionsForChatMl,
+ parseJsonIfString as parseIfString,
} from "@langfuse/shared";
import type { PlaygroundTool } from "@/src/features/playground/page/types";
-import { safeJsonParse } from "@/src/utils/json";
const EMPTY_TOOL_PARAMETERS = {
type: "object",
properties: {},
} as const;
-function parseIfString(value: unknown): unknown {
- if (typeof value !== "string") return value;
-
- const parsed = safeJsonParse(value);
- return parsed === undefined ? value : parsed;
-}
-
function asRecord(value: unknown): Record<string, unknown> | null {
const parsed = parseIfString(value);
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
diff --git a/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.integration.test.ts b/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.integration.test.ts
index 7e8fe5db3f..fc9f6f31d0 100644
--- a/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.integration.test.ts
+++ b/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.integration.test.ts
@@ -28,6 +28,7 @@ const baseInput: DispatchInput = {
input: "hello",
output: "hello world",
metadata: { topic: "integration" },
+ toolCalls: [],
},
experiment: {
itemExpectedOutput: "hello world",
diff --git a/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.test.ts b/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.test.ts
index 3922ab63c9..fa0d8ab0a8 100644
--- a/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.test.ts
+++ b/worker/src/features/evaluation/codeBased/awsLambdaCodeEvalDispatcher.test.ts
@@ -19,6 +19,7 @@ const baseInput: DispatchInput = {
input: null,
output: null,
metadata: null,
+ toolCalls: [],
},
},
};
@@ -89,6 +90,7 @@ describe("AwsLambdaCodeEvalDispatcher", () => {
input: { question: "2+2" },
output: "4",
metadata: { source: "test" },
+ toolCalls: [],
},
experiment: {
itemExpectedOutput: "4",
diff --git a/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.test.ts b/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.test.ts
index d2799431d8..e0ca9ba7a3 100644
--- a/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.test.ts
+++ b/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.test.ts
@@ -95,6 +95,20 @@ describe("executeCodeBasedEvaluation", () => {
{ var: "input", value: { question: "2+2" } },
{ var: "output", value: "4" },
{ var: "experimentItemExpectedOutput", value: "4" },
+ // Zipped shape produced by extractObservationVariables for the
+ // "toolCalls" entry of the code eval mapping.
+ {
+ var: "toolCalls",
+ value: [
+ {
+ id: "call_1",
+ name: "search",
+ arguments: { query: "weather" },
+ type: "function",
+ index: 0,
+ },
+ ],
+ },
],
hasExperimentContext: true,
executionMetadata: { job_execution_id: "job-1" },
@@ -115,6 +129,15 @@ describe("executeCodeBasedEvaluation", () => {
input: { question: "2+2" },
output: "4",
metadata: null,
+ toolCalls: [
+ {
+ id: "call_1",
+ name: "search",
+ arguments: { query: "weather" },
+ type: "function",
+ index: 0,
+ },
+ ],
},
experiment: {
itemExpectedOutput: "4",
@@ -188,7 +211,12 @@ describe("executeCodeBasedEvaluation", () => {
expect(mocks.dispatcher.dispatch).toHaveBeenCalledWith(
expect.objectContaining({
payload: {
- observation: { input: null, output: null, metadata: null },
+ observation: {
+ input: null,
+ output: null,
+ metadata: null,
+ toolCalls: [],
+ },
},
}),
);
@@ -227,7 +255,12 @@ describe("executeCodeBasedEvaluation", () => {
expect(mocks.dispatcher.dispatch).toHaveBeenCalledWith(
expect.objectContaining({
payload: {
- observation: { input: null, output: null, metadata: null },
+ observation: {
+ input: null,
+ output: null,
+ metadata: null,
+ toolCalls: [],
+ },
experiment: {
itemExpectedOutput: null,
itemMetadata: null,
@@ -270,7 +303,12 @@ describe("executeCodeBasedEvaluation", () => {
expect(mocks.dispatcher.dispatch).toHaveBeenCalledWith(
expect.objectContaining({
payload: {
- observation: { input: null, output: null, metadata: null },
+ observation: {
+ input: null,
+ output: null,
+ metadata: null,
+ toolCalls: [],
+ },
},
}),
);
@@ -317,6 +355,7 @@ describe("executeCodeBasedEvaluation", () => {
input: null,
output: "true",
metadata: "42",
+ toolCalls: [],
},
experiment: {
itemExpectedOutput: "null",
@@ -369,6 +408,7 @@ describe("executeCodeBasedEvaluation", () => {
input: null,
output: null,
metadata: null,
+ toolCalls: [],
},
experiment: {
itemExpectedOutput: null,
@@ -464,7 +504,12 @@ describe("executeCodeBasedEvaluation", () => {
level: "ERROR",
statusMessage: "Code eval execution failed: runner exploded",
input: JSON.stringify({
- observation: { input: "prompt", output: null, metadata: null },
+ observation: {
+ input: "prompt",
+ output: null,
+ metadata: null,
+ toolCalls: [],
+ },
}),
output: expect.stringContaining("runner exploded"),
metadata: expect.objectContaining({
diff --git a/worker/src/features/evaluation/codeBased/localCodeEvalDispatcher.test.ts b/worker/src/features/evaluation/codeBased/localCodeEvalDispatcher.test.ts
index 01ebc6cfef..183883a298 100644
--- a/worker/src/features/evaluation/codeBased/localCodeEvalDispatcher.test.ts
+++ b/worker/src/features/evaluation/codeBased/localCodeEvalDispatcher.test.ts
@@ -20,6 +20,7 @@ const baseInput: Omit<DispatchInput, "runtime" | "code"> = {
input: { question: "2+2" },
output: "4",
metadata: { source: "test" },
+ toolCalls: [],
},
experiment: {
itemExpectedOutput: "4",
diff --git a/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.ts b/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.ts
index 430f86a841..77ecf4e777 100644
--- a/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.ts
+++ b/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.ts
@@ -2,11 +2,54 @@ import { describe, it, expect } from "vitest";
import { extractObservationVariables } from "../../../../../../packages/shared/src/server/evals/extractObservationVariables";
import { type ObservationForEval } from "../types";
import {
- availableObservationEvalVariableColumns,
+ observationEvalVariableColumns,
ObservationEvalVariableColumn,
type ObservationVariableMapping,
} from "@langfuse/shared";
+// Test-only superset: extends the production columns with fields that are not
+// mappable in the product today, to cover extractObservationVariables'
+// custom-columns parameter.
+const availableObservationEvalVariableColumns = [
+ ...observationEvalVariableColumns,
+ {
+ id: "toolDefinitions",
+ name: "Tool Definitions",
+ description: "Tool definitions",
+ internal: "tool_definitions",
+ },
+ {
+ id: "toolCallNames",
+ name: "Tool Call Names",
+ description: "Tool call names",
+ internal: "tool_call_names",
+ },
+ {
+ id: "providedModelName",
+ name: "Model",
+ description: "Model",
+ internal: "provided_model_name",
+ },
+ {
+ id: "modelParameters",
+ name: "Model Parameters",
+ description: "Model parameters",
+ internal: "model_parameters",
+ },
+ {
+ id: "usageDetails",
+ name: "Usage Details",
+ description: "Usage details",
+ internal: "usage_details",
+ },
+ {
+ id: "costDetails",
+ name: "Cost Details",
+ description: "Cost details",
+ internal: "cost_details",
+ },
+];
+
describe("extractObservationVariables", () => {
const mockObservation: ObservationForEval = {
// Core identifiers
@@ -41,7 +84,10 @@ describe("extractObservationVariables", () => {
// Tool call properties
tool_definitions: { search: '{"description": "Search the web"}' },
- tool_calls: ['{"name": "search", "args": {"query": "test"}}'],
+ // Real storage shape: name-less JSON strings, names in the parallel array.
+ tool_calls: [
+ '{"id":"call_1","arguments":"{\\"query\\":\\"test\\"}","type":"function","index":0}',
+ ],
tool_call_names: ["search"],
tool_call_count: 1,
@@ -164,22 +210,126 @@ describe("extractObservationVariables", () => {
});
describe("tool call extraction", () => {
- it("should extract toolCalls variable", () => {
+ it("should extract toolCalls as zipped objects with the default columns", () => {
const variableMapping: ObservationVariableMapping[] = [
{ templateVariable: "tools", selectedColumnId: "toolCalls" },
];
- const result = extractObservationVariables(
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].var).toBe("tools");
+ expect(result[0].value).toEqual([
{
- observation: mockObservation,
- variableMapping,
+ id: "call_1",
+ name: "search",
+ arguments: { query: "test" },
+ type: "function",
+ index: 0,
},
- availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],
- );
+ ]);
+ });
+
+ it("passes string argument values through unchanged", () => {
+ // Zipped calls skip deepParseJson entirely (arguments are already parsed
+ // by the zip), so JSON-literal strings the model emitted ("true", "42",
+ // serialized objects) are NOT coerced. This pins the payload types
+ // evaluator code receives.
+ const args = JSON.stringify({
+ count: "42",
+ flag: "true",
+ nested: '{"a":1}',
+ });
+ const observation = {
+ ...mockObservation,
+ tool_calls: [
+ JSON.stringify({
+ id: "call_1",
+ arguments: args,
+ type: "function",
+ index: 0,
+ }),
+ ],
+ tool_call_names: ["search"],
+ };
+
+ const result = extractObservationVariables({
+ observation,
+ variableMapping: [
+ { templateVariable: "tools", selectedColumnId: "toolCalls" },
+ ],
+ });
+
+ expect(result[0].value).toEqual([
+ {
+ id: "call_1",
+ name: "search",
+ arguments: {
+ count: "42",
+ flag: "true",
+ nested: '{"a":1}',
+ },
+ type: "function",
+ index: 0,
+ },
+ ]);
+ });
+
+ it("keeps JSON-literal id/name/type strings as strings", () => {
+ // A tool named "null" (or an id/type of "true"/"false") is unusual but
+ // legal. deepParseJson would coerce these top-level fields to primitives
+ // at depth 2 — which then fails buildCodeEvalPayload's schema parse and
+ // empties the whole array, or leaks null/true into judge prompts.
+ const observation = {
+ ...mockObservation,
+ tool_calls: [
+ JSON.stringify({
+ id: "true",
+ arguments: "{}",
+ type: "false",
+ index: 0,
+ }),
+ ],
+ tool_call_names: ["null"],
+ };
+
+ const result = extractObservationVariables({
+ observation,
+ variableMapping: [
+ { templateVariable: "tools", selectedColumnId: "toolCalls" },
+ ],
+ });
+
+ expect(result[0].value).toEqual([
+ {
+ id: "true",
+ name: "null",
+ arguments: {},
+ type: "false",
+ index: 0,
+ },
+ ]);
+ });
+
+ it("should support JSONPath selectors over zipped toolCalls", () => {
+ const variableMapping: ObservationVariableMapping[] = [
+ {
+ templateVariable: "calledTools",
+ selectedColumnId: "toolCalls",
+ jsonSelector: "$[*].name",
+ },
+ ];
+
+ const result = extractObservationVariables({
+ observation: mockObservation,
+ variableMapping,
+ });
expect(result).toHaveLength(1);
- expect(result[0].var).toBe("tools");
- expect(result[0].value).toEqual(mockObservation.tool_calls);
+ expect(result[0].value).toEqual("search");
});
it("should extract toolDefinitions variable", () => {