Skip to content

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

feat(tracing): filter observations by tool calls (#11031)

Nimar33022d7428e1
diff --git a/packages/shared/.eslintrc.js b/packages/shared/.eslintrc.js
index 15ec24a23d..1ccc66f044 100644
--- a/packages/shared/.eslintrc.js
+++ b/packages/shared/.eslintrc.js
@@ -5,4 +5,11 @@ module.exports = {
parserOptions: {
project: true,
},
+ rules: {
+ // Allow unused vars prefixed with _ (intentionally unused params/destructured vars)
+ "no-unused-vars": [
+ "error",
+ { argsIgnorePattern: "^_", varsIgnorePattern: "^_" },
+ ],
+ },
};
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 007d141b8c..689f8909f5 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -25,6 +25,10 @@
"import": "./dist/src/server/auth/apiKeys.js",
"require": "./dist/src/server/auth/apiKeys.js"
},
+ "./src/utils/chatml": {
+ "import": "./dist/src/utils/chatml/index.js",
+ "require": "./dist/src/utils/chatml/index.js"
+ },
"./encryption": {
"import": "./dist/src/encryption/index.js",
"require": "./dist/src/encryption/index.js"
diff --git a/packages/shared/scripts/seeder/utils/clickhouse-builder.ts b/packages/shared/scripts/seeder/utils/clickhouse-builder.ts
index 72dce2166a..104b234ae9 100644
--- a/packages/shared/scripts/seeder/utils/clickhouse-builder.ts
+++ b/packages/shared/scripts/seeder/utils/clickhouse-builder.ts
@@ -195,7 +195,11 @@ export class ClickHouseQueryBuilder {
start_time AS event_ts,
0 AS is_deleted,
'' AS usage_pricing_tier_id,
- '' AS usage_pricing_tier_name
+ '' AS usage_pricing_tier_name,
+ map() AS tool_definitions,
+ [] AS tool_calls,
+ [] AS tool_call_names
+
FROM numbers(${totalObservations});
`;
}
diff --git a/packages/shared/scripts/seeder/utils/data-generators.ts b/packages/shared/scripts/seeder/utils/data-generators.ts
index 0d4d36242f..e40cfa90ca 100644
--- a/packages/shared/scripts/seeder/utils/data-generators.ts
+++ b/packages/shared/scripts/seeder/utils/data-generators.ts
@@ -759,6 +759,8 @@ export class DataGenerator {
);
// 6. GENERATION - Final summary generation
+ const toolObservation = observations[observations.length - 1];
+ const toolName = toolObservation.name || "WebSearchTool";
observations.push(
createObservation({
id: `${traceId}-generation`,
@@ -800,6 +802,14 @@ export class DataGenerator {
output: this.randomInt(35, 45) / 100000,
total: this.randomInt(50, 70) / 100000,
},
+ tool_definitions: {
+ WebSearchTool: "Search the web for information",
+ CalculatorTool: "Perform mathematical calculations",
+ WeatherForecastTool: "Get weather forecasts and data",
+ EmailSenderTool: "Send emails to recipients",
+ },
+ tool_calls: ["call_workflow_1"],
+ tool_call_names: [toolName],
}),
);
@@ -1121,6 +1131,16 @@ export class DataGenerator {
updated_at: end,
event_ts: start,
is_deleted: 0,
+ tool_definitions: d.tool
+ ? {
+ "billing.lookup":
+ "Look up billing records and transaction history",
+ "billing.refund":
+ "Issue refunds for duplicate or erroneous charges",
+ }
+ : undefined,
+ tool_calls: d.tool ? [`call_${index}`] : undefined,
+ tool_call_names: d.tool ? [d.tool.name] : undefined,
};
if (!d.tool) return [baseGen];
@@ -1157,6 +1177,8 @@ export class DataGenerator {
updated_at: start - 5,
event_ts: start - 40,
is_deleted: 0,
+ tool_definitions: undefined,
+ tool_calls: undefined,
};
return [toolObs, baseGen];
diff --git a/packages/shared/src/domain/observations.ts b/packages/shared/src/domain/observations.ts
index d5098659bc..9c0ff13e23 100644
--- a/packages/shared/src/domain/observations.ts
+++ b/packages/shared/src/domain/observations.ts
@@ -93,6 +93,10 @@ export const ObservationSchema = z.object({
// pricing tier information
usagePricingTierId: z.string().nullable(),
usagePricingTierName: z.string().nullable(),
+ // tool data
+ toolDefinitions: z.record(z.string(), z.string()).nullable(),
+ toolCalls: z.array(z.string()).nullable(),
+ toolCallNames: z.array(z.string()).nullable(),
});
export type Observation = z.infer<typeof ObservationSchema>;
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index ae468721d9..a4f2053e75 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -16,6 +16,7 @@ export * from "./utils/objects";
export * from "./utils/typeChecks";
export * from "./utils/prompts";
export * from "./utils/jsonSchemaValidation";
+export * from "./utils/chatml";
export * from "./features/entitlements/plans";
export * from "./interfaces/rate-limits";
export * from "./tableDefinitions/typeHelpers";
diff --git a/packages/shared/src/observationsTable.ts b/packages/shared/src/observationsTable.ts
index 32d3771e45..384532e05c 100644
--- a/packages/shared/src/observationsTable.ts
+++ b/packages/shared/src/observationsTable.ts
@@ -232,6 +232,36 @@ export const observationsTableCols: ColumnDefinition[] = [
type: "string",
internal: "", // handled by comment filter helpers
},
+ {
+ name: "Available Tool Names",
+ id: "toolNames",
+ type: "arrayOptions",
+ internal: "", // ClickHouse only - uses mapKeys(tool_definitions)
+ options: [], // to be added at runtime
+ nullable: true,
+ },
+ {
+ name: "Called Tool Names",
+ id: "calledToolNames",
+ type: "arrayOptions",
+ internal: "", // ClickHouse only - uses tool_call_names
+ options: [], // to be added at runtime
+ nullable: true,
+ },
+ {
+ name: "Available Tools",
+ id: "toolDefinitions",
+ type: "number",
+ internal: "", // ClickHouse only
+ nullable: true,
+ },
+ {
+ name: "Tool Calls",
+ id: "toolCalls",
+ type: "number",
+ internal: "", // ClickHouse only
+ nullable: true,
+ },
];
// to be used client side, insert options for use in filter-builder
@@ -247,6 +277,8 @@ export type ObservationOptions = {
promptName: Array<SingleValueOption>;
tags: Array<SingleValueOption>;
type: Array<SingleValueOption>;
+ toolNames: Array<SingleValueOption>;
+ calledToolNames: Array<SingleValueOption>;
};
export function observationsTableColsWithOptions(
@@ -283,6 +315,12 @@ export function observationsTableColsWithOptions(
if (col.id === "type") {
return formatColumnOptions(col, options?.type ?? []);
}
+ if (col.id === "toolNames") {
+ return formatColumnOptions(col, options?.toolNames ?? []);
+ }
+ if (col.id === "calledToolNames") {
+ return formatColumnOptions(col, options?.calledToolNames ?? []);
+ }
return col;
});
}
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 0887737f94..2ca399026e 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -35,10 +35,12 @@ export * from "./clickhouse/client";
export * from "./clickhouse/schemaUtils";
export * from "./clickhouse/schema";
export * from "./repositories/definitions";
+export * from "../utils/IORepresentation/chatML/types";
export * from "../server/ingestion/types";
export * from "../server/ingestion/modelMatch";
export * from "./ingestion/processEventBatch";
export * from "../server/ingestion/validateAndInflateScore";
+export * from "./ingestion/extractToolsBackend";
export * from "../server/queries/public-api-filter-builder";
export * from "../server/pricing-tiers";
export * from "./redis/redis";
diff --git a/packages/shared/src/server/ingestion/extractToolsBackend.ts b/packages/shared/src/server/ingestion/extractToolsBackend.ts
new file mode 100644
index 0000000000..3f04e13e85
--- /dev/null
+++ b/packages/shared/src/server/ingestion/extractToolsBackend.ts
@@ -0,0 +1,387 @@
+import { z } from "zod/v4";
+
+/**
+ * ClickHouse storage schema for tool definitions.
+ *
+ * Based on ToolDefinitionSchema from packages/shared/src/utils/IORepresentation/chatML/types.ts
+ * `parameters` stored as JSON string instead of z.record
+ */
+export const ClickhouseToolDefinitionSchema = z.object({
+ name: z.string(),
+ description: z.string().optional(),
+ parameters: z.string().optional(), // JSON string of parameters schema
+});
+export type ClickhouseToolDefinition = z.infer<
+ typeof ClickhouseToolDefinitionSchema
+>;
+
+/**
+ * ClickHouse storage schema for tool calls (invocations).
+ *
+ * Based on ToolCallSchema from packages/shared/src/utils/IORepresentation/chatML/types.ts
+ * Adapted for ClickHouse Array(JSON) storage:
+ * - `arguments` stored as JSON string (base may have parsed object)
+ * - `index` optional field included for parallel tool call ordering
+ */
+export const ClickhouseToolArgumentSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ arguments: z.string(), // JSON string of call arguments
+ type: z.string().optional(),
+ index: z.number().optional(),
+});
+export type ClickhouseToolArgument = z.infer<
+ typeof ClickhouseToolArgumentSchema
+>;
+
+/**
+ * Flatten tool definition from nested or flat format.
+ * Handles both OpenAI Chat Completions {type, function: {name, ...}} and flat {name, ...}.
+ */
+function flattenToolDefinition(tool: unknown): {
+ name?: string;
+ description?: string;
+ parameters?: unknown;
+} {
+ if (!tool || typeof tool !== "object") return {};
+ const t = tool as Record<string, unknown>;
+
+ // Handle nested {type, function: {name, ...}} format (OpenAI Chat Completions)
+ const toolData = (t.function as Record<string, unknown> | undefined) ?? t;
+
+ return {
+ name: toolData.name as string | undefined,
+ description: (toolData.description ?? toolData.desc) as string | undefined,
+ parameters:
+ toolData.parameters ??
+ toolData.parameters_json_schema ??
+ toolData.inputSchema,
+ };
+}
+
+/**
+ * Flatten tool call from nested or flat format.
+ * Handles OpenAI {function: {name, arguments}} and flat {name, arguments}.
+ */
+function flattenToolCall(call: unknown): {
+ id?: string;
+ name?: string;
+ arguments?: string;
+ type?: string;
+ index?: number;
+} {
+ if (!call || typeof call !== "object") return {};
+ const c = call as Record<string, unknown>;
+
+ // Handle nested {function: {name, arguments}} format
+ const func = c.function as Record<string, unknown> | undefined;
+ const name = (func?.name ?? c.name ?? c.toolName) as string | undefined;
+ const rawArgs = func?.arguments ?? c.arguments ?? c.args;
+ const args =
+ typeof rawArgs === "string" ? rawArgs : JSON.stringify(rawArgs ?? {});
+
+ return {
+ id: (c.id ?? c.toolCallId ?? c.call_id) as string | undefined,
+ name,
+ arguments: args,
+ type: (c.type ?? (func ? "function" : undefined)) as string | undefined,
+ index: c.index as number | undefined,
+ };
+}
+
+/**
+ * Helper to add a tool definition, deduplicating by name.
+ */
+function addToolDefinition(
+ definitions: ClickhouseToolDefinition[],
+ tool: unknown,
+): void {
+ const flattened = flattenToolDefinition(tool);
+ if (!flattened.name) return; // Skip invalid tools
+
+ const normalized: ClickhouseToolDefinition = {
+ name: flattened.name,
+ description: flattened.description,
+ parameters: flattened.parameters
+ ? JSON.stringify(flattened.parameters)
+ : undefined,
+ };
+
+ // Deduplicate by name
+ if (!definitions.some((t) => t.name === normalized.name)) {
+ definitions.push(normalized);
+ }
+}
+
+/**
+ * Helper to add a tool call/argument.
+ */
+function addToolArgument(args: ClickhouseToolArgument[], call: unknown): void {
+ const flattened = flattenToolCall(call);
+ if (!flattened.name) return; // Skip invalid calls
+
+ args.push({
+ id: flattened.id ?? "",
+ name: flattened.name,
+ arguments: flattened.arguments ?? "{}",
+ type: flattened.type,
+ index: flattened.index,
+ });
+}
+
+/**
+ * Extract tool definitions from raw input data (top-level tools array).
+ */
+function extractToolsFromRawInput(
+ input: unknown,
+ definitions: ClickhouseToolDefinition[],
+): void {
+ if (!input || typeof input !== "object") return;
+
+ const obj = Array.isArray(input)
+ ? { messages: input }
+ : (input as Record<string, unknown>);
+
+ // Top-level tools array (OpenAI request format)
+ if (Array.isArray(obj.tools)) {
+ for (const tool of obj.tools) {
+ addToolDefinition(definitions, tool);
+ }
+ }
+
+ // Messages array with tools on individual messages
+ if (Array.isArray(obj.messages)) {
+ for (const msg of obj.messages) {
+ if (msg && typeof msg === "object") {
+ // Standard tools array on message
+ if (Array.isArray((msg as any).tools)) {
+ for (const tool of (msg as any).tools) {
+ addToolDefinition(definitions, tool);
+ }
+ }
+
+ // LangGraph format: tool definition in role:"tool" message content
+ // TODO: This should be handled by langgraph adapter preprocessing in the future
+ if (
+ (msg as any).role === "tool" &&
+ (msg as any).content?.type === "function" &&
+ (msg as any).content?.function
+ ) {
+ addToolDefinition(definitions, (msg as any).content);
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Extract tool calls from raw output data.
+ */
+function extractToolCallsFromRawOutput(
+ output: unknown,
+ args: ClickhouseToolArgument[],
+): void {
+ if (!output) return;
+
+ // Array of messages
+ if (Array.isArray(output)) {
+ for (const msg of output) {
+ if (msg && typeof msg === "object") {
+ extractToolCallsFromMessage(msg as Record<string, unknown>, args);
+ }
+ }
+ return;
+ }
+
+ if (typeof output !== "object") return;
+ const obj = output as Record<string, unknown>;
+
+ // Direct tool_calls at top level
+ if (Array.isArray(obj.tool_calls)) {
+ for (const call of obj.tool_calls) {
+ addToolArgument(args, call);
+ }
+ }
+
+ // OpenAI choices format: {choices: [{message: {tool_calls: [...]}}]}
+ if (Array.isArray(obj.choices)) {
+ for (const choice of obj.choices) {
+ if (choice && typeof choice === "object") {
+ const c = choice as Record<string, unknown>;
+ const message = c.message as Record<string, unknown> | undefined;
+ if (message && Array.isArray(message.tool_calls)) {
+ for (const call of message.tool_calls) {
+ addToolArgument(args, call);
+ }
+ }
+ }
+ }
+ }
+
+ // Anthropic tool_use in content array: {content: [{type: "tool_use", ...}]}
+ if (Array.isArray(obj.content)) {
+ for (const part of obj.content) {
+ if (
+ part &&
+ typeof part === "object" &&
+ (part as Record<string, unknown>).type === "tool_use"
+ ) {
+ const p = part as Record<string, unknown>;
+ addToolArgument(args, {
+ id: p.id,
+ name: p.name,
+ arguments: JSON.stringify(p.input ?? {}),
+ type: "tool_use",
+ });
+ }
+ }
+ }
+
+ // LangChain additional_kwargs: {additional_kwargs: {tool_calls: [...]}}
+ const additionalKwargs = obj.additional_kwargs as
+ | Record<string, unknown>
+ | undefined;
+ if (additionalKwargs && Array.isArray(additionalKwargs.tool_calls)) {
+ for (const call of additionalKwargs.tool_calls) {
+ addToolArgument(args, call);
+ }
+ }
+}
+
+/**
+ * Extract tool calls from a single message object.
+ */
+function extractToolCallsFromMessage(
+ msg: Record<string, unknown>,
+ args: ClickhouseToolArgument[],
+): void {
+ if (Array.isArray(msg.tool_calls)) {
+ for (const call of msg.tool_calls) {
+ addToolArgument(args, call);
+ }
+ }
+
+ // Anthropic content array
+ if (Array.isArray(msg.content)) {
+ for (const part of msg.content) {
+ if (
+ part &&
+ typeof part === "object" &&
+ (part as Record<string, unknown>).type === "tool_use"
+ ) {
+ const p = part as Record<string, unknown>;
+ addToolArgument(args, {
+ id: p.id,
+ name: p.name,
+ arguments: JSON.stringify(p.input ?? {}),
+ type: "tool_use",
+ });
+ }
+ }
+ }
+}
+
+/**
+ * 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;
+}
+
+/**
+ * Extract tool definitions and arguments from observation input/output.
+ * Extracts directly from raw input/output formats.
+ *
+ * @param input - Raw observation input (object or JSON string)
+ * @param output - Raw observation output (object or JSON string)
+ * @returns Object with toolDefinitions and toolArguments arrays
+ */
+export function extractToolsFromObservation(
+ input: unknown,
+ output: unknown,
+): {
+ toolDefinitions: ClickhouseToolDefinition[];
+ toolArguments: ClickhouseToolArgument[];
+} {
+ try {
+ const toolDefinitions: ClickhouseToolDefinition[] = [];
+ const toolArguments: ClickhouseToolArgument[] = [];
+
+ const parsedInput = parseIfString(input);
+ const parsedOutput = parseIfString(output);
+
+ extractToolsFromRawInput(parsedInput, toolDefinitions);
+ extractToolCallsFromRawOutput(parsedOutput, toolArguments);
+
+ // Deduplicate tool arguments by id
+ const seenIds = new Set<string>();
+ const uniqueArgs = toolArguments.filter((arg) => {
+ const key = arg.id || `${arg.name}-${arg.arguments}`;
+ if (seenIds.has(key)) return false;
+ seenIds.add(key);
+ return true;
+ });
+
+ return { toolDefinitions, toolArguments: uniqueArgs };
+ } catch (error) {
+ console.error("Tool extraction error:", error);
+ return { toolDefinitions: [], toolArguments: [] };
+ }
+}
+
+/**
+ * Convert array of tool definitions to Map format for ClickHouse.
+ * Key: tool name, Value: JSON string of {description, parameters}
+ */
+export function convertDefinitionsToMap(
+ definitions: ClickhouseToolDefinition[],
+): Record<string, string> {
+ const map: Record<string, string> = {};
+ for (const def of definitions) {
+ // Last definition wins if duplicate names (shouldn't happen after dedup)
+ map[def.name] = JSON.stringify({
+ description: def.description ?? "",
+ parameters: def.parameters ?? "",
+ });
+ }
+ return map;
+}
+
+/**
+ * Convert array of tool calls to parallel arrays for ClickHouse.
+ *
+ * Returns:
+ * - tool_calls: Array of JSON strings containing {id, arguments, type, index} (NO name)
+ * - tool_call_names: Array of names in the same order as tool_calls
+ *
+ * This structure enables efficient filtering by name using has(tool_call_names, 'name')
+ * without needing to parse JSON.
+ */
+export function convertCallsToArrays(args: ClickhouseToolArgument[]): {
+ tool_calls: string[];
+ tool_call_names: string[];
+} {
+ const tool_calls: string[] = [];
+ const tool_call_names: string[] = [];
+
+ for (const arg of args) {
+ tool_call_names.push(arg.name);
+ tool_calls.push(
+ JSON.stringify({
+ id: arg.id,
+ arguments: arg.arguments ?? "{}",
+ type: arg.type ?? "",
+ index: arg.index ?? 0,
+ }),
+ );
+ }
+
+ return { tool_calls, tool_call_names };
+}
diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.ts
index f22ab4a0b0..3345f76a87 100644
--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts
+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts
@@ -1187,6 +1187,10 @@ export class OtelIngestionProcessor {
]),
);
+ // TODO: Map gen_ai.tool.definitions to input.tools for backend extraction
+ // const toolDefs = attributes["gen_ai.tool.definitions"] || attributes["model_request_parameters"]?.function_tools;
+ // if (toolDefs && input && typeof input === "object") { input = { ...input, tools: toolDefs }; }
+
// Langfuse
input =
domain === "trace" && attributes[LangfuseOtelSpanAttributes.TRACE_INPUT]
diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
index d1d23e47b4..9d996a17e3 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
@@ -49,6 +49,11 @@ const EVENTS_FIELDS = {
promptName: 'e.prompt_name as "prompt_name"',
promptVersion: 'e.prompt_version as "prompt_version"',
+ // Tool fields
+ toolDefinitions: 'e.tool_definitions as "tool_definitions"',
+ toolCalls: 'e.tool_calls as "tool_calls"',
+ toolCallNames: 'e.tool_call_names as "tool_call_names"',
+
// I/O & metadata fields
input: "e.input",
output: "e.output",
@@ -99,10 +104,14 @@ const FIELD_SETS = {
"internalModelId",
"userId",
"sessionId",
+ "toolDefinitions",
+ "toolCalls",
+ "toolCallNames",
],
calculated: ["latency", "timeToFirstToken"],
io: ["input", "output"],
metadata: ["metadata"],
+ tools: ["toolDefinitions", "toolCalls", "toolCallNames"],
eventTs: ["eventTs"],
// getById field sets (reuse the same fields - all queries use `FROM events e`)
@@ -120,6 +129,9 @@ const FIELD_SETS = {
"level",
"statusMessage",
"version",
+ "toolDefinitions",
+ "toolCalls",
+ "toolCallNames",
],
byIdModel: [
"providedModelName",
diff --git a/packages/shared/src/server/queries/createGenerationsQuery.ts b/packages/shared/src/server/queries/createGenerationsQuery.ts
index 49222b066d..417bf44b90 100644
--- a/packages/shared/src/server/queries/createGenerationsQuery.ts
+++ b/packages/shared/src/server/queries/createGenerationsQuery.ts
@@ -15,6 +15,10 @@ type AdditionalObservationFields = {
traceName: string | null;
traceTags: Array<string>;
traceTimestamp: Date | null;
+ // Tool counts for list view performance
+ // (actual data fields: toolDefinitions, toolCalls, toolCallNames come from Observation domain type)
+ toolDefinitionsCount: number | null;
+ toolCallsCount: number | null;
} & ObservationPriceFields;
export type FullObservation = AdditionalObservationFields & Observation;
diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.ts
index 738492c3fa..6af64cc6ef 100644
--- a/packages/shared/src/server/repositories/definitions.ts
+++ b/packages/shared/src/server/repositories/definitions.ts
@@ -53,6 +53,9 @@ export const observationRecordBaseSchema = z.object({
prompt_id: z.string().nullish(),
prompt_name: z.string().nullish(),
prompt_version: z.number().nullish(),
+ tool_definitions: z.record(z.string(), z.string()).optional(),
+ tool_calls: z.array(z.string()).optional(),
+ tool_call_names: z.array(z.string()).optional(),
is_deleted: z.number(),
});
@@ -416,6 +419,11 @@ export const convertTraceToStagingObservation = (
prompt_name: undefined,
prompt_version: undefined,
+ // Tool fields - traces don't have tools
+ tool_definitions: undefined,
+ tool_calls: undefined,
+ tool_call_names: undefined,
+
// System fields
created_at: traceRecord.created_at,
updated_at: traceRecord.updated_at,
@@ -570,6 +578,10 @@ export const convertPostgresObservationToInsert = (
prompt_id: observation.prompt_id,
prompt_name: observation.prompt_name,
prompt_version: observation.prompt_version,
+ // Tool fields - Postgres observations don't have persisted tools
+ tool_definitions: undefined,
+ tool_calls: undefined,
+ tool_call_names: undefined,
created_at: observation.created_at?.getTime(),
updated_at: observation.updated_at?.getTime(),
event_ts: observation.start_time?.getTime(),
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index dcc2e130b9..3558a3822c 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -186,6 +186,13 @@ async function enrichObservationsWithTraceFields(
traceName: o.name ?? null,
traceTags: [], // TODO pull from PG
traceTimestamp: null,
+ toolDefinitions: o.toolDefinitions ?? null,
+ toolCalls: o.toolCalls ?? null,
+ // Compute counts from actual data for events table
+ toolDefinitionsCount: o.toolDefinitions
+ ? Object.keys(o.toolDefinitions).length
+ : null,
+ toolCallsCount: o.toolCalls ? o.toolCalls.length : null,
};
});
}
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 7234cf5bb2..d185b18cd9 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -174,6 +174,9 @@ export const getObservationsForTrace = async <IncludeIO extends boolean>(
prompt_id,
prompt_name,
prompt_version,
+ tool_definitions,
+ tool_calls,
+ tool_call_names,
created_at,
updated_at,
event_ts
@@ -291,6 +294,9 @@ export const getObservationForTraceIdByName = async ({
prompt_id,
prompt_name,
prompt_version,
+ tool_definitions,
+ tool_calls,
+ tool_call_names,
created_at,
updated_at,
event_ts
@@ -413,6 +419,9 @@ export const getObservationsById = async (
prompt_id,
prompt_name,
prompt_version,
+ tool_definitions,
+ tool_calls,
+ tool_call_names,
created_at,
updated_at,
event_ts
@@ -477,6 +486,9 @@ const getObservationByIdInternal = async ({
prompt_id,
prompt_name,
prompt_version,
+ tool_definitions,
+ tool_calls,
+ tool_call_names,
created_at,
updated_at,
event_ts
@@ -527,6 +539,9 @@ export type ObservationsTableQueryResult = ObservationRecordReadType & {
trace_tags?: string[];
trace_name?: string;
trace_user_id?: string;
+ // Tool counts for list view performance (ClickHouse numbers as strings)
+ tool_definitions_count?: string;
+ tool_calls_count?: string;
};
export const getObservationsTableCount = async (
@@ -600,6 +615,11 @@ export const getObservationsTableWithModelData = async (
traceTags: trace?.tags ?? [],
traceTimestamp: trace?.timestamp ?? null,
userId: trace?.userId ?? null,
+ // Tool counts for list view (actual data in toolDefinitions/toolCalls from domain)
+ toolDefinitionsCount: o.tool_definitions_count
+ ? Number(o.tool_definitions_count)
+ : null,
+ toolCallsCount: o.tool_calls_count ? Number(o.tool_calls_count) : null,
...enrichObservationWithModelData(model),
};
});
@@ -644,7 +664,9 @@ const getObservationsTableInternal = async <T>(
o.prompt_version as "prompt_version",
internal_model_id as "internal_model_id",
if(isNull(end_time), NULL, date_diff('millisecond', start_time, end_time)) as latency,
- if(isNull(completion_start_time), NULL, date_diff('millisecond', start_time, completion_start_time)) as "time_to_first_token"`;
+ if(isNull(completion_start_time), NULL, date_diff('millisecond', start_time, completion_start_time)) as "time_to_first_token",
+ length(mapKeys(o.tool_definitions)) as "tool_definitions_count",
+ length(o.tool_calls) as "tool_calls_count"`;
const {
projectId,
@@ -994,6 +1016,102 @@ export const getObservationsGroupedByName = async (
return res;
};
+export const getObservationsGroupedByToolName = async (
+ projectId: string,
+ filter: FilterState,
+) => {
+ const observationsFilter = new FilterList([
+ new StringFilter({
+ clickhouseTable: "observations",
+ field: "project_id",
+ operator: "=",
+ value: projectId,
+ tablePrefix: "o",
+ }),
+ ]);
+
+ observationsFilter.push(
+ ...createFilterFromFilterState(
+ filter,
+ observationsTableUiColumnDefinitions,
+ ),
+ );
+
+ const appliedObservationsFilter = observationsFilter.apply();
+
+ const query = `
+ SELECT arrayJoin(mapKeys(o.tool_definitions)) as toolName
+ FROM observations o
+ WHERE ${appliedObservationsFilter.query}
+ AND length(mapKeys(o.tool_definitions)) > 0
+ GROUP BY toolName
+ ORDER BY count() DESC
+ LIMIT 1000;
+ `;
+
+ const res = await queryClickhouse<{ toolName: string }>({
+ query,
+ params: {
+ ...appliedObservationsFilter.params,
+ },
+ tags: {
+ feature: "tracing",
+ type: "observation",
+ kind: "analytic",
+ projectId,
+ },
+ });
+ return res;
+};
+
+export const getObservationsGroupedByCalledToolName = async (
+ projectId: string,
+ filter: FilterState,
+) => {
+ const observationsFilter = new FilterList([
+ new StringFilter({
+ clickhouseTable: "observations",
+ field: "project_id",
+ operator: "=",
+ value: projectId,
+ tablePrefix: "o",
+ }),
+ ]);
+
+ observationsFilter.push(
+ ...createFilterFromFilterState(
+ filter,
+ observationsTableUiColumnDefinitions,
+ ),
+ );
+
+ const appliedObservationsFilter = observationsFilter.apply();
+
+ const query = `
+ SELECT arrayJoin(o.tool_call_names) as calledToolName
+ FROM observations o
+ WHERE ${appliedObservationsFilter.query}
+ AND length(o.tool_call_names) > 0
+ GROUP BY calledToolName
+ ORDER BY count() DESC
+ LIMIT 1000;
+ `;
+
+ const res = await queryClickhouse<{ calledToolName: string }>({
+ query,
+ params: {
+ ...appliedObservationsFilter.params,
+ },
+ tags: {
+ feature: "tracing",
+ type: "observation",
+ kind: "analytic",
+ projectId,
+ },
+ });
+ return res;
+};
+
export const getObservationsGroupedByPromptName = async (
projectId: string,
filter: FilterState,
diff --git a/packages/shared/src/server/repositories/observations_converters.ts b/packages/shared/src/server/repositories/observations_converters.ts
index ed7a29dc32..91906ccc5e 100644
--- a/packages/shared/src/server/repositories/observations_converters.ts
+++ b/packages/shared/src/server/repositories/observations_converters.ts
@@ -245,6 +245,17 @@ export function convertObservationPartial(
usagePricingTierName: record.usage_pricing_tier_name ?? null,
}),
+ // Tool fields
+ ...(record.tool_definitions !== undefined && {
+ toolDefinitions: record.tool_definitions ?? null,
+ }),
+ ...(record.tool_calls !== undefined && {
+ toolCalls: record.tool_calls ?? null,
+ }),
+ ...(record.tool_call_names !== undefined && {
+ toolCallNames: record.tool_call_names ?? null,
+ }),
+
// Metrics (calculated fields)
...((record.end_time !== undefined || record.start_time !== undefined) && {
latency:
@@ -310,6 +321,9 @@ export function convertObservationPartial(
totalUsage: partial.totalUsage ?? 0,
usagePricingTierId: partial.usagePricingTierId ?? null,
usagePricingTierName: partial.usagePricingTierName ?? null,
+ toolDefinitions: partial.toolDefinitions ?? null,
+ toolCalls: partial.toolCalls ?? null,
+ toolCallNames: partial.toolCallNames ?? null,
};
}
diff --git a/packages/shared/src/server/tableMappings/mapObservationsTable.ts b/packages/shared/src/server/tableMappings/mapObservationsTable.ts
index 56b1565579..6be96bcad5 100644
--- a/packages/shared/src/server/tableMappings/mapObservationsTable.ts
+++ b/packages/shared/src/server/tableMappings/mapObservationsTable.ts
@@ -227,4 +227,28 @@ export const observationsTableUiColumnDefinitions: UiColumnMappings = [
clickhouseTableName: "observations",
clickhouseSelect: "o.prompt_version",
},
+ {
+ uiTableName: "Available Tools",
+ uiTableId: "toolDefinitions",
+ clickhouseTableName: "observations",
+ clickhouseSelect: "length(mapKeys(o.tool_definitions))",
+ },
+ {
+ uiTableName: "Tool Calls",
+ uiTableId: "toolCalls",
+ clickhouseTableName: "observations",
+ clickhouseSelect: "length(o.tool_calls)",
+ },
+ {
+ uiTableName: "Tool Names",
+ uiTableId: "toolNames",
+ clickhouseTableName: "observations",
+ clickhouseSelect: "mapKeys(o.tool_definitions)",
+ },
+ {
+ uiTableName: "Called Tool Names",
+ uiTableId: "calledToolNames",
+ clickhouseTableName: "observations",
+ clickhouseSelect: "o.tool_call_names",
+ },
];
diff --git a/packages/shared/src/server/test-utils/tracing-factory.ts b/packages/shared/src/server/test-utils/tracing-factory.ts
index 12727b15ee..8b301c19b9 100644
--- a/packages/shared/src/server/test-utils/tracing-factory.ts
+++ b/packages/shared/src/server/test-utils/tracing-factory.ts
@@ -98,6 +98,9 @@ export const createObservation = (
prompt_version: 1,
end_time: Date.now(),
completion_start_time: Date.now(),
+ tool_definitions: {},
+ tool_calls: [],
+ tool_call_names: [],
...observation,
};
};
diff --git a/packages/shared/src/tableDefinitions/mapDashboards.ts b/packages/shared/src/tableDefinitions/mapDashboards.ts
index ec85afabac..d08123d2e1 100644
--- a/packages/shared/src/tableDefinitions/mapDashboards.ts
+++ b/packages/shared/src/tableDefinitions/mapDashboards.ts
@@ -93,6 +93,12 @@ export const dashboardColumnDefinitions: UiColumnMappings = [
uiTableId: "model",
uiTableName: "Model",
},
+ {
+ clickhouseTableName: "observations",
+ clickhouseSelect: "mapKeys(tool_definitions)",
+ uiTableId: "toolNames",
+ uiTableName: "Tool Names",
+ },
{
clickhouseTableName: "traces",
clickhouseSelect: "environment",
diff --git a/packages/shared/src/utils/IORepresentation/chatML/types.ts b/packages/shared/src/utils/IORepresentation/chatML/types.ts
index 9b084ef9ca..3764eb715d 100644
--- a/packages/shared/src/utils/IORepresentation/chatML/types.ts
+++ b/packages/shared/src/utils/IORepresentation/chatML/types.ts
@@ -4,7 +4,7 @@ import { z } from "zod/v4";
* Schema for tool/function definitions in ChatML.
* Used to define available tools for LLM function calling.
*/
-const ToolDefinitionSchema = z.object({
+export const ToolDefinitionSchema = z.object({
name: z.string(),
description: z.string().optional(),
parameters: z.record(z.string(), z.any()).optional(),
@@ -14,7 +14,7 @@ const ToolDefinitionSchema = z.object({
* Schema for tool/function call invocations in ChatML.
* Represents an LLM's request to call a specific tool.
*/
-const ToolCallSchema = z.object({
+export const ToolCallSchema = z.object({
id: z.string(),
name: z.string(),
arguments: z.string(), // JSON string of arguments
@@ -246,3 +246,49 @@ const SimpleChatMessageSchema = z
* Used for backend extraction - validates array has at least one message.
*/
export const SimpleChatMlArraySchema = z.array(SimpleChatMessageSchema).min(1);
+
+/**
+ * Full ChatML message schema with frontend transforms.
+ *
+ * NOTE: Moved to shared package to enable testing.
+ * Reason: Worker tests cannot import from web package and
+ * in the current setup web tests cannot import from shared.
+ * Therefore, we moved frontend specific transformation logic to the
+ * shared package for now, until web tests can import from shared.
+ *
+ * Includes transforms for frontend rendering:
+ * - Spreads additional_kwargs into message (makes fields accessible)
+ * - Moves unknown fields to json property (enables PrettyJsonView)
+ */
+export const ChatMlMessageSchema = BaseChatMlMessageSchema.refine(
+ (value) => value.content !== null || value.role !== undefined,
+)
+ .transform(({ additional_kwargs, ...other }) => ({
+ ...other,
+ ...additional_kwargs,
+ }))
+ .transform(
+ ({
+ role,
+ name,
+ content,
+ audio,
+ type,
+ tools,
+ tool_calls,
+ tool_call_id,
+ ...other
+ }) => ({
+ role,
+ name,
+ content,
+ audio,
+ type,
+ tools,
+ tool_calls,
+ tool_call_id,
+ ...(Object.keys(other).length === 0 ? {} : { json: other }),
+ }),
+ );
+
+export const ChatMlArraySchema = z.array(ChatMlMessageSchema).min(1);
diff --git a/packages/shared/src/utils/chatml/adapters/aisdk.ts b/packages/shared/src/utils/chatml/adapters/aisdk.ts
new file mode 100644
index 0000000000..c211592308
--- /dev/null
+++ b/packages/shared/src/utils/chatml/adapters/aisdk.ts
@@ -0,0 +1,496 @@
+import type { NormalizerContext, ProviderAdapter } from "../types";
+import {
+ removeNullFields,
+ stringifyToolResultContent,
+ parseMetadata,
+ isRichToolResult,
+} from "../helpers";
+import { z } from "zod/v4";
+
+/**
+ * AI SDK v5 Adapter
+ *
+ * Handles traces from Vercel AI SDK v5 with any model provider
+ *
+ * Key characteristics:
+ * - Observation names: ai.generateText.doGenerate, ai.generateObject.doGenerate
+ * - Metadata: ai.operationId, ai.model.provider, ai.model.id
+ * - Message structure: {role, content: [{type, text/toolCallId/...}]}
+ * - Tool calls: {type: "tool-call", toolCallId, toolName, input|args}
+ * - Tool results: {type: "tool-result", toolCallId, toolName, output|result}
+ */
+
+// Message with AI SDK v5 tool-call content structure
+const AISDKToolCallMessageSchema = z.looseObject({
+ role: z.string(),
+ content: z.array(
+ z.looseObject({
+ type: z.literal("tool-call"),
+ toolCallId: z.string(),
+ toolName: z.string(),
+ }),
+ ),
+});
+
+// Message with AI SDK v5 tool-result content structure
+const AISDKToolResultMessageSchema = z.looseObject({
+ role: z.literal("tool"),
+ content: z.array(
+ z.looseObject({
+ type: z.literal("tool-result"),
+ toolCallId: z.string(),
+ toolName: z.string(),
+ }),
+ ),
+});
+
+// Message array with AI SDK v5 patterns
+const AISDKMessagesArraySchema = z
+ .array(
+ z.looseObject({
+ role: z.string(),
+ content: z
+ .union([z.string(), z.array(z.looseObject({ type: z.string() }))])
+ .optional(),
+ }),
+ )
+ .refine(
+ (messages) => {
+ // Must have at least one message with AI SDK v5 structured content
+ return messages.some(
+ (msg) =>
+ Array.isArray(msg.content) &&
+ msg.content.some(
+ (item: unknown) =>
+ (item &&
+ typeof item === "object" &&
+ "type" in item &&
+ (item as Record<string, unknown>).type === "tool-call") ||
+ (item as Record<string, unknown>).type === "tool-result",
+ ),
+ );
+ },
+ { message: "Must have AI SDK v5 tool-call or tool-result patterns" },
+ );
+
+// Array of raw tool call objects, format as seen on OUTPUTs
+// Example: [{toolCallId: "...", toolName: "...", input: {...}}, ...]
+const AISDKRawToolCallArraySchema = z
+ .array(
+ z.looseObject({
+ toolCallId: z.string(),
+ toolName: z.string(),
+ // Can have either 'input' (OpenAI) or 'args' (Bedrock)
+ }),
+ )
+ .refine((arr) => arr.length > 0, {
+ message: "Must have at least one tool call",
+ });
+
+// normalize a single AI SDK v5 message to ChatML format
+// we don't want additional fields here to get clean rendering
+function normalizeMessage(msg: unknown): Record<string, unknown> {
+ if (!msg || typeof msg !== "object") return {};
+
+ let working = msg as Record<string, unknown>;
+
+ // Strip provider-specific metadata (Bedrock, OpenAI, etc.)
+ const {
+ providerMetadata: _providerMetadata,
+ providerOptions: _providerOptions,
+ ...withoutProviderFields
+ } = working;
+ working = withoutProviderFields;
+
+ let normalized = removeNullFields(working);
+
+ // Normalize content: [{type: "text", text: "..."}] → string
+ if (
+ normalized.content &&
+ Array.isArray(normalized.content) &&
+ normalized.content.length > 0
+ ) {
+ // all text already or do we need to normalize further?
+ const allTextItems = normalized.content.every(
+ (item: unknown) =>
+ item &&
+ typeof item === "object" &&
+ (item as Record<string, unknown>).type === "text" &&
+ typeof (item as Record<string, unknown>).text === "string",
+ );
+
+ if (allTextItems && normalized.content.length === 1) {
+ // Single text item: extract the text
+ const firstItem = normalized.content[0] as Record<string, unknown>;
+ normalized.content = firstItem.text;
+ } else if (allTextItems && normalized.content.length > 1) {
+ // Multiple text items: concatenate
+ const texts = normalized.content.map(
+ (item: unknown) => (item as Record<string, unknown>).text,
+ );
+ normalized.content = texts.join("");
+ } else {
+ // Mixed content or tool-calls/tool-results: normalize each item
+ normalized.content = normalized.content.map((item: unknown) => {
+ if (!item || typeof item !== "object") return item;
+
+ const contentItem = item as Record<string, unknown>;
+
+ // Handle tool-call content item
+ // {type: "tool-call", toolCallId, toolName, input|args, providerOptions}
+ if (contentItem.type === "tool-call") {
+ const { providerOptions: _po, ...cleanedItem } = contentItem;
+
+ // Normalize args|input to arguments
+ const args = contentItem.args ?? contentItem.input;
+ return {
+ ...cleanedItem,
+ arguments:
+ typeof args === "string" ? args : JSON.stringify(args ?? {}),
+ };
+ }
+
+ // Handle tool-result content item
+ // {type: "tool-result", toolCallId, toolName, output|result}
+ if (contentItem.type === "tool-result") {
+ // Normalize output|result to content
+ const resultValue = contentItem.output ?? contentItem.result;
+
+ // If result has nested {type: "text", value: "..."}, extract value
+ if (
+ resultValue &&
+ typeof resultValue === "object" &&
+ !Array.isArray(resultValue) &&
+ (resultValue as Record<string, unknown>).type === "text" &&
+ "value" in (resultValue as Record<string, unknown>)
+ ) {
+ return {
+ ...contentItem,
+ content: (resultValue as Record<string, unknown>).value,
+ };
+ }
+
+ // Otherwise stringify the result
+ return {
+ ...contentItem,
+ content:
+ typeof resultValue === "string"
+ ? resultValue
+ : JSON.stringify(resultValue ?? ""),
+ };
+ }
+
+ return contentItem;
+ });
+
+ // Convert tool-call content items to tool_calls array
+ if (Array.isArray(normalized.content)) {
+ const toolCallItems = normalized.content.filter(
+ (item: unknown) =>
+ item &&
+ typeof item === "object" &&
+ (item as Record<string, unknown>).type === "tool-call",
+ );
+
+ if (toolCallItems.length > 0) {
+ normalized.tool_calls = toolCallItems.map((item: unknown) => {
+ const tc = item as Record<string, unknown>;
+ return {
+ id: tc.toolCallId,
+ name: tc.toolName,
+ arguments: tc.arguments,
+ type: "function",
+ };
+ });
+
+ // Remove tool-call items from content, keep only text items
+ const textItems = normalized.content.filter(
+ (item: unknown) =>
+ item &&
+ typeof item === "object" &&
+ (item as Record<string, unknown>).type === "text",
+ );
+
+ if (textItems.length > 0) {
+ const texts = textItems.map(
+ (item: unknown) => (item as Record<string, unknown>).text ?? "",
+ );
+ normalized.content = texts.join("");
+ } else {
+ // No text content, remove content field
+ delete normalized.content;
+ }
+ }
+ }
+
+ // Handle tool-result content items for tool role messages
+ // Only process if content is still an array (wasn't converted to string above)
+ if (Array.isArray(normalized.content)) {
+ const toolResultItems = normalized.content.filter(
+ (item: unknown) =>
+ item &&
+ typeof item === "object" &&
+ (item as Record<string, unknown>).type === "tool-result",
+ );
+
+ if (toolResultItems.length > 0 && normalized.role === "tool") {
+ // For single tool result, extract tool_call_id and content
+ if (toolResultItems.length === 1) {
+ const result = toolResultItems[0] as Record<string, unknown>;
+ normalized.tool_call_id = result.toolCallId;
+ normalized.content = result.content;
+ } else {
+ // Multiple tool results: keep as array (less common)
+ normalized.content = toolResultItems;
+ }
+ }
+ }
+ }
+ }
+
+ // For tool messages with rich object content, spread into message
+ // so it goes to json passthrough field and renders as PrettyJsonView.
+ // Rich = nested structure OR 3+ keys. Simple <=2 scalar keys.
+ if (
+ normalized.role === "tool" &&
+ typeof normalized.content === "object" &&
+ normalized.content !== null &&
+ !Array.isArray(normalized.content)
+ ) {
+ if (isRichToolResult(normalized.content)) {
+ // Rich object: spread for table rendering
+ const { content, ...rest } = normalized;
+ return { ...rest, ...content };
+ } else {
+ // Simple object: stringify for text rendering
+ normalized.content = stringifyToolResultContent(normalized.content);
+ }
+ }
+
+ return normalized;
+}
+
+function flattenToolDefinition(tool: unknown): Record<string, unknown> {
+ // handle stringified tools (e.g. from metadata.tools with bedrock)
+ if (typeof tool === "string") {
+ try {
+ tool = JSON.parse(tool);
+ } catch {
+ return {};
+ }
+ }
+
+ if (typeof tool !== "object" || !tool) return {};
+
+ const t = tool as Record<string, unknown>;
+
+ const toolDef: Record<string, unknown> = {
+ name: t.name,
+ description: t.description ?? "",
+ };
+
+ // AI SDK uses inputSchema instead of parameters
+ if (t.inputSchema != null) {
+ toolDef.parameters = t.inputSchema;
+ } else if (t.parameters != null) {
+ toolDef.parameters = t.parameters;
+ }
+
+ return toolDef;
+}
+
+/**
+ * Split tool result messages with multiple results into separate messages
+ * AI SDK can have: {role: "tool", content: [{type: "tool-result", ...}, {type: "tool-result", ...}]}
+ * ChatML expects: [{role: "tool", tool_call_id: "...", content: "..."}, ...]
+ */
+function splitToolResultMessages(messages: unknown[]): unknown[] {
+ const result: unknown[] = [];
+
+ for (const msg of messages) {
+ if (!msg || typeof msg !== "object") {
+ result.push(msg);
+ continue;
+ }
+
+ const message = msg as Record<string, unknown>;
+
+ // Check if this is a tool message with array content containing multiple tool-result items
+ if (
+ message.role === "tool" &&
+ Array.isArray(message.content) &&
+ message.content.length > 1 &&
+ message.content.every(
+ (item: unknown) =>
+ item &&
+ typeof item === "object" &&
+ (item as Record<string, unknown>).type === "tool-result",
+ )
+ ) {
+ // Split into separate messages, one per tool result
+ for (const item of message.content) {
+ const toolResult = item as Record<string, unknown>;
+ result.push({
+ role: "tool",
+ tool_call_id: toolResult.toolCallId,
+ content: toolResult.content,
+ });
+ }
+ } else {
+ result.push(message);
+ }
+ }
+
+ return result;
+}
+
+function preprocessData(data: unknown, ctx?: NormalizerContext): unknown {
+ if (!data) return data;
+
+ // Extract tools from context metadata (observation.metadata.tools)
+ let toolsFromContext: unknown[] | undefined;
+ if (ctx?.metadata && typeof ctx.metadata === "object") {
+ const meta = ctx.metadata as Record<string, unknown>;
+ if (Array.isArray(meta.tools)) {
+ toolsFromContext = meta.tools.map(flattenToolDefinition);
+ }
+ }
+
+ // Handle wrapped format with messages and tools
+ // {messages: [...], tools: [...]} or {messages: [...], providerOptions: {...}}
+ if (typeof data === "object" && !Array.isArray(data) && "messages" in data) {
+ const obj = data as Record<string, unknown>;
+ const messagesArray = obj.messages as unknown[];
+
+ if (Array.isArray(messagesArray)) {
+ let tools: unknown[] | undefined;
+
+ if (Array.isArray(obj.tools)) {
+ tools = (obj.tools as unknown[]).map(flattenToolDefinition);
+ }
+
+ const normalized = messagesArray.map(normalizeMessage);
+
+ const split = splitToolResultMessages(normalized);
+
+ // Attach tools to messages if present
+ if (tools && tools.length > 0) {
+ return split.map((msg) => ({
+ ...(msg as Record<string, unknown>),
+ tools,
+ }));
+ }
+
+ return split;
+ }
+ }
+
+ if (Array.isArray(data)) {
+ // is an array of raw tool call objects?
+ // Example: [{toolCallId: "...", toolName: "...", input: {...}}, ...]
+ const rawToolCallArrayResult = AISDKRawToolCallArraySchema.safeParse(data);
+
+ if (rawToolCallArrayResult.success) {
+ // Convert raw tool calls into a single assistant message with tool_calls
+ const toolCalls = data.map((item) => {
+ const tc = item as Record<string, unknown>;
+ const args = tc.args ?? tc.input;
+
+ return {
+ id: tc.toolCallId,
+ name: tc.toolName,
+ arguments:
+ typeof args === "string" ? args : JSON.stringify(args ?? {}),
+ type: "function",
+ };
+ });
+
+ const assistantMessage: Record<string, unknown> = {
+ role: "assistant",
+ content: "",
+ tool_calls: toolCalls,
+ };
+
+ // Attach tools from context if available
+ if (toolsFromContext && toolsFromContext.length > 0) {
+ assistantMessage.tools = toolsFromContext;
+ }
+
+ return [assistantMessage];
+ }
+
+ // otherwise it's an array of messages
+ const normalized = data.map(normalizeMessage);
+ const split = splitToolResultMessages(normalized);
+
+ // Attach tools from context metadata if present
+ if (toolsFromContext && toolsFromContext.length > 0) {
+ return split.map((msg) => ({
+ ...(msg as Record<string, unknown>),
+ tools: toolsFromContext,
+ }));
+ }
+
+ return split;
+ }
+
+ // if it's not an array but just a single message
+ if (typeof data === "object" && "role" in data) {
+ return normalizeMessage(data);
+ }
+
+ return data;
+}
+
+export const aisdkAdapter: ProviderAdapter = {
+ id: "aisdk",
+
+ detect(ctx: NormalizerContext): boolean {
+ const meta = parseMetadata(ctx.metadata);
+
+ // EXPLICIT: Framework hint
+ if (ctx.framework === "aisdk" || ctx.framework === "aisdk-v5") return true;
+
+ // STRONG INDICATORS: AI SDK v5 telemetry markers
+ if (meta && typeof meta === "object") {
+ if ("scope" in meta && typeof meta.scope === "object") {
+ const scope = meta.scope as Record<string, unknown>;
+ if (scope.name === "ai") return true;
+ }
+
+ if ("attributes" in meta && typeof meta.attributes === "object") {
+ const attrs = meta.attributes as Record<string, unknown> | null;
+ if (
+ attrs &&
+ typeof attrs["operation.name"] === "string" &&
+ attrs["operation.name"].startsWith("ai.")
+ ) {
+ return true;
+ }
+ }
+ }
+
+ // STRUCTURAL: Schema-based detection (for edge cases without metadata)
+ if (AISDKToolCallMessageSchema.safeParse(ctx.metadata).success) return true;
+ if (AISDKToolResultMessageSchema.safeParse(ctx.metadata).success)
+ return true;
+ if (AISDKMessagesArraySchema.safeParse(ctx.metadata).success) return true;
+
+ if (AISDKToolCallMessageSchema.safeParse(ctx.data).success) return true;
+ if (AISDKToolResultMessageSchema.safeParse(ctx.data).success) return true;
+ if (AISDKMessagesArraySchema.safeParse(ctx.data).success) return true;
+
+ // Raw tool call array detection (OUTPUT format)
+ if (AISDKRawToolCallArraySchema.safeParse(ctx.data).success) return true;
+
+ return false;
+ },
+
+ preprocess(
+ data: unknown,
+ _kind: "input" | "output",
+ ctx: NormalizerContext,
+ ): unknown {
+ return preprocessData(data, ctx);
+ },
+};
diff --git a/packages/shared/src/utils/chatml/adapters/gemini.ts b/packages/shared/src/utils/chatml/adapters/gemini.ts
new file mode 100644
index 0000000000..686556a5c7
--- /dev/null
+++ b/packages/shared/src/utils/chatml/adapters/gemini.ts
@@ -0,0 +1,464 @@
+import type { NormalizerContext, ProviderAdapter } from "../types";
+import {
+ parseMetadata,
+ stringifyToolResultContent,
+ isRichToolResult,
+} from "../helpers";
+import { z } from "zod/v4";
+
+/**
+ * Detection schemas for Gemini/VertexAI formats
+ *
+ * Two main format families (inner structure is identical):
+ * 1. Raw Gemini API (Vertex): {candidates: [{content: {parts, role}}]}
+ * 2. Google ADK: {content: {parts, role}} or {config, contents: [{parts, role}]}
+ */
+
+// Raw Gemini API response: {candidates: [{content: {...}}]}
+const GeminiRawAPISchema = z.looseObject({
+ candidates: z.array(
+ z.looseObject({
+ content: z.looseObject({
+ parts: z.array(z.any()).optional(),
+ role: z.string().optional(),
+ }),
+ }),
+ ),
+});
+
+// ADK output format: {content: {parts: [...], role: "..."}}
+const GeminiADKOutputSchema = z.looseObject({
+ content: z.looseObject({
+ parts: z.array(z.any()),
+ role: z.string(),
+ }),
+});
+
+// ADK input format: {config: {tools, system_instruction}, contents: [...]}
+const GeminiADKInputSchema = z.looseObject({
+ config: z.looseObject({
+ tools: z.array(z.any()).optional(),
+ system_instruction: z.string().optional(),
+ }),
+ contents: z.array(z.any()),
+});
+
+// Simple request format: {contents: [{parts: [...], role: "..."}]}
+const GeminiRequestSchema = z.looseObject({
+ contents: z.array(
+ z.looseObject({
+ parts: z.array(z.any()),
+ role: z.string().optional(),
+ }),
+ ),
+});
+
+/**
+ * Case-insensitive field accessor
+ * Handles both snake_case and camelCase (e.g., function_call OR functionCall)
+ */
+function getField(obj: unknown, snakeName: string, camelName: string): unknown {
+ if (!obj || typeof obj !== "object") return undefined;
+ const o = obj as Record<string, unknown>;
+ return o[snakeName] ?? o[camelName];
+}
+
+// Note: Gemini tools come from config.tools with function_declarations, not from messages
+// The format {role: "tool", content: {type: "function"}} is LangGraph, handled by langgraph adapter
+
+/**
+ * Extract both tool calls and text from parts array
+ * Handles: function_call/functionCall, text, function_response/functionResponse
+ * snake_case is from python SDK while camelCase is from JavaScript SDK / REST
+ */
+function extractFromParts(parts: unknown[]): {
+ toolCalls: Array<Record<string, unknown>>;
+ text: string;
+} {
+ const toolCalls: Array<Record<string, unknown>> = [];
+ const textParts: string[] = [];
+
+ for (const part of parts) {
+ if (typeof part === "string") {
+ textParts.push(part);
+ continue;
+ }
+ if (!part || typeof part !== "object") continue;
+
+ const p = part as Record<string, unknown>;
+
+ // Check for function_call OR functionCall (case-insensitive)
+ const fc = getField(p, "function_call", "functionCall");
+ if (fc && typeof fc === "object") {
+ const functionCall = fc as Record<string, unknown>;
+ toolCalls.push({
+ id: functionCall.id || "",
+ name: functionCall.name,
+ arguments:
+ typeof functionCall.args === "string"
+ ? functionCall.args
+ : JSON.stringify(functionCall.args ?? {}),
+ type: "function",
+ });
+ continue;
+ }
+
+ // {text: "..."} or {type: "text", text: "..."}
+ // text can be a string (normal response) or an object (when responseMimeType: "application/json")
+ if (p.text !== undefined && p.text !== null) {
+ textParts.push(
+ typeof p.text === "string" ? p.text : JSON.stringify(p.text, null, 2),
+ );
+ continue;
+ }
+
+ // {function_response: {name, response}} OR {functionResponse: {name, response}}
+ const fr = getField(p, "function_response", "functionResponse");
+ if (fr && typeof fr === "object") {
+ const functionResponse = fr as Record<string, unknown>;
+ textParts.push(JSON.stringify(functionResponse.response || {}));
+ }
+ }
+
+ return {
+ toolCalls,
+ text: textParts.join(""),
+ };
+}
+
+/**
+ * Extract tool declarations from Google ADK tools array
+ * Handles: {function_declarations: [{name, description, parameters}]}
+ */
+function extractToolDeclarations(tools: unknown[]): Array<{
+ name: string;
+ description?: string;
+ parameters?: Record<string, unknown>;
+}> {
+ const declarations: Array<{
+ name: string;
+ description?: string;
+ parameters?: Record<string, unknown>;
+ }> = [];
+
+ for (const tool of tools) {
+ if (!tool || typeof tool !== "object") continue;
+ const t = tool as Record<string, unknown>;
+
+ // Check for function_declarations OR functionDeclarations
+ const fd = getField(t, "function_declarations", "functionDeclarations");
+ if (fd && Array.isArray(fd)) {
+ for (const decl of fd as Array<Record<string, unknown>>) {
+ const toolDef: Record<string, unknown> = {
+ name: (decl.name as string) || "",
+ };
+ if (decl.description !== null && decl.description !== undefined) {
+ toolDef.description = decl.description;
+ }
+ if (decl.parameters !== null && decl.parameters !== undefined) {
+ toolDef.parameters = decl.parameters;
+ }
+ declarations.push(
+ toolDef as {
+ name: string;
+ description?: string;
+ parameters?: Record<string, unknown>;
+ },
+ );
+ }
+ }
+ }
+
+ return declarations;
+}
+
+// normalize a single Gemini message to ChatML format
+function normalizeGeminiMessage(msg: unknown): Record<string, unknown> {
+ if (!msg || typeof msg !== "object") return {};
+
+ const message = msg as Record<string, unknown>;
+ let normalized = { ...message };
+
+ // convert Gemini "model" role → "assistant"
+ // if (message.role === "model") {
+ // normalized.role = "assistant";
+ // }
+
+ // handle direct tool call message format
+ // {type: "tool_call", name: "...", args: {...}} → {role: "assistant", tool_calls: [...]}
+ if (
+ normalized.type === "tool_call" &&
+ normalized.name &&
+ typeof normalized.name === "string"
+ ) {
+ const toolCall: Record<string, unknown> = {
+ id: normalized.id || "",
+ name: normalized.name,
+ arguments:
+ typeof normalized.args === "string"
+ ? normalized.args
+ : JSON.stringify(normalized.args ?? {}),
+ type: "function",
+ };
+
+ const { type: _type, name: _name, args: _args, ...rest } = normalized;
+ normalized = {
+ ...rest,
+ role: rest.role || "assistant",
+ tool_calls: [toolCall],
+ };
+ }
+
+ // normalize existing tool_calls array
+ if (normalized.tool_calls && Array.isArray(normalized.tool_calls)) {
+ normalized.tool_calls = normalized.tool_calls.map((tc) => {
+ if (!tc || typeof tc !== "object") return {};
+ const toolCall = tc as Record<string, unknown>;
+
+ // Convert Gemini format {type: "tool_call", name, args} → flat format
+ if (toolCall.type === "tool_call" && "args" in toolCall) {
+ return {
+ id: toolCall.id || "",
+ name: toolCall.name,
+ arguments:
+ typeof toolCall.args === "string"
+ ? toolCall.args
+ : JSON.stringify(toolCall.args ?? {}),
+ type: "function",
+ };
+ }
+
+ return toolCall;
+ });
+ }
+
+ // process top-level parts array
+ // Gemini format: {parts: [{function_call/text/function_response}], role: "..."}
+ if (normalized.parts && Array.isArray(normalized.parts)) {
+ const { toolCalls, text } = extractFromParts(normalized.parts);
+ if (toolCalls.length > 0) {
+ normalized.tool_calls = toolCalls;
+ }
+ if (text) {
+ normalized.content = text;
+ // Remove parts to avoid showing in passthrough
+ delete normalized.parts;
+ }
+ }
+
+ // process nested content.parts[]
+ // Gemini format: {content: {parts: [{function_call: {...}}], role: "model"}}
+ if (
+ normalized.content &&
+ typeof normalized.content === "object" &&
+ !Array.isArray(normalized.content) &&
+ "parts" in normalized.content
+ ) {
+ const content = normalized.content as Record<string, unknown>;
+ if (Array.isArray(content.parts)) {
+ const { toolCalls } = extractFromParts(content.parts);
+ if (toolCalls.length > 0) {
+ normalized.tool_calls = toolCalls;
+ }
+
+ // Extract role if nested
+ if (content.role && typeof content.role === "string") {
+ normalized.role = content.role;
+ }
+ }
+ }
+
+ // process content as array (structured content format)
+ // Gemini format: {content: [{type: "text", text: "..."}]}
+ if (Array.isArray(normalized.content)) {
+ const { text } = extractFromParts(normalized.content);
+ if (text) {
+ normalized.content = text;
+ }
+ }
+
+ // For tool messages with rich object content, spread into message
+ // so it goes to json passthrough field and renders as PrettyJsonView.
+ // Rich = nested structure OR 3+ keys. Simple <=2 scalar keys.
+ if (
+ normalized.role === "tool" &&
+ typeof normalized.content === "object" &&
+ normalized.content !== null &&
+ !Array.isArray(normalized.content)
+ ) {
+ if (isRichToolResult(normalized.content)) {
+ // Rich object: spread for table rendering
+ const { content, ...rest } = normalized;
+ return { ...rest, ...content };
+ } else {
+ // Simple object: stringify for text rendering
+ normalized.content = stringifyToolResultContent(normalized.content);
+ }
+ }
+
+ return normalized;
+}
+
+// normalize messages
+function normalizeMessages(data: unknown[]): unknown[] {
+ return data.map(normalizeGeminiMessage);
+}
+
+// unwrap outer wrappers first then normalize inner structure
+function preprocessData(data: unknown): unknown {
+ if (!data) return data;
+
+ // ========================================
+ // STEP 1: Unwrap Raw Gemini API format
+ // ========================================
+ // {candidates: [{content: {parts, role}}]} → {parts, role, ...otherFields}
+ if (GeminiRawAPISchema.safeParse(data).success) {
+ const obj = data as Record<string, unknown>;
+ const candidates = obj.candidates as Array<Record<string, unknown>>;
+ if (candidates[0]?.content) {
+ // Unwrap: merge first candidate's content with other top-level fields
+ const { candidates: _candidates, ...otherFields } = obj;
+ return normalizeGeminiMessage({
+ ...candidates[0].content,
+ ...otherFields,
+ });
+ }
+ }
+
+ // ========================================
+ // STEP 2: Unwrap ADK output format
+ // ========================================
+ // {content: {parts, role}, finish_reason: "..."} → {parts, role, finish_reason: "..."}
+ if (GeminiADKOutputSchema.safeParse(data).success) {
+ const obj = data as Record<string, unknown>;
+ const content = obj.content as Record<string, unknown>;
+ if ("parts" in content && Array.isArray(content.parts)) {
+ const { content: _content, ...otherFields } = obj;
+ return normalizeGeminiMessage({ ...content, ...otherFields });
+ }
+ }
+
+ // ========================================
+ // STEP 3: Handle ADK input format
+ // ========================================
+ // {config: {tools, system_instruction}, contents: [...]}
+ if (GeminiADKInputSchema.safeParse(data).success) {
+ const obj = data as Record<string, unknown>;
+ const config = obj.config as Record<string, unknown> | undefined;
+ const contents = obj.contents;
+
+ if (config && Array.isArray(contents)) {
+ const messages: unknown[] = [];
+
+ // Extract system_instruction from config and prepend as system message
+ const systemInstruction = getField(
+ config,
+ "system_instruction",
+ "systemInstruction",
+ );
+ if (systemInstruction && typeof systemInstruction === "string") {
+ messages.push({
+ role: "system",
+ content: systemInstruction,
+ });
+ }
+
+ messages.push(...contents);
+
+ // Extract and attach tools if present
+ if ("tools" in config && Array.isArray(config.tools)) {
+ const extractedTools = extractToolDeclarations(config.tools);
+
+ if (extractedTools.length > 0) {
+ return normalizeMessages(messages).map((msg) => ({
+ ...(msg as Record<string, unknown>),
+ tools: extractedTools,
+ }));
+ }
+ }
+
+ // No tools, just normalize messages
+ return normalizeMessages(messages);
+ }
+ }
+
+ // ========================================
+ // STEP 4: Handle simple request format
+ // ========================================
+ // {contents: [{parts, role}], model: "..."}
+ if (GeminiRequestSchema.safeParse(data).success) {
+ const obj = data as Record<string, unknown>;
+ return normalizeMessages(obj.contents as unknown[]);
+ }
+
+ // ========================================
+ // STEP 5: Handle arrays
+ // ========================================
+ if (Array.isArray(data)) {
+ return normalizeMessages(data);
+ }
+
+ // ========================================
+ // STEP 6: Handle messages wrapper
+ // ========================================
+ if (typeof data === "object" && "messages" in data) {
+ const obj = data as Record<string, unknown>;
+ return {
+ ...obj,
+ messages: Array.isArray(obj.messages)
+ ? normalizeMessages(obj.messages)
+ : obj.messages,
+ };
+ }
+
+ return data;
+}
+
+export const geminiAdapter: ProviderAdapter = {
+ id: "gemini",
+
+ detect(ctx: NormalizerContext): boolean {
+ const meta = parseMetadata(ctx.metadata);
+
+ // HINTS: Fast checks for explicit Gemini indicators
+ if (ctx.framework === "gemini") return true;
+ if (ctx.observationName?.toLowerCase().includes("gemini")) return true;
+ if (ctx.observationName?.toLowerCase().includes("vertex")) return true;
+ if (meta?.ls_provider === "google_vertexai") return true;
+
+ // Metadata attributes check
+ if (meta && typeof meta === "object" && "attributes" in meta) {
+ const attributes = (meta as Record<string, unknown>).attributes;
+ if (
+ attributes &&
+ typeof attributes === "object" &&
+ (attributes as Record<string, unknown>)["gen_ai.system"] ===
+ "gcp.vertex.agent"
+ ) {
+ return true;
+ }
+ }
+
+ // STRUCTURAL: Schema-based detection on metadata (check metadata first for performance)
+ if (GeminiRequestSchema.safeParse(ctx.metadata).success) return true;
+ if (GeminiADKInputSchema.safeParse(ctx.metadata).success) return true;
+ if (GeminiRawAPISchema.safeParse(ctx.metadata).success) return true;
+ if (GeminiADKOutputSchema.safeParse(ctx.metadata).success) return true;
+
+ // Schema-based detection on data (slower, do last)
+ if (GeminiRequestSchema.safeParse(ctx.data).success) return true;
+ if (GeminiADKInputSchema.safeParse(ctx.data).success) return true;
+ if (GeminiRawAPISchema.safeParse(ctx.data).success) return true;
+ if (GeminiADKOutputSchema.safeParse(ctx.data).success) return true;
+
+ return false;
+ },
+
+ preprocess(
+ data: unknown,
+ _kind: "input" | "output",
+ _ctx: NormalizerContext,
+ ): unknown {
+ return preprocessData(data);
+ },
+};
diff --git a/packages/shared/src/utils/chatml/adapters/generic.ts b/packages/shared/src/utils/chatml/adapters/generic.ts
new file mode 100644
index 0000000000..5a45536864
--- /dev/null
+++ b/packages/shared/src/utils/chatml/adapters/generic.ts
@@ -0,0 +1,150 @@
+import type { NormalizerContext, ProviderAdapter } from "../types";
+
+function normalizeGoogleMessage(msg: unknown): Record<string, unknown> {
+ if (!msg || typeof msg !== "object") return {};
+
+ const message = msg as Record<string, unknown>;
+ let normalized = { ...message };
+
+ // Google/Gemini: "model" role → "assistant"
+ if (message.role === "model") {
+ normalized.role = "assistant";
+ }
+
+ // Google/Gemini/Microsoft Agent: "parts" field → "content" field
+ if (message.parts && Array.isArray(message.parts)) {
+ // Check if parts contain function_call, function_response, or Microsoft Agent tool calls
+ const hasFunctionCall = message.parts.some((p: unknown) => {
+ // Null guard: ensure p exists and is an object before accessing properties
+ if (!p || typeof p !== "object") {
+ return false;
+ }
+ const part = p as Record<string, unknown>;
+ return part.function_call || part.type === "tool_call";
+ });
+ const hasFunctionResponse = message.parts.some((p: unknown) => {
+ // Null guard: ensure p exists and is an object before accessing properties
+ if (!p || typeof p !== "object") {
+ return false;
+ }
+ const part = p as Record<string, unknown>;
+ return part.function_response || part.type === "tool_call_response";
+ });
+
+ if (hasFunctionCall || hasFunctionResponse) {
+ // Keep parts as structured content array
+ normalized.content = message.parts;
+ } else {
+ // Extract text from parts
+ const content = message.parts
+ .map((part: unknown) => {
+ if (typeof part === "object" && part !== null) {
+ const p = part as Record<string, unknown>;
+ // Support both Google's "text" and Microsoft's "content" fields
+ if (p.text) {
+ return p.text;
+ }
+ if (p.content && typeof p.content === "string") {
+ return p.content;
+ }
+ }
+ // Only stringify if it's actually a simple value, not an object
+ if (typeof part === "string" || typeof part === "number") {
+ return String(part);
+ }
+ return "";
+ })
+ .filter((text: unknown) => text !== "")
+ .join("");
+ normalized.content = content;
+ }
+ delete normalized.parts;
+ }
+
+ return normalized;
+}
+
+function preprocessData(data: unknown): unknown {
+ if (!data) return data;
+
+ // Handle Google output format: {candidates: [{content: {parts, role}}]}
+ if (
+ typeof data === "object" &&
+ "candidates" in data &&
+ Array.isArray((data as Record<string, unknown>).candidates)
+ ) {
+ const obj = data as Record<string, unknown>;
+ const candidate = (obj.candidates as Record<string, unknown>[])[0];
+ if (candidate?.content) {
+ return normalizeGoogleMessage(candidate.content);
+ }
+ }
+
+ // Handle Google input format: {model: "...", contents: [...]} or {contents: "string"}
+ if (typeof data === "object" && "contents" in data && !("messages" in data)) {
+ const obj = data as Record<string, unknown>;
+ const contents = obj.contents;
+ const messages: Record<string, unknown>[] = [];
+
+ // Handle system_instruction if present
+ const config = obj.config as Record<string, unknown> | undefined;
+ if (config?.system_instruction) {
+ messages.push({
+ role: "system",
+ content: config.system_instruction,
+ });
+ }
+
+ // Convert contents to ChatML format
+ if (typeof contents === "string") {
+ messages.push({ role: "user", content: contents });
+ } else if (Array.isArray(contents)) {
+ messages.push(...contents.map(normalizeGoogleMessage));
+ }
+
+ return messages.length > 0 ? messages : data;
+ }
+
+ // Array of messages
+ if (Array.isArray(data)) {
+ // Handle nested array format: [[ChatML...]]
+ if (data.length === 1 && Array.isArray(data[0])) {
+ return data[0].map(normalizeGoogleMessage);
+ }
+ return data.map(normalizeGoogleMessage);
+ }
+
+ // Object with messages key
+ if (typeof data === "object" && "messages" in data) {
+ const obj = data as Record<string, unknown>;
+ return {
+ ...obj,
+ messages: Array.isArray(obj.messages)
+ ? obj.messages.map(normalizeGoogleMessage)
+ : obj.messages,
+ };
+ }
+
+ // Single message
+ if (typeof data === "object" && ("role" in data || "parts" in data)) {
+ return normalizeGoogleMessage(data);
+ }
+
+ return data;
+}
+
+export const genericAdapter: ProviderAdapter = {
+ id: "generic",
+
+ detect(_ctx: NormalizerContext): boolean {
+ return true; // fallback
+ },
+
+ preprocess(
+ data: unknown,
+ _kind: "input" | "output",
+ _ctx: NormalizerContext,
+ ): unknown {
+ return preprocessData(data);
+ },
+};
diff --git a/packages/shared/src/utils/chatml/adapters/index.ts b/packages/shared/src/utils/chatml/adapters/index.ts
new file mode 100644
index 0000000000..b4c449fe05
--- /dev/null
+++ b/packages/shared/src/utils/chatml/adapters/index.ts
@@ -0,0 +1,47 @@
+import type { NormalizerContext, ProviderAdapter } from "../types";
+import { langgraphAdapter } from "./langgraph";
+import { aisdkAdapter } from "./aisdk";
+import { openAIAdapter } from "./openai";
+import { geminiAdapter } from "./gemini";
+import { microsoftAgentAdapter } from "./microsoft-agent";
+import { pydanticAIAdapter } from "./pydantic-ai";
+import { genericAdapter } from "./generic";
+
+const adapters: ProviderAdapter[] = [
+ langgraphAdapter, // Must be before openAI (both use langfuse-sdk scope)
+ aisdkAdapter, // Vercel AI SDK v5 (for all LLM providers like OpenAI, Bedrock, Anthropic, etc.)
+ openAIAdapter, // OpenAI (Chat Completions & Responses API)
+ geminiAdapter, // Gemini/VertexAI format
+ microsoftAgentAdapter, // Microsoft Agent Framework
+ pydanticAIAdapter, // Pydantic AI framework
+ // Add more adapters here as needed
+ genericAdapter, // Always last (fallback)
+];
+
+function selectAdapter(ctx: NormalizerContext): ProviderAdapter {
+ // Explicit override
+ if (ctx.framework) {
+ const adapter = adapters.find((a) => a.id === ctx.framework);
+ if (adapter) return adapter;
+ }
+
+ // First adapter that matches wins
+ for (const adapter of adapters) {
+ if (adapter.detect(ctx)) {
+ return adapter;
+ }
+ }
+
+ return genericAdapter;
+}
+
+// Export selectAdapter and individual adapters for direct use
+export { selectAdapter };
+export type { NormalizerContext, ProviderAdapter } from "../types";
+export { langgraphAdapter } from "./langgraph";
+export { aisdkAdapter } from "./aisdk";
+export { openAIAdapter } from "./openai";
+export { geminiAdapter } from "./gemini";
+export { microsoftAgentAdapter } from "./microsoft-agent";
+export { pydanticAIAdapter } from "./pydantic-ai";
+export { genericAdapter } from "./generic";
diff --git a/packages/shared/src/utils/chatml/adapters/langgraph.ts b/packages/shared/src/utils/chatml/adapters/langgraph.ts
new file mode 100644
index 0000000000..15bf79f8cf
--- /dev/null
+++ b/packages/shared/src/utils/chatml/adapters/langgraph.ts
@@ -0,0 +1,377 @@
+import type { NormalizerContext, ProviderAdapter } from "../types";
+import {
+ removeNullFields,
+ stringifyToolResultContent,
+ parseMetadata,
+ isRichToolResult,
+} from "../helpers";
+import { z } from "zod/v4";
+
+// Detection schemas for LangChain/LangGraph formats
+
+// LangChain message with type field (no role)
+const LangChainMessageSchema = z.array(
+ z.looseObject({
+ type: z.enum(["human", "ai", "tool", "system"]),
+ content: z.any(),
+ }),
+);
+
+// LangGraph message with additional_kwargs
+const LangGraphMessageSchema = z
+ .array(
+ z.looseObject({
+ role: z.string().optional(),
+ additional_kwargs: z
+ .looseObject({
+ tool_calls: z.array(z.any()).optional(),
+ })
+ .optional(),
+ }),
+ )
+ .refine(
+ (data) => {
+ // Reject if any message has top-level parts (Microsoft Agent/Gemini format)
+ return !data.some(
+ (msg) =>
+ typeof msg === "object" &&
+ msg !== null &&
+ "parts" in msg &&
+ Array.isArray((msg as Record<string, unknown>).parts),
+ );
+ },
+ { message: "Messages with top-level parts are not LangGraph format" },
+ );
+
+// Wrapped messages format
+const LangGraphWrappedSchema = z.looseObject({
+ messages: z.array(z.any()),
+});
+
+/**
+ * Detect if a message is a tool definition (not a tool result)
+ * LangGraph format: {role: "tool", content: {type: "function", function: {...}}}
+ * Tool results have tool_call_id, tool definitions do not
+ */
+function isLangGraphToolDefinition(msg: unknown): boolean {
+ if (!msg || typeof msg !== "object") return false;
+
+ const message = msg as Record<string, unknown>;
+
+ return (
+ message.role === "tool" &&
+ typeof message.content === "object" &&
+ message.content !== null &&
+ !Array.isArray(message.content) &&
+ (message.content as Record<string, unknown>).type === "function" &&
+ !!(message.content as Record<string, unknown>).function &&
+ !message.tool_call_id // Tool definitions don't have tool_call_id
+ );
+}
+
+// extract tool definitions from messages array
+function extractToolDefinitions(messages: unknown[]): Array<{
+ name: string;
+ description?: string;
+ parameters?: Record<string, unknown>;
+}> {
+ return messages.filter(isLangGraphToolDefinition).map((msg) => {
+ const message = msg as Record<string, unknown>;
+ const func = (message.content as Record<string, unknown>)
+ .function as Record<string, unknown>;
+
+ const toolDef: Record<string, unknown> = {
+ name: (func.name as string) || "",
+ };
+ if (func.description !== null && func.description !== undefined) {
+ toolDef.description = func.description;
+ }
+ if (func.parameters !== null && func.parameters !== undefined) {
+ toolDef.parameters = func.parameters;
+ }
+
+ return toolDef as {
+ name: string;
+ description?: string;
+ parameters?: Record<string, unknown>;
+ };
+ });
+}
+
+function normalizeMessage(msg: unknown): Record<string, unknown> {
+ if (!msg || typeof msg !== "object") return {};
+
+ let normalized = removeNullFields(msg);
+
+ // LangGraph/LangChain: "type" field → "role" field
+ if (normalized.type && !normalized.role) {
+ const typeToRole: Record<string, string> = {
+ human: "user",
+ ai: "assistant",
+ tool: "tool",
+ system: "system",
+ };
+ const type = String(normalized.type);
+ if (typeToRole[type]) {
+ normalized.role = typeToRole[type];
+ normalized._originalType = type;
+ }
+ }
+
+ // LangGraph: tool_calls in additional_kwargs → top level
+ if (
+ normalized.additional_kwargs &&
+ typeof normalized.additional_kwargs === "object"
+ ) {
+ const additionalKwargs = normalized.additional_kwargs as Record<
+ string,
+ unknown
+ >;
+
+ // Handle tool_calls from additional_kwargs
+ if (additionalKwargs.tool_calls) {
+ if (!normalized.tool_calls) {
+ // No top-level tool_calls, extract from additional_kwargs
+ normalized.tool_calls = additionalKwargs.tool_calls;
+ }
+ // IMPORTANT: Always remove tool_calls from additional_kwargs to prevent
+ // ChatMlSchema from overwriting our processed version when it spreads additional_kwargs
+ // This handles both cases:
+ // 1. LangGraph format: tool_calls extracted from additional_kwargs
+ // 2. LangChain format: top-level tool_calls already exists, prevent overwrite
+ // Don't mutate original object - JSON view needs to show original data
+ // Filter out null fields to prevent them from creating extra json blocks in UI
+ const { tool_calls: _removed, ...restKwargs } = additionalKwargs;
+ normalized.additional_kwargs = removeNullFields(restKwargs);
+ }
+
+ // Keep other fields in additional_kwargs (non-null values) for JSON view
+ // ChatMlSchema will spread these into passthrough json field
+ }
+
+ // Flatten nested tool_calls format to flat ChatML format
+ // LangGraph can have OpenAI-style nested format: {id, type, function: {name, arguments}}
+ // Convert to flat format: {id, name, arguments, type}
+ if (normalized.tool_calls && Array.isArray(normalized.tool_calls)) {
+ const sanitizedToolCalls = (normalized.tool_calls as unknown[]).filter(
+ (tc): tc is Record<string, unknown> =>
+ Boolean(tc) && typeof tc === "object",
+ );
+
+ normalized.tool_calls = sanitizedToolCalls.map((tc) => {
+ // If nested format (has function.name), flatten it
+ if (tc.function && typeof tc.function === "object") {
+ const func = tc.function as Record<string, unknown>;
+ return {
+ id: tc.id,
+ name: func.name,
+ arguments:
+ typeof func.arguments === "string"
+ ? func.arguments
+ : JSON.stringify(func.arguments ?? {}),
+ type: tc.type || "function",
+ ...(tc.index !== undefined ? { index: tc.index } : {}),
+ };
+ }
+ // Already flat format - handle both 'args' (LangChain) and 'arguments' (OpenAI)
+ // LangChain uses 'args', OpenAI uses 'arguments'
+ const argsValue = tc.args ?? tc.arguments;
+ return {
+ ...tc,
+ name: tc.name,
+ arguments:
+ typeof argsValue === "string"
+ ? argsValue
+ : JSON.stringify(argsValue ?? {}),
+ };
+ });
+ }
+
+ // For tool messages with rich object content, spread into message
+ // so it goes to json passthrough field → renders as PrettyJsonView.
+ // Rich = nested structure OR 3+ keys. Simple <=2 scalar keys.
+ if (
+ normalized.role === "tool" &&
+ typeof normalized.content === "object" &&
+ normalized.content !== null &&
+ !Array.isArray(normalized.content)
+ ) {
+ if (isRichToolResult(normalized.content)) {
+ // Rich object: spread for table rendering
+ const { content, ...rest } = normalized;
+ return { ...rest, ...content };
+ } else {
+ // Simple object: stringify for text rendering
+ normalized.content = stringifyToolResultContent(normalized.content);
+ }
+ }
+
+ return normalized;
+}
+
+function filterAndNormalizeMessages(data: unknown[]): unknown[] {
+ return data
+ .filter((msg) => !isLangGraphToolDefinition(msg))
+ .map(normalizeMessage);
+}
+
+function preprocessData(data: unknown): unknown {
+ if (!data) return data;
+
+ // Array of messages
+ if (Array.isArray(data)) {
+ const extractedTools = extractToolDefinitions(data);
+ const normalizedMessages = filterAndNormalizeMessages(data);
+
+ if (extractedTools.length > 0) {
+ // Attach tools to all messages
+ return normalizedMessages.map((msg) => ({
+ ...(msg as Record<string, unknown>),
+ tools: extractedTools,
+ }));
+ }
+
+ return normalizedMessages;
+ }
+
+ // Object with messages key
+ if (typeof data === "object" && "messages" in data) {
+ const obj = data as Record<string, unknown>;
+ if (Array.isArray(obj.messages)) {
+ const extractedTools = extractToolDefinitions(obj.messages);
+ const normalizedMessages = filterAndNormalizeMessages(obj.messages);
+
+ if (extractedTools.length > 0) {
+ return {
+ ...obj,
+ messages: normalizedMessages.map((msg) => ({
+ ...(msg as Record<string, unknown>),
+ tools: extractedTools,
+ })),
+ };
+ }
+
+ return {
+ ...obj,
+ messages: normalizedMessages,
+ };
+ }
+ }
+
+ // Single message - wrap in array for consistency
+ if (typeof data === "object" && ("role" in data || "type" in data)) {
+ return [normalizeMessage(data)];
+ }
+
+ return data;
+}
+
+export const langgraphAdapter: ProviderAdapter = {
+ id: "langgraph",
+
+ detect(ctx: NormalizerContext): boolean {
+ const meta = parseMetadata(ctx.metadata);
+
+ // EXPLICIT: Framework hint
+ if (ctx.framework === "langgraph") return true;
+
+ // REJECTIONS: Reject AI SDK v5 and OpenAI Agents SDK formats
+ if (meta && typeof meta === "object") {
+ // Check scope.name for AI SDK or OpenAI Agents
+ if ("scope" in meta && typeof meta.scope === "object") {
+ const scope = meta.scope as Record<string, unknown>;
+
+ // Reject AI SDK v5 (scope.name === "ai")
+ if (scope.name === "ai") return false;
+
+ // Reject OpenAI Agents SDK
+ if (
+ scope.name === "openinference.instrumentation.openai_agents" ||
+ (typeof scope.name === "string" &&
+ scope.name.includes("openai_agents"))
+ ) {
+ return false;
+ }
+ }
+
+ // Check attributes["operation.name"] for AI SDK pattern
+ if ("attributes" in meta && typeof meta.attributes === "object") {
+ const attrs = meta.attributes as Record<string, unknown> | null;
+ if (
+ attrs &&
+ typeof attrs["operation.name"] === "string" &&
+ attrs["operation.name"].startsWith("ai.")
+ ) {
+ return false;
+ }
+ }
+ }
+
+ // HINTS: LangGraph/LangChain-specific metadata markers
+ if (meta && typeof meta === "object") {
+ // LangGraph markers
+ if (
+ "langgraph_step" in meta ||
+ "langgraph_node" in meta ||
+ "langgraph_path" in meta ||
+ "langgraph_checkpoint_ns" in meta ||
+ meta.framework === "langgraph" ||
+ (Array.isArray(meta.tags) && meta.tags.includes("langgraph"))
+ ) {
+ return true;
+ }
+
+ // LangSmith/LangChain markers (ls_ prefix indicates LangChain ecosystem)
+ const hasLangChainMarkers = Object.keys(meta).some((key) =>
+ key.startsWith("ls_"),
+ );
+ if (hasLangChainMarkers) {
+ return true;
+ }
+ }
+
+ // STRUCTURAL: Schema-based detection on metadata
+ if (LangChainMessageSchema.safeParse(ctx.metadata).success) return true;
+ if (LangGraphMessageSchema.safeParse(ctx.metadata).success) return true;
+
+ // Check wrapped messages format
+ if (LangGraphWrappedSchema.safeParse(ctx.metadata).success) {
+ const wrapped = ctx.metadata as { messages: unknown[]; tools?: unknown };
+ // reject OpenAI Chat Completions format {tools: [...], messages: [...]}
+ if (Array.isArray(wrapped.tools)) {
+ return false;
+ }
+ if (LangChainMessageSchema.safeParse(wrapped.messages).success)
+ return true;
+ if (LangGraphMessageSchema.safeParse(wrapped.messages).success)
+ return true;
+ }
+
+ // finally Schema-based detection on data b/c of performance
+ if (LangChainMessageSchema.safeParse(ctx.data).success) return true;
+ if (LangGraphMessageSchema.safeParse(ctx.data).success) return true;
+
+ // Check wrapped messages format on data
+ if (LangGraphWrappedSchema.safeParse(ctx.data).success) {
+ const wrapped = ctx.data as { messages: unknown[]; tools?: unknown };
+ // reject OpenAI Chat Completions format {tools: [...], messages: [...]}
+ if (Array.isArray(wrapped.tools)) {
+ return false;
+ }
+ if (LangChainMessageSchema.safeParse(wrapped.messages).success)
+ return true;
+ if (LangGraphMessageSchema.safeParse(wrapped.messages).success)
+ return true;
+ }
+
+ return false;
+ },
+
+ preprocess(
+ data: unknown,
+ _kind: "input" | "output",
+ _ctx: NormalizerContext,
+ ): unknown {
+ return preprocessData(data);
+ },
+};
diff --git a/packages/shared/src/utils/chatml/adapters/microsoft-agent.ts b/packages/shared/src/utils/chatml/adapters/microsoft-agent.ts
new file mode 100644
index 0000000000..b4d935cc64
--- /dev/null
+++ b/packages/shared/src/utils/chatml/adapters/microsoft-agent.ts
@@ -0,0 +1,287 @@
+import type { NormalizerContext, ProviderAdapter } from "../types";
+import {
+ parseMetadata,
+ getNestedProperty,
+ stringifyToolResultContent,
+ isRichToolResult,
+} from "../helpers";
+import { z } from "zod/v4";
+
+/**
+ * Detection schemas for Microsoft Agent Framework format
+ *
+ * Microsoft Agent Framework uses a ChatML-like format with parts arrays:
+ * - Messages: {role: "user|assistant|tool", parts: [{type, ...}]}
+ * - Tool calls: {type: "tool_call", id: [...], name, arguments}
+ * - Tool responses: {type: "tool_call_response", id: [...], response}
+ * - Text: {type: "text", content}
+ */
+
+// Microsoft Agent message with parts array
+const MicrosoftAgentMessageSchema = z.looseObject({
+ role: z.enum(["user", "assistant", "tool"]),
+ parts: z.array(
+ z.looseObject({
+ type: z.enum(["text", "tool_call", "tool_call_response"]),
+ }),
+ ),
+});
+
+// Array of Microsoft Agent messages
+const MicrosoftAgentMessagesSchema = z.array(MicrosoftAgentMessageSchema);
+
+/**
+ * Extract tool calls and text content from parts array
+ * Handles: text, tool_call, tool_call_response
+ */
+function extractFromParts(parts: unknown[]): {
+ toolCalls: Array<Record<string, unknown>>;
+ text: string;
+ toolCallId?: string;
+} {
+ const toolCalls: Array<Record<string, unknown>> = [];
+ const textParts: string[] = [];
+ let toolCallId: string | undefined;
+
+ for (const part of parts) {
+ if (!part || typeof part !== "object") continue;
+
+ const p = part as Record<string, unknown>;
+
+ // Handle tool_call: {type: "tool_call", id: [...], name, arguments}
+ if (p.type === "tool_call") {
+ // uses array IDs: ["run_id", "call_id"], we just need the call id,
+ let callId = "";
+ if (Array.isArray(p.id)) {
+ const callIdMatch = p.id.find(
+ (id) => typeof id === "string" && id.startsWith("call_"),
+ );
+ callId = callIdMatch || p.id[p.id.length - 1] || "";
+ } else if (typeof p.id === "string") {
+ callId = p.id;
+ }
+
+ toolCalls.push({
+ id: callId,
+ name: p.name,
+ arguments:
+ typeof p.arguments === "string"
+ ? p.arguments
+ : JSON.stringify(p.arguments ?? {}),
+ type: "function",
+ });
+ continue;
+ }
+
+ // Handle text: {type: "text", content}
+ if (p.type === "text" && typeof p.content === "string") {
+ textParts.push(p.content);
+ continue;
+ }
+
+ // Handle tool_call_response: {type: "tool_call_response", id: [...], response}
+ if (p.type === "tool_call_response") {
+ // we just need the call_id, again
+ if (Array.isArray(p.id)) {
+ const callIdMatch = p.id.find(
+ (id) => typeof id === "string" && id.startsWith("call_"),
+ );
+ toolCallId = callIdMatch || p.id[p.id.length - 1] || "";
+ } else if (typeof p.id === "string") {
+ toolCallId = p.id;
+ }
+ textParts.push(stringifyToolResultContent(p.response));
+ }
+ }
+
+ return {
+ toolCalls,
+ text: textParts.join(""),
+ toolCallId,
+ };
+}
+
+/**
+ * Extract tool definitions from metadata.attributes["gen_ai.tool.definitions"]
+ * Microsoft Agent Framework uses OpenAI-style tool definitions
+ */
+function extractToolDefinitions(tools: unknown): Array<{
+ name: string;
+ description?: string;
+ parameters?: Record<string, unknown>;
+}> {
+ if (!Array.isArray(tools)) return [];
+
+ const definitions: Array<{
+ name: string;
+ description?: string;
+ parameters?: Record<string, unknown>;
+ }> = [];
+
+ for (const tool of tools) {
+ if (!tool || typeof tool !== "object") continue;
+ const t = tool as Record<string, unknown>;
+
+ // Handle OpenAI-style tool definitions: {type: "function", function: {name, description, parameters}}
+ // intentionally not imported from openai for separation of concerns
+ if (t.type === "function" && t.function && typeof t.function === "object") {
+ const func = t.function as Record<string, unknown>;
+ const toolDef: Record<string, unknown> = {
+ name: func.name || "",
+ };
+ if (func.description !== null && func.description !== undefined) {
+ toolDef.description = func.description;
+ }
+ if (func.parameters !== null && func.parameters !== undefined) {
+ toolDef.parameters = func.parameters;
+ }
+ definitions.push(
+ toolDef as {
+ name: string;
+ description?: string;
+ parameters?: Record<string, unknown>;
+ },
+ );
+ }
+ }
+
+ return definitions;
+}
+
+// Normalize a single Microsoft Agent message to our ChatML format
+function normalizeMicrosoftAgentMessage(msg: unknown): Record<string, unknown> {
+ if (!msg || typeof msg !== "object") return {};
+
+ const message = msg as Record<string, unknown>;
+ const normalized = { ...message };
+
+ if (normalized.parts && Array.isArray(normalized.parts)) {
+ const { toolCalls, text, toolCallId } = extractFromParts(normalized.parts);
+
+ if (toolCalls.length > 0) {
+ normalized.tool_calls = toolCalls;
+ }
+
+ if (text) {
+ normalized.content = text;
+ }
+
+ // Set tool_call_id for tool messages (from tool_call_response)
+ if (toolCallId && normalized.role === "tool") {
+ normalized.tool_call_id = toolCallId;
+ }
+
+ // prevent showing in passthrough
+ delete normalized.parts;
+ }
+
+ // For tool messages with rich object content, spread into message
+ // so it goes to json passthrough field → renders as PrettyJsonView.
+ // Rich = nested structure OR 3+ keys. Simple <=2 scalar keys.
+ if (
+ normalized.role === "tool" &&
+ typeof normalized.content === "object" &&
+ normalized.content !== null &&
+ !Array.isArray(normalized.content)
+ ) {
+ if (isRichToolResult(normalized.content)) {
+ // Rich object: spread for table rendering
+ const { content, ...rest } = normalized;
+ return { ...rest, ...content };
+ } else {
+ // Simple object: stringify for text rendering
+ normalized.content = stringifyToolResultContent(normalized.content);
+ }
+ }
+
+ return normalized;
+}
+
+function normalizeMessages(data: unknown[]): unknown[] {
+ return data.map(normalizeMicrosoftAgentMessage);
+}
+
+function preprocessData(data: unknown, ctx: NormalizerContext): unknown {
+ if (!data) return data;
+
+ if (Array.isArray(data)) {
+ const normalized = normalizeMessages(data);
+
+ // extract tool definitions from metadata
+ const meta = parseMetadata(ctx.metadata);
+ const toolDefinitions = getNestedProperty(
+ meta,
+ "attributes",
+ "gen_ai.tool.definitions",
+ );
+
+ if (toolDefinitions) {
+ const tools = extractToolDefinitions(toolDefinitions);
+ if (tools.length > 0) {
+ return normalized.map((msg) => ({
+ ...(msg as Record<string, unknown>),
+ tools,
+ }));
+ }
+ }
+
+ return normalized;
+ }
+
+ // messages wrapper
+ if (typeof data === "object" && "messages" in data) {
+ const obj = data as Record<string, unknown>;
+ return {
+ ...obj,
+ messages: Array.isArray(obj.messages)
+ ? normalizeMessages(obj.messages)
+ : obj.messages,
+ };
+ }
+
+ // single message
+ if (typeof data === "object" && "role" in data) {
+ return normalizeMicrosoftAgentMessage(data);
+ }
+
+ return data;
+}
+
+export const microsoftAgentAdapter: ProviderAdapter = {
+ id: "microsoft-agent",
+
+ detect(ctx: NormalizerContext): boolean {
+ const meta = parseMetadata(ctx.metadata);
+
+ // HINTS: Fast checks for explicit Microsoft Agent Framework indicators
+ if (ctx.framework === "microsoft-agent") return true;
+
+ const scopeName = getNestedProperty(meta, "scope", "name");
+ if (scopeName === "agent_framework") return true;
+
+ const providerName = getNestedProperty(
+ meta,
+ "attributes",
+ "gen_ai.provider.name",
+ );
+ if (providerName === "microsoft.agent_framework") return true;
+
+ // STRUCTURAL: Schema-based detection on metadata
+ if (MicrosoftAgentMessagesSchema.safeParse(ctx.metadata).success)
+ return true;
+
+ // Schema-based detection on data (slower, do last)
+ if (MicrosoftAgentMessagesSchema.safeParse(ctx.data).success) return true;
+ if (MicrosoftAgentMessageSchema.safeParse(ctx.data).success) return true;
+
+ return false;
+ },
+
+ preprocess(
+ data: unknown,
+ _kind: "input" | "output",
+ ctx: NormalizerContext,
+ ): unknown {
+ return preprocessData(data, ctx);
+ },
+};
diff --git a/packages/shared/src/utils/chatml/adapters/openai.ts b/packages/shared/src/utils/chatml/adapters/openai.ts
new file mode 100644
index 0000000000..d9d7b74016
--- /dev/null
+++ b/packages/shared/src/utils/chatml/adapters/openai.ts
@@ -0,0 +1,398 @@
+import type { NormalizerContext, ProviderAdapter } from "../types";
+import {
+ removeNullFields,
+ stringifyToolResultContent,
+ parseMetadata,
+ isRichToolResult,
+} from "../helpers";
+import { z } from "zod/v4";
+
+/**
+ * Detection schemas for OpenAI formats
+ * These are permissive - only validate structural markers, not full API contracts
+ */
+
+// INPUT SCHEMAS (requests)
+const OpenAIInputChatCompletionsSchema = z.looseObject({
+ messages: z.array(z.any()),
+ tools: z.array(z.any()).optional(),
+});
+
+const OpenAIInputMessagesSchema = z
+ .array(
+ z.looseObject({
+ role: z.enum(["system", "user", "assistant", "tool", "function"]),
+ }),
+ )
+ .refine(
+ (data) => {
+ // Reject if any message has top-level parts (Microsoft Agent/Gemini format)
+ // OpenAI uses parts inside content, not at message level
+ return !data.some(
+ (msg) =>
+ typeof msg === "object" &&
+ msg !== null &&
+ "parts" in msg &&
+ Array.isArray((msg as Record<string, unknown>).parts),
+ );
+ },
+ { message: "Messages with top-level parts are not OpenAI format" },
+ );
+
+// OUTPUT SCHEMAS (responses)
+const OpenAIOutputResponsesSchema = z.looseObject({
+ output: z.array(z.any()),
+ tools: z.array(z.any()).optional(),
+});
+
+const OpenAIOutputChoicesSchema = z.looseObject({
+ model: z.string(),
+ choices: z.array(z.any()),
+});
+
+const OpenAIOutputSingleMessageSchema = z.looseObject({
+ role: z.string(),
+ tool_calls: z.array(
+ z.looseObject({
+ type: z.string(),
+ function: z.looseObject({
+ name: z.string(),
+ }),
+ }),
+ ),
+});
+
+function normalizeMessage(msg: unknown): Record<string, unknown> {
+ if (!msg || typeof msg !== "object") return {};
+
+ // we want to do type-based conversions BEFORE removeNullFields
+ // because removeNullFields moves unrecognized fields to json passthrough
+ let working = msg as Record<string, unknown>;
+
+ // Convert direct function call message to tool_calls array format
+ // Format: { type: "function_call", name: "...", arguments: {...}, call_id: "..." }
+ // Convert to: { role: "assistant", tool_calls: [{ id, name, arguments, type }] }
+ if (
+ (working.type === "function_call" || working.type === "tool_call") &&
+ working.name &&
+ typeof working.name === "string"
+ ) {
+ const toolCall: Record<string, unknown> = {
+ id: working.call_id || working.id || "",
+ name: working.name,
+ arguments:
+ typeof working.arguments === "string"
+ ? working.arguments
+ : JSON.stringify(working.arguments ?? {}),
+ type: "function",
+ };
+
+ const {
+ type: _type,
+ name: _name,
+ arguments: _args,
+ call_id: _call_id,
+ id: _id,
+ status: _status,
+ ...rest
+ } = working;
+ working = {
+ ...rest,
+ role: rest.role || "assistant",
+ tool_calls: [toolCall],
+ };
+ }
+
+ // Convert function_call_output to standard tool message format
+ // Format: { type: "function_call_output", call_id: "...", output: "..." }
+ // Convert to: { role: "tool", tool_call_id: "...", content: "..." }
+ if (working.type === "function_call_output") {
+ const content =
+ typeof working.output === "string"
+ ? working.output
+ : JSON.stringify(working.output ?? "");
+
+ const { type: _type, call_id, output: _output, ...rest } = working;
+
+ working = {
+ ...rest,
+ role: "tool",
+ tool_call_id: call_id,
+ content,
+ };
+ }
+
+ // Now apply removeNullFields after conversions
+ let normalized = removeNullFields(working);
+
+ // Extract text from OpenAI Agents output_text format
+ // Format: content: [{type: "output_text", text: "..."}]
+ if (
+ normalized.content &&
+ Array.isArray(normalized.content) &&
+ normalized.content.length > 0
+ ) {
+ const firstItem = normalized.content[0];
+ if (
+ firstItem &&
+ typeof firstItem === "object" &&
+ (firstItem as Record<string, unknown>).type === "output_text" &&
+ typeof (firstItem as Record<string, unknown>).text === "string"
+ ) {
+ // Extract just the text for simple output
+ normalized.content = (firstItem as Record<string, unknown>).text;
+ }
+ }
+
+ // Normalize camelCase toolCalls to snake_case tool_calls (VAPI framework does this, otherwise it matches OpenAI)
+ if ("toolCalls" in normalized && Array.isArray(normalized.toolCalls)) {
+ normalized.tool_calls = normalized.toolCalls;
+ delete normalized.toolCalls;
+ }
+
+ // Flatten OpenAI nested tool_calls format: function.name → name, function.arguments → arguments
+ // Format: { id, type: "function", function: { name, arguments } }
+ // Convert to: { id, name, arguments, type }
+ if (normalized.tool_calls && Array.isArray(normalized.tool_calls)) {
+ const sanitizedToolCalls = (normalized.tool_calls as unknown[]).filter(
+ (tc): tc is Record<string, unknown> =>
+ Boolean(tc) && typeof tc === "object",
+ );
+
+ normalized.tool_calls = sanitizedToolCalls.map((tc) => {
+ if (tc.function && typeof tc.function === "object") {
+ const func = tc.function as Record<string, unknown>;
+ return {
+ id: tc.id,
+ name: func.name,
+ arguments:
+ typeof func.arguments === "string"
+ ? func.arguments
+ : JSON.stringify(func.arguments ?? {}),
+ type: tc.type || "function",
+ index: tc.index,
+ };
+ }
+ // Already flat format, just ensure arguments is stringified
+ return {
+ ...tc,
+ arguments:
+ typeof tc.arguments === "string"
+ ? tc.arguments
+ : JSON.stringify(tc.arguments ?? {}),
+ };
+ });
+ }
+
+ // For tool messages with rich object content, spread into message
+ // so it goes to json passthrough field and renders as PrettyJsonView.
+ // Rich = nested structure OR 3+ keys. Simple <=2 scalar keys.
+ if (
+ normalized.role === "tool" &&
+ typeof normalized.content === "object" &&
+ normalized.content !== null &&
+ !Array.isArray(normalized.content)
+ ) {
+ if (isRichToolResult(normalized.content)) {
+ // Rich object: spread for table rendering
+ const { content, ...rest } = normalized;
+ return { ...rest, ...content };
+ } else {
+ // Simple object: stringify for text rendering
+ normalized.content = stringifyToolResultContent(normalized.content);
+ }
+ }
+
+ return normalized;
+}
+
+/**
+ * Flatten tool definition from nested or flat format to standard format
+ * Handles both Chat Completions {type, function: {name, ...}} and flat {name, ...}
+ */
+function flattenToolDefinition(tool: unknown): Record<string, unknown> {
+ if (typeof tool !== "object" || !tool) return {};
+
+ const t = tool as Record<string, unknown>;
+ // Handle nested {type, function: {name, ...}} or flat {name, ...}
+ const toolFunc = (t.function as Record<string, unknown> | undefined) ?? t;
+
+ const toolDef: Record<string, unknown> = {
+ name: toolFunc.name,
+ description: toolFunc.description ?? "",
+ };
+ if (toolFunc.parameters != null) toolDef.parameters = toolFunc.parameters;
+ return toolDef;
+}
+
+function preprocessData(data: unknown): unknown {
+ if (!data) return data;
+
+ // OpenAI Chat Completions API: {tools, messages} OR Responses API: {tools, output}
+ // References:
+ // - https://platform.openai.com/docs/api-reference/chat/create
+ // - https://platform.openai.com/docs/api-reference/responses
+ if (
+ typeof data === "object" &&
+ !Array.isArray(data) &&
+ "tools" in data &&
+ (("messages" in data && !("output" in data)) || "output" in data)
+ ) {
+ const obj = data as Record<string, unknown>;
+ const messagesArray = (obj.messages ?? obj.output) as unknown[];
+
+ if (Array.isArray(messagesArray) && Array.isArray(obj.tools)) {
+ // Attach tools to all messages
+ return messagesArray.map((msg) => ({
+ ...normalizeMessage(msg),
+ tools: (obj.tools as unknown[]).map(flattenToolDefinition),
+ }));
+ }
+ }
+
+ // Responses API without tools: {output: [...]}
+ if (
+ typeof data === "object" &&
+ !Array.isArray(data) &&
+ "output" in data &&
+ !("messages" in data) &&
+ !("tools" in data)
+ ) {
+ const obj = data as Record<string, unknown>;
+ if (Array.isArray(obj.output)) {
+ return (obj.output as unknown[]).map(normalizeMessage);
+ }
+ }
+
+ // Chat Completions response: {choices: [{message: {...}}]}
+ if (typeof data === "object" && !Array.isArray(data) && "choices" in data) {
+ const obj = data as Record<string, unknown>;
+ if (Array.isArray(obj.choices) && obj.choices.length > 0) {
+ const firstChoice = obj.choices[0] as Record<string, unknown>;
+ if (
+ firstChoice &&
+ typeof firstChoice === "object" &&
+ "message" in firstChoice
+ ) {
+ return normalizeMessage(firstChoice.message);
+ }
+ }
+ }
+
+ // Array of messages
+ if (Array.isArray(data)) {
+ return data.map(normalizeMessage);
+ }
+
+ // Object with messages key
+ if (typeof data === "object" && "messages" in data) {
+ const obj = data as Record<string, unknown>;
+ return {
+ ...obj,
+ messages: Array.isArray(obj.messages)
+ ? obj.messages.map(normalizeMessage)
+ : obj.messages,
+ };
+ }
+
+ // Single message
+ if (typeof data === "object" && "role" in data) {
+ return normalizeMessage(data);
+ }
+
+ return data;
+}
+
+export const openAIAdapter: ProviderAdapter = {
+ id: "openai",
+
+ detect(ctx: NormalizerContext): boolean {
+ const meta = parseMetadata(ctx.metadata);
+
+ // REJECTIONS: Explicit rejection of LangGraph/LangChain formats
+ if (meta && typeof meta === "object") {
+ // LangGraph
+ if (
+ "langgraph_step" in meta ||
+ "langgraph_node" in meta ||
+ "langgraph_path" in meta ||
+ meta.framework === "langgraph" ||
+ (Array.isArray(meta.tags) && meta.tags.includes("langgraph"))
+ ) {
+ return false;
+ }
+
+ // LangChain (type without role)
+ if (
+ ctx.metadata &&
+ typeof ctx.metadata === "object" &&
+ "messages" in ctx.metadata
+ ) {
+ const messages = (ctx.metadata as Record<string, unknown>).messages;
+ if (Array.isArray(messages)) {
+ const hasLangChainType = messages.some((msg: unknown) => {
+ // Null guard: ensure msg exists and is an object before accessing properties
+ if (!msg || typeof msg !== "object") {
+ return false;
+ }
+ const message = msg as Record<string, unknown>;
+ return (
+ message.type &&
+ typeof message.type === "string" &&
+ ["human", "ai", "tool", "system"].includes(message.type) &&
+ !("role" in message)
+ );
+ });
+ if (hasLangChainType) return false;
+ }
+ }
+ }
+
+ // HINTS: Fast checks for explicit OpenAI indicators
+ if (ctx.framework === "openai") return true;
+ if (ctx.observationName?.toLowerCase().includes("openai")) return true;
+ if (meta?.ls_provider === "openai") return true;
+
+ // Metadata attributes check
+ if (meta && typeof meta === "object" && "attributes" in meta) {
+ const attributes = (meta as Record<string, unknown>).attributes;
+ if (
+ attributes &&
+ typeof attributes === "object" &&
+ (attributes as Record<string, unknown>)["llm.system"] === "openai"
+ ) {
+ return true;
+ }
+ }
+
+ // STRUCTURAL: Schema-based detection on metadata
+ if (OpenAIInputChatCompletionsSchema.safeParse(ctx.metadata).success)
+ return true;
+ if (OpenAIInputMessagesSchema.safeParse(ctx.metadata).success) return true;
+ if (OpenAIOutputResponsesSchema.safeParse(ctx.metadata).success)
+ return true;
+ if (OpenAIOutputChoicesSchema.safeParse(ctx.metadata).success) return true;
+ if (OpenAIOutputSingleMessageSchema.safeParse(ctx.metadata).success)
+ return true;
+
+ // finally, test on data if available. we might've done this already if we passed
+ // data into metadata. we only do this last due to performance concerns.
+ if (OpenAIInputChatCompletionsSchema.safeParse(ctx.data).success)
+ return true;
+ if (OpenAIInputMessagesSchema.safeParse(ctx.data).success) return true;
+ if (OpenAIOutputResponsesSchema.safeParse(ctx.data).success) return true;
+ if (OpenAIOutputChoicesSchema.safeParse(ctx.data).success) return true;
+ if (OpenAIOutputSingleMessageSchema.safeParse(ctx.data).success)
+ return true;
+
+ return false;
+ },
+
+ preprocess(
+ data: unknown,
+ _kind: "input" | "output",
+ _ctx: NormalizerContext,
+ ): unknown {
+ return preprocessData(data);
+ },
+};
diff --git a/packages/shared/src/utils/chatml/adapters/pydantic-ai.ts b/packages/shared/src/utils/chatml/adapters/pydantic-ai.ts
new file mode 100644
index 0000000000..9db49e6453
--- /dev/null
+++ b/packages/shared/src/utils/chatml/adapters/pydantic-ai.ts
@@ -0,0 +1,227 @@
+import type { NormalizerContext, ProviderAdapter } from "../types";
+import { removeNullFields, parseMetadata, getNestedProperty } from "../helpers";
+import { z } from "zod/v4";
+
+/**
+ * Pydantic AI adapter
+ * Handles pydantic-ai's parts-based message format
+ *
+ * Pydantic AI uses parts arrays:
+ * - Text: {type: "text", content: "..."}
+ * - Tool calls: {type: "tool_call", id, name, arguments}
+ * - Tool responses: {type: "tool_call_response", id, name, result}
+ * Tools are in: metadata.attributes.model_request_parameters.function_tools
+ */
+
+// Detection schema
+const PydanticAIMessagesSchema = z.array(
+ z.looseObject({
+ role: z.enum(["system", "user", "assistant"]),
+ parts: z.array(z.any()),
+ }),
+);
+
+/**
+ * Extract tool calls, text, and tool responses from parts array
+ */
+function extractFromParts(parts: unknown[]): {
+ toolCalls: Array<Record<string, unknown>>;
+ toolResponses: Array<Record<string, unknown>>;
+ text: string;
+} {
+ const toolCalls: Array<Record<string, unknown>> = [];
+ const toolResponses: Array<Record<string, unknown>> = [];
+ const textParts: string[] = [];
+
+ for (const part of parts) {
+ if (!part || typeof part !== "object") continue;
+ const p = part as Record<string, unknown>;
+
+ if (p.type === "text" && typeof p.content === "string") {
+ textParts.push(p.content);
+ } else if (p.type === "tool_call") {
+ toolCalls.push({
+ id: p.id,
+ name: p.name,
+ arguments:
+ typeof p.arguments === "string"
+ ? p.arguments
+ : JSON.stringify(p.arguments ?? {}),
+ type: "function",
+ });
+ } else if (p.type === "tool_call_response") {
+ toolResponses.push({
+ tool_call_id: p.id,
+ content:
+ typeof p.result === "string"
+ ? p.result
+ : JSON.stringify(p.result ?? ""),
+ });
+ }
+ }
+
+ return { toolCalls, toolResponses, text: textParts.join("") };
+}
+
+/**
+ * Normalize pydantic-ai tool definition to standard format
+ */
+function normalizeToolDefinition(tool: unknown): Record<string, unknown> {
+ if (!tool || typeof tool !== "object") return {};
+
+ const t = tool as Record<string, unknown>;
+ const normalized: Record<string, unknown> = {
+ name: t.name,
+ description: t.description || "",
+ };
+
+ // pydantic-ai uses parameters_json_schema instead of parameters
+ if (t.parameters_json_schema) {
+ normalized.parameters = t.parameters_json_schema;
+ }
+
+ return normalized;
+}
+
+/**
+ * Extract tool definitions from pydantic-ai metadata
+ * Tools are in: metadata.attributes.model_request_parameters.function_tools
+ */
+function extractToolDefinitions(
+ metadata: unknown,
+): Array<Record<string, unknown>> {
+ const meta = parseMetadata(metadata);
+ if (!meta) return [];
+
+ const tools = getNestedProperty(
+ meta,
+ "attributes",
+ "model_request_parameters",
+ "function_tools",
+ );
+
+ if (Array.isArray(tools)) {
+ return tools.map(normalizeToolDefinition);
+ }
+
+ return [];
+}
+
+/**
+ * Normalize a single pydantic-ai message
+ * Returns either a single message or array of messages (for tool responses)
+ */
+function normalizeMessage(
+ msg: unknown,
+): Record<string, unknown> | Record<string, unknown>[] {
+ if (!msg || typeof msg !== "object") return {};
+
+ const message = msg as Record<string, unknown>;
+
+ // If no parts, return as-is
+ if (!Array.isArray(message.parts)) {
+ return removeNullFields(message);
+ }
+
+ const { toolCalls, toolResponses, text } = extractFromParts(message.parts);
+
+ // Extract other fields (exclude role and parts)
+ const { role: _role, parts: _parts, ...rest } = message;
+
+ // Assistant message with tool calls
+ if (message.role === "assistant" && toolCalls.length > 0) {
+ return removeNullFields({
+ role: "assistant",
+ content: text || "",
+ tool_calls: toolCalls,
+ ...rest,
+ });
+ }
+
+ // User message with tool responses - split into separate tool messages
+ if (message.role === "user" && toolResponses.length > 0) {
+ return toolResponses.map((tr) =>
+ removeNullFields({
+ role: "tool",
+ ...tr,
+ }),
+ );
+ }
+
+ // Regular text message
+ return removeNullFields({
+ role: message.role,
+ content: text || "",
+ ...rest,
+ });
+}
+
+function normalizeMessages(data: unknown[]): unknown[] {
+ return data.flatMap((msg) => {
+ const normalized = normalizeMessage(msg);
+ return Array.isArray(normalized) ? normalized : [normalized];
+ });
+}
+
+function preprocessData(data: unknown, ctx: NormalizerContext): unknown {
+ if (!data) return data;
+
+ // Handle array of messages
+ if (Array.isArray(data)) {
+ const normalized = normalizeMessages(data);
+
+ // Extract and attach tool definitions from metadata
+ const tools = extractToolDefinitions(ctx.metadata);
+ if (tools.length > 0) {
+ return normalized.map((msg) => ({
+ ...(msg as Record<string, unknown>),
+ tools,
+ }));
+ }
+
+ return normalized;
+ }
+
+ // messages wrapper
+ if (typeof data === "object" && "messages" in data) {
+ const obj = data as Record<string, unknown>;
+ return {
+ ...obj,
+ messages: Array.isArray(obj.messages)
+ ? normalizeMessages(obj.messages)
+ : obj.messages,
+ };
+ }
+
+ // Single message
+ return normalizeMessage(data);
+}
+
+export const pydanticAIAdapter: ProviderAdapter = {
+ id: "pydantic-ai",
+
+ detect(ctx: NormalizerContext): boolean {
+ const meta = parseMetadata(ctx.metadata);
+
+ if (ctx.framework === "pydantic-ai") return true;
+
+ const scopeName = getNestedProperty(meta, "scope", "name");
+ if (scopeName === "pydantic-ai") return true;
+
+ // STRUCTURAL: Schema-based detection on metadata (check metadata first for performance)
+ if (PydanticAIMessagesSchema.safeParse(ctx.metadata).success) return true;
+
+ // Schema-based detection on data (slower, do last)
+ if (PydanticAIMessagesSchema.safeParse(ctx.data).success) return true;
+
+ return false;
+ },
+
+ preprocess(
+ data: unknown,
+ _kind: "input" | "output",
+ ctx: NormalizerContext,
+ ): unknown {
+ return preprocessData(data, ctx);
+ },
+};
diff --git a/web/src/utils/chatml/core.ts b/packages/shared/src/utils/chatml/core.ts
similarity index 66%
rename from web/src/utils/chatml/core.ts
rename to packages/shared/src/utils/chatml/core.ts
index 361e22d820..ce3326f516 100644
--- a/web/src/utils/chatml/core.ts
+++ b/packages/shared/src/utils/chatml/core.ts
@@ -1,8 +1,18 @@
+/**
+ * ChatML core normalization functions.
+ *
+ * NOTE: Moved to shared package to enable testing
+ * because web can't import from worker. Also, web tests
+ * can't import from shared, so tested FE logic
+ */
import { z } from "zod/v4";
import {
ChatMlArraySchema,
- type ChatMlMessageSchema,
-} from "@/src/components/schemas/ChatMlSchema";
+ ChatMlMessageSchema,
+} from "../IORepresentation/chatML/types";
+import { selectAdapter, type NormalizerContext } from "./adapters";
+
+type ChatMlMessage = z.infer<typeof ChatMlMessageSchema>;
export function mapToChatMl(
input: unknown,
@@ -88,7 +98,7 @@ export function combineInputOutputMessages(
inputResult: ReturnType<typeof mapToChatMl>,
outputResult: ReturnType<typeof mapOutputToChatMl>,
cleanOutput: unknown,
-): ChatMlMessageSchema[] {
+): ChatMlMessage[] {
if (!inputResult.success) {
return [];
}
@@ -106,9 +116,43 @@ export function combineInputOutputMessages(
...(typeof cleanOutput === "string"
? { content: cleanOutput }
: { json: cleanOutput }),
- } as ChatMlMessageSchema,
+ } as ChatMlMessage,
]),
];
return combinedMessages;
}
+
+/**
+ * Normalize input using shared adapters with frontend schema validation.
+ * Uses adapters from shared package but validates with strict frontend schema.
+ */
+export function normalizeInput(
+ input: unknown,
+ ctx: NormalizerContext = {},
+): ReturnType<typeof ChatMlArraySchema.safeParse> {
+ const adapter = selectAdapter({
+ ...ctx,
+ metadata: ctx.metadata ?? input,
+ data: input,
+ });
+ const preprocessed = adapter.preprocess(input, "input", ctx);
+ return mapToChatMl(preprocessed);
+}
+
+/**
+ * Normalize output using shared adapters with frontend schema validation.
+ * Uses adapters from shared package but validates with strict frontend schema.
+ */
+export function normalizeOutput(
+ output: unknown,
+ ctx: NormalizerContext = {},
+): ReturnType<typeof ChatMlArraySchema.safeParse> {
+ const adapter = selectAdapter({
+ ...ctx,
+ metadata: ctx.metadata ?? output,
+ data: output,
+ });
+ const preprocessed = adapter.preprocess(output, "output", ctx);
+ return mapOutputToChatMl(preprocessed);
+}
diff --git a/packages/shared/src/utils/chatml/helpers.ts b/packages/shared/src/utils/chatml/helpers.ts
new file mode 100644
index 0000000000..b6adc84a2d
--- /dev/null
+++ b/packages/shared/src/utils/chatml/helpers.ts
@@ -0,0 +1,99 @@
+export function removeNullFields(obj: unknown): Record<string, unknown> {
+ if (!obj || typeof obj !== "object") return {};
+
+ const cleaned: Record<string, unknown> = { ...obj };
+
+ Object.keys(cleaned).forEach((key) => {
+ if (cleaned[key] === null) {
+ delete cleaned[key];
+ }
+ });
+
+ return cleaned;
+}
+
+export function stringifyToolCallArgs(
+ toolCall: Record<string, unknown>,
+): Record<string, unknown> {
+ if (!toolCall?.function) return toolCall;
+
+ const func = toolCall.function as Record<string, unknown>;
+ return {
+ ...toolCall,
+ function: {
+ ...func,
+ arguments:
+ typeof func.arguments === "string"
+ ? func.arguments
+ : JSON.stringify(func.arguments ?? {}),
+ },
+ };
+}
+
+export function stringifyToolResultContent(content: unknown): string {
+ if (typeof content === "string") return content;
+ if (content === null || content === undefined) return "";
+ return JSON.stringify(content);
+}
+
+/**
+ * used to check if a tool call is "complex" to render as PrettyJsonView table
+ * or stringify it and render it as pure string. only used for role: tool type
+ * calls. used for tool calls themselves, not for tool selections by an LLM.
+ *
+ * Rich = has nested structure OR has more than 2 top-level keys
+ * Simple <= 2 keys with only scalar values (strings, numbers, booleans, null)
+ */
+export function isRichToolResult(content: unknown): boolean {
+ if (!content || typeof content !== "object" || Array.isArray(content)) {
+ return false;
+ }
+
+ const keys = Object.keys(content);
+
+ // More than 2 keys → probably rich/structured data
+ if (keys.length > 2) return true;
+
+ // Check if any value is an object or array (nested structure)
+ for (const key of keys) {
+ const value = (content as Record<string, unknown>)[key];
+ if (value && typeof value === "object") {
+ return true; // Has nested structure
+ }
+ }
+
+ // 1-2 keys with only scalar values: simple
+ return false;
+}
+
+export function parseMetadata(
+ metadata: unknown,
+): Record<string, unknown> | null {
+ if (!metadata) return null;
+
+ if (typeof metadata === "string") {
+ try {
+ return JSON.parse(metadata);
+ } catch {
+ return null;
+ }
+ }
+
+ if (typeof metadata === "object") {
+ return metadata as Record<string, unknown>;
+ }
+
+ return null;
+}
+
+export function getNestedProperty(
+ obj: Record<string, unknown> | null | undefined,
+ ...path: string[]
+): unknown {
+ let current: unknown = obj;
+ for (const key of path) {
+ if (!current || typeof current !== "object") return undefined;
+ current = (current as Record<string, unknown>)[key];
+ }
+ return current;
+}
diff --git a/packages/shared/src/utils/chatml/index.ts b/packages/shared/src/utils/chatml/index.ts
new file mode 100644
index 0000000000..94ec711264
--- /dev/null
+++ b/packages/shared/src/utils/chatml/index.ts
@@ -0,0 +1,20 @@
+export * from "./types";
+export * from "./helpers";
+export * from "./core";
+export {
+ SimpleChatMlArraySchema,
+ ChatMlArraySchema,
+ ChatMlMessageSchema,
+} from "../IORepresentation/chatML/types";
+
+// Explicitly export adapters to ensure they're available
+export {
+ selectAdapter,
+ langgraphAdapter,
+ aisdkAdapter,
+ openAIAdapter,
+ geminiAdapter,
+ microsoftAgentAdapter,
+ pydanticAIAdapter,
+ genericAdapter,
+} from "./adapters";
diff --git a/packages/shared/src/utils/chatml/types.ts b/packages/shared/src/utils/chatml/types.ts
new file mode 100644
index 0000000000..ff49e23f20
--- /dev/null
+++ b/packages/shared/src/utils/chatml/types.ts
@@ -0,0 +1,35 @@
+export type NormalizerContext = {
+ metadata?: unknown;
+ observationName?: string;
+ framework?: string; // for explicit overrides
+ data?: unknown; // Optional: actual input/output content for structural detection
+};
+
+// Unified tool event representation across all providers
+export type ToolEvent =
+ | {
+ type: "call";
+ id?: string;
+ name: string;
+ argsJson: string; // Always JSON string for consistency
+ }
+ | {
+ type: "result";
+ id?: string;
+ content: string; // Always string (stringify objects)
+ status?: "ok" | "error";
+ };
+
+// Minimal provider adapter interface
+/* eslint-disable no-unused-vars */
+export interface ProviderAdapter {
+ id: string;
+ detect(ctx: NormalizerContext): boolean;
+ preprocess(
+ data: unknown,
+ kind: "input" | "output",
+ ctx: NormalizerContext,
+ ): unknown;
+ extractToolEvents?(message: Record<string, unknown>): ToolEvent[];
+}
+/* eslint-enable no-unused-vars */
diff --git a/web/src/components/schemas/ChatMlSchema.ts b/web/src/components/schemas/ChatMlSchema.ts
index 0796d72a7f..8ab49dfd95 100644
--- a/web/src/components/schemas/ChatMlSchema.ts
+++ b/web/src/components/schemas/ChatMlSchema.ts
@@ -1,37 +1,2 @@
-import { BaseChatMlMessageSchema } from "@langfuse/shared";
-import { z } from "zod/v4";
-
-export const ChatMlMessageSchema = BaseChatMlMessageSchema.refine(
- (value) => value.content !== null || value.role !== undefined,
-)
- .transform(({ additional_kwargs, ...other }) => ({
- ...other,
- ...additional_kwargs,
- }))
- .transform(
- ({
- role,
- name,
- content,
- audio,
- type,
- tools,
- tool_calls,
- tool_call_id,
- ...other
- }) => ({
- role,
- name,
- content,
- audio,
- type,
- tools,
- tool_calls,
- tool_call_id,
- ...(Object.keys(other).length === 0 ? {} : { json: other }),
- }),
- );
-export type ChatMlMessageSchema = z.infer<typeof ChatMlMessageSchema>;
-
-export const ChatMlArraySchema = z.array(ChatMlMessageSchema).min(1);
-export type ChatMlArraySchema = z.infer<typeof ChatMlArraySchema>;
+// Re-export from shared (moved to enable worker tests)
+export { ChatMlMessageSchema, ChatMlArraySchema } from "@langfuse/shared";
diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsx
index 1640e8c7a7..9fb0e9add6 100644
--- a/web/src/components/table/use-cases/observations.tsx
+++ b/web/src/components/table/use-cases/observations.tsx
@@ -111,6 +111,8 @@ export type ObservationsTableRow = {
inputCost?: number;
outputCost?: number;
};
+ toolDefinitions?: number;
+ toolCalls?: number;
};
export type ObservationsTableProps = {
@@ -337,6 +339,16 @@ export default function ObservationsTable({
value: t.value,
count: t.count !== undefined ? Number(t.count) : undefined,
})) ?? undefined,
+ toolNames:
+ filterOptions.data?.toolNames?.map((tn) => ({
+ value: tn.value,
+ count: tn.count !== undefined ? Number(tn.count) : undefined,
+ })) ?? undefined,
+ calledToolNames:
+ filterOptions.data?.calledToolNames?.map((ctn) => ({
+ value: ctn.value,
+ count: ctn.count !== undefined ? Number(ctn.count) : undefined,
+ })) ?? undefined,
latency: [],
timeToFirstToken: [],
tokensPerSecond: [],
@@ -661,6 +673,36 @@ export default function ObservationsTable({
enableHiding: true,
enableSorting: true,
},
+ {
+ accessorKey: "toolDefinitions",
+ id: "toolDefinitions",
+ header: "Available Tools",
+ size: 120,
+ enableHiding: true,
+ enableSorting: true,
+ defaultHidden: true,
+ cell: ({ row }) => {
+ const value: number | undefined = row.getValue("toolDefinitions");
+ return value !== undefined ? (
+ <span>{numberFormatter(value, 0)}</span>
+ ) : undefined;
+ },
+ },
+ {
+ accessorKey: "toolCalls",
+ id: "toolCalls",
+ header: "Tool Calls",
+ size: 100,
+ enableHiding: true,
+ enableSorting: true,
+ defaultHidden: true,
+ cell: ({ row }) => {
+ const value: number | undefined = row.getValue("toolCalls");
+ return value !== undefined ? (
+ <span>{numberFormatter(value, 0)}</span>
+ ) : undefined;
+ },
+ },
{
accessorKey: "timeToFirstToken",
id: "timeToFirstToken",
@@ -1156,6 +1198,8 @@ export default function ObservationsTable({
costDetails: generation.costDetails ?? {},
usagePricingTierName: generation.usagePricingTierName ?? undefined,
environment: generation.environment ?? undefined,
+ toolDefinitions: generation.toolDefinitionsCount ?? undefined,
+ toolCalls: generation.toolCallsCount ?? undefined,
};
})
: [];
diff --git a/web/src/components/trace2/lib/tree-building.clienttest.ts b/web/src/components/trace2/lib/tree-building.clienttest.ts
index 3a9df5e77e..749bbde46b 100644
--- a/web/src/components/trace2/lib/tree-building.clienttest.ts
+++ b/web/src/components/trace2/lib/tree-building.clienttest.ts
@@ -46,6 +46,9 @@ const createMockObservation = (
latency: null,
usagePricingTierId: null,
usagePricingTierName: null,
+ toolDefinitions: null,
+ toolCalls: null,
+ toolCallNames: null,
...overrides,
});
diff --git a/web/src/features/filters/config/observations-config.ts b/web/src/features/filters/config/observations-config.ts
index c9f8c0aba9..331cf964f5 100644
--- a/web/src/features/filters/config/observations-config.ts
+++ b/web/src/features/filters/config/observations-config.ts
@@ -134,6 +134,30 @@ export const observationFilterConfig: FilterConfig = {
max: 100,
unit: "$",
},
+ {
+ type: "categorical" as const,
+ column: "toolNames",
+ label: "Available Tool Names",
+ },
+ {
+ type: "categorical" as const,
+ column: "calledToolNames",
+ label: "Called Tool Names",
+ },
+ {
+ type: "numeric" as const,
+ column: "toolDefinitions",
+ label: "Available Tools",
+ min: 0,
+ max: 25,
+ },
+ {
+ type: "numeric" as const,
+ column: "toolCalls",
+ label: "Tool Calls",
+ min: 0,
+ max: 25,
+ },
{
type: "keyValue" as const,
column: "score_categories",
diff --git a/web/src/features/public-api/types/observations.ts b/web/src/features/public-api/types/observations.ts
index e95bacfb3d..74ed1288a2 100644
--- a/web/src/features/public-api/types/observations.ts
+++ b/web/src/features/public-api/types/observations.ts
@@ -147,6 +147,13 @@ export const transformDbToApiObservation = (
userId,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
sessionId,
+ // Exclude tool data from public API (not yet released)
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ toolDefinitions,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ toolCalls,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ toolCallNames,
...rest
} = observation as EventsObservation & ObservationPriceFields;
diff --git a/web/src/features/query/dashboardUiTableToViewMapping.ts b/web/src/features/query/dashboardUiTableToViewMapping.ts
index 7fa1a8d85e..9918e646fd 100644
--- a/web/src/features/query/dashboardUiTableToViewMapping.ts
+++ b/web/src/features/query/dashboardUiTableToViewMapping.ts
@@ -86,6 +86,10 @@ const viewMappings: Record<z.infer<typeof views>, Record<string, string>[]> = {
uiTableName: "Model",
viewName: "providedModelName",
},
+ {
+ uiTableName: "Tool Names",
+ viewName: "toolNames",
+ },
{
uiTableName: "Environment",
viewName: "environment",
diff --git a/web/src/features/query/dataModel.ts b/web/src/features/query/dataModel.ts
index ad060fc829..adc7b93684 100644
--- a/web/src/features/query/dataModel.ts
+++ b/web/src/features/query/dataModel.ts
@@ -429,6 +429,18 @@ export const observationsView: ViewDeclarationType = {
type: "string",
description: "Month of the observation start_time in YYYY-MM format.",
},
+ toolNames: {
+ sql: "mapKeys(observations.tool_definitions)",
+ alias: "toolNames",
+ type: "arrayString",
+ description: "Names of available tools defined for the observation.",
+ },
+ calledToolNames: {
+ sql: "observations.tool_call_names",
+ alias: "calledToolNames",
+ type: "arrayString",
+ description: "Names of tools that were called by the observation.",
+ },
},
measures: {
count: {
@@ -544,6 +556,22 @@ export const observationsView: ViewDeclarationType = {
description: "Unique scores attached to the observation.",
unit: "scores",
},
+ toolDefinitions: {
+ sql: "nullIf(length(mapKeys(@@AGG1@@(tool_definitions))), 0)",
+ aggs: { agg1: "any" },
+ alias: "toolDefinitions",
+ type: "integer",
+ description: "Number of available tools per observation.",
+ unit: "tools",
+ },
+ toolCalls: {
+ sql: "nullIf(length(@@AGG1@@(tool_calls)), 0)",
+ aggs: { agg1: "any" },
+ alias: "toolCalls",
+ type: "integer",
+ description: "Number of tool calls per observation.",
+ unit: "calls",
+ },
},
tableRelations: {
traces: {
@@ -1056,6 +1084,18 @@ export const eventsObservationsView: ViewDeclarationType = {
type: "string",
description: "Month of the observation start_time in YYYY-MM format.",
},
+ toolNames: {
+ sql: "mapKeys(events_observations.tool_definitions)",
+ alias: "toolNames",
+ type: "arrayString",
+ description: "Names of available tools defined for the observation.",
+ },
+ calledToolNames: {
+ sql: "events_observations.tool_call_names",
+ alias: "calledToolNames",
+ type: "arrayString",
+ description: "Names of tools that were called by the observation.",
+ },
},
measures: {
count: {
@@ -1166,6 +1206,22 @@ export const eventsObservationsView: ViewDeclarationType = {
description: "Unique scores attached to the observation.",
unit: "scores",
},
+ toolDefinitions: {
+ sql: "nullIf(length(mapKeys(@@AGG1@@(events_observations.tool_definitions))), 0)",
+ aggs: { agg1: "any" },
+ alias: "toolDefinitions",
+ type: "integer",
+ description: "Number of available tools per observation.",
+ unit: "tools",
+ },
+ toolCalls: {
+ sql: "nullIf(length(@@AGG1@@(events_observations.tool_calls)), 0)",
+ aggs: { agg1: "any" },
+ alias: "toolCalls",
+ type: "integer",
+ description: "Number of tool calls per observation.",
+ unit: "calls",
+ },
},
tableRelations: {
// No traces relation - userId, sessionId, tags are denormalized on events table
diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsx
index c57a665700..b73b48849d 100644
--- a/web/src/features/widgets/components/WidgetForm.tsx
+++ b/web/src/features/widgets/components/WidgetForm.tsx
@@ -465,6 +465,7 @@ export function WidgetForm({
const nameOptions = traceFilterOptions.data?.name || [];
const tagsOptions = traceFilterOptions.data?.tags || [];
const modelOptions = generationsFilterOptions.data?.model || [];
+ const toolNamesOptions = generationsFilterOptions.data?.toolNames || [];
// Filter columns for PopoverFilterBuilder
const filterColumns: ColumnDefinition[] = [
@@ -501,6 +502,13 @@ export function WidgetForm({
options: tagsOptions,
internal: "internalValue",
},
+ {
+ name: "Tool Names",
+ id: "toolNames",
+ type: "arrayOptions",
+ options: toolNamesOptions,
+ internal: "internalValue",
+ },
{
name: "User",
id: "user",
diff --git a/web/src/server/api/routers/generations/filterOptionsQuery.ts b/web/src/server/api/routers/generations/filterOptionsQuery.ts
index 206231b25b..8ba320f32a 100644
--- a/web/src/server/api/routers/generations/filterOptionsQuery.ts
+++ b/web/src/server/api/routers/generations/filterOptionsQuery.ts
@@ -8,6 +8,8 @@ import {
getObservationsGroupedByModelId,
getObservationsGroupedByName,
getObservationsGroupedByPromptName,
+ getObservationsGroupedByToolName,
+ getObservationsGroupedByCalledToolName,
getNumericScoresGroupedByName,
getTracesGroupedByName,
getTracesGroupedByTags,
@@ -65,6 +67,8 @@ export const filterOptionsQuery = protectedProjectProcedure
traceNames,
tags,
modelId,
+ toolNames,
+ calledToolNames,
] = await Promise.all([
// numeric scores
getNumericScoresGroupedByName(input.projectId, traceTimestampFilters),
@@ -85,6 +89,13 @@ export const filterOptionsQuery = protectedProjectProcedure
getClickhouseTraceTags(),
// modelId
getObservationsGroupedByModelId(input.projectId, startTimeFilter ?? []),
+ // available tool names (from tool_definitions)
+ getObservationsGroupedByToolName(input.projectId, startTimeFilter ?? []),
+ // called tool names (from tool_call_names)
+ getObservationsGroupedByCalledToolName(
+ input.projectId,
+ startTimeFilter ?? [],
+ ),
]);
// typecheck filter options, needs to include all columns with options
@@ -117,6 +128,16 @@ export const filterOptionsQuery = protectedProjectProcedure
.map((i) => ({
value: i.tag as string,
})),
+ toolNames: toolNames
+ .filter((i) => i.toolName !== null)
+ .map((i) => ({
+ value: i.toolName as string,
+ })),
+ calledToolNames: calledToolNames
+ .filter((i) => i.calledToolName !== null)
+ .map((i) => ({
+ value: i.calledToolName as string,
+ })),
type: [
"GENERATION",
"SPAN",
diff --git a/web/src/utils/chatml/adapters/aisdk.ts b/web/src/utils/chatml/adapters/aisdk.ts
index 2acfccfdbb..1987322349 100644
--- a/web/src/utils/chatml/adapters/aisdk.ts
+++ b/web/src/utils/chatml/adapters/aisdk.ts
@@ -1,495 +1 @@
-import type { NormalizerContext, ProviderAdapter } from "../types";
-import {
- removeNullFields,
- stringifyToolResultContent,
- parseMetadata,
- isRichToolResult,
-} from "../helpers";
-import { z } from "zod/v4";
-
-/**
- * AI SDK v5 Adapter
- *
- * Handles traces from Vercel AI SDK v5 with any model provider
- *
- * Key characteristics:
- * - Observation names: ai.generateText.doGenerate, ai.generateObject.doGenerate
- * - Metadata: ai.operationId, ai.model.provider, ai.model.id
- * - Message structure: {role, content: [{type, text/toolCallId/...}]}
- * - Tool calls: {type: "tool-call", toolCallId, toolName, input|args}
- * - Tool results: {type: "tool-result", toolCallId, toolName, output|result}
- */
-
-// Message with AI SDK v5 tool-call content structure
-const AISDKToolCallMessageSchema = z.looseObject({
- role: z.string(),
- content: z.array(
- z.looseObject({
- type: z.literal("tool-call"),
- toolCallId: z.string(),
- toolName: z.string(),
- }),
- ),
-});
-
-// Message with AI SDK v5 tool-result content structure
-const AISDKToolResultMessageSchema = z.looseObject({
- role: z.literal("tool"),
- content: z.array(
- z.looseObject({
- type: z.literal("tool-result"),
- toolCallId: z.string(),
- toolName: z.string(),
- }),
- ),
-});
-
-// Message array with AI SDK v5 patterns
-const AISDKMessagesArraySchema = z
- .array(
- z.looseObject({
- role: z.string(),
- content: z
- .union([z.string(), z.array(z.looseObject({ type: z.string() }))])
- .optional(),
- }),
- )
- .refine(
- (messages) => {
- // Must have at least one message with AI SDK v5 structured content
- return messages.some(
- (msg) =>
- Array.isArray(msg.content) &&
- msg.content.some(
- (item: unknown) =>
- (item &&
- typeof item === "object" &&
- "type" in item &&
- (item as Record<string, unknown>).type === "tool-call") ||
- (item as Record<string, unknown>).type === "tool-result",
- ),
- );
- },
- { message: "Must have AI SDK v5 tool-call or tool-result patterns" },
- );
-
-// Array of raw tool call objects, format as seen on OUTPUTs
-// Example: [{toolCallId: "...", toolName: "...", input: {...}}, ...]
-const AISDKRawToolCallArraySchema = z
- .array(
- z.looseObject({
- toolCallId: z.string(),
- toolName: z.string(),
- // Can have either 'input' (OpenAI) or 'args' (Bedrock)
- }),
- )
- .refine((arr) => arr.length > 0, {
- message: "Must have at least one tool call",
- });
-
-// normalize a single AI SDK v5 message to ChatML format
-// we don't want additional fields here to get clean rendering
-function normalizeMessage(msg: unknown): Record<string, unknown> {
- if (!msg || typeof msg !== "object") return {};
-
- let working = msg as Record<string, unknown>;
-
- // Strip provider-specific metadata (Bedrock, OpenAI, etc.)
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- const { providerMetadata, providerOptions, ...withoutProviderFields } =
- working;
- working = withoutProviderFields;
-
- let normalized = removeNullFields(working);
-
- // Normalize content: [{type: "text", text: "..."}] → string
- if (
- normalized.content &&
- Array.isArray(normalized.content) &&
- normalized.content.length > 0
- ) {
- // all text already or do owe need to normalize further?
- const allTextItems = normalized.content.every(
- (item: unknown) =>
- item &&
- typeof item === "object" &&
- (item as Record<string, unknown>).type === "text" &&
- typeof (item as Record<string, unknown>).text === "string",
- );
-
- if (allTextItems && normalized.content.length === 1) {
- // Single text item: extract the text
- const firstItem = normalized.content[0] as Record<string, unknown>;
- normalized.content = firstItem.text;
- } else if (allTextItems && normalized.content.length > 1) {
- // Multiple text items: concatenate
- const texts = normalized.content.map(
- (item: unknown) => (item as Record<string, unknown>).text,
- );
- normalized.content = texts.join("");
- } else {
- // Mixed content or tool-calls/tool-results: normalize each item
- normalized.content = normalized.content.map((item: unknown) => {
- if (!item || typeof item !== "object") return item;
-
- const contentItem = item as Record<string, unknown>;
-
- // Handle tool-call content item
- // {type: "tool-call", toolCallId, toolName, input|args, providerOptions}
- if (contentItem.type === "tool-call") {
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- const { providerOptions: _po, ...cleanedItem } = contentItem;
-
- // Normalize args|input to arguments
- const args = contentItem.args ?? contentItem.input;
- return {
- ...cleanedItem,
- arguments:
- typeof args === "string" ? args : JSON.stringify(args ?? {}),
- };
- }
-
- // Handle tool-result content item
- // {type: "tool-result", toolCallId, toolName, output|result}
- if (contentItem.type === "tool-result") {
- // Normalize output|result to content
- const resultValue = contentItem.output ?? contentItem.result;
-
- // If result has nested {type: "text", value: "..."}, extract value
- if (
- resultValue &&
- typeof resultValue === "object" &&
- !Array.isArray(resultValue) &&
- (resultValue as Record<string, unknown>).type === "text" &&
- "value" in (resultValue as Record<string, unknown>)
- ) {
- return {
- ...contentItem,
- content: (resultValue as Record<string, unknown>).value,
- };
- }
-
- // Otherwise stringify the result
- return {
- ...contentItem,
- content:
- typeof resultValue === "string"
- ? resultValue
- : JSON.stringify(resultValue ?? ""),
- };
- }
-
- return contentItem;
- });
-
- // Convert tool-call content items to tool_calls array
- if (Array.isArray(normalized.content)) {
- const toolCallItems = normalized.content.filter(
- (item: unknown) =>
- item &&
- typeof item === "object" &&
- (item as Record<string, unknown>).type === "tool-call",
- );
-
- if (toolCallItems.length > 0) {
- normalized.tool_calls = toolCallItems.map((item: unknown) => {
- const tc = item as Record<string, unknown>;
- return {
- id: tc.toolCallId,
- name: tc.toolName,
- arguments: tc.arguments,
- type: "function",
- };
- });
-
- // Remove tool-call items from content, keep only text items
- const textItems = normalized.content.filter(
- (item: unknown) =>
- item &&
- typeof item === "object" &&
- (item as Record<string, unknown>).type === "text",
- );
-
- if (textItems.length > 0) {
- const texts = textItems.map(
- (item: unknown) => (item as Record<string, unknown>).text ?? "",
- );
- normalized.content = texts.join("");
- } else {
- // No text content, remove content field
- delete normalized.content;
- }
- }
- }
-
- // Handle tool-result content items for tool role messages
- // Only process if content is still an array (wasn't converted to string above)
- if (Array.isArray(normalized.content)) {
- const toolResultItems = normalized.content.filter(
- (item: unknown) =>
- item &&
- typeof item === "object" &&
- (item as Record<string, unknown>).type === "tool-result",
- );
-
- if (toolResultItems.length > 0 && normalized.role === "tool") {
- // For single tool result, extract tool_call_id and content
- if (toolResultItems.length === 1) {
- const result = toolResultItems[0] as Record<string, unknown>;
- normalized.tool_call_id = result.toolCallId;
- normalized.content = result.content;
- } else {
- // Multiple tool results: keep as array (less common)
- normalized.content = toolResultItems;
- }
- }
- }
- }
- }
-
- // For tool messages with rich object content, spread into message
- // so it goes to json passthrough field and renders as PrettyJsonView.
- // Rich = nested structure OR 3+ keys. Simple <=2 scalar keys.
- if (
- normalized.role === "tool" &&
- typeof normalized.content === "object" &&
- normalized.content !== null &&
- !Array.isArray(normalized.content)
- ) {
- if (isRichToolResult(normalized.content)) {
- // Rich object: spread for table rendering
- const { content, ...rest } = normalized;
- return { ...rest, ...content };
- } else {
- // Simple object: stringify for text rendering
- normalized.content = stringifyToolResultContent(normalized.content);
- }
- }
-
- return normalized;
-}
-
-function flattenToolDefinition(tool: unknown): Record<string, unknown> {
- // handle stringified tools (e.g. from metadata.tools with bedrock)
- if (typeof tool === "string") {
- try {
- tool = JSON.parse(tool);
- } catch {
- return {};
- }
- }
-
- if (typeof tool !== "object" || !tool) return {};
-
- const t = tool as Record<string, unknown>;
-
- const toolDef: Record<string, unknown> = {
- name: t.name,
- description: t.description ?? "",
- };
-
- // AI SDK uses inputSchema instead of parameters
- if (t.inputSchema != null) {
- toolDef.parameters = t.inputSchema;
- } else if (t.parameters != null) {
- toolDef.parameters = t.parameters;
- }
-
- return toolDef;
-}
-
-/**
- * Split tool result messages with multiple results into separate messages
- * AI SDK can have: {role: "tool", content: [{type: "tool-result", ...}, {type: "tool-result", ...}]}
- * ChatML expects: [{role: "tool", tool_call_id: "...", content: "..."}, ...]
- */
-function splitToolResultMessages(messages: unknown[]): unknown[] {
- const result: unknown[] = [];
-
- for (const msg of messages) {
- if (!msg || typeof msg !== "object") {
- result.push(msg);
- continue;
- }
-
- const message = msg as Record<string, unknown>;
-
- // Check if this is a tool message with array content containing multiple tool-result items
- if (
- message.role === "tool" &&
- Array.isArray(message.content) &&
- message.content.length > 1 &&
- message.content.every(
- (item: unknown) =>
- item &&
- typeof item === "object" &&
- (item as Record<string, unknown>).type === "tool-result",
- )
- ) {
- // Split into separate messages, one per tool result
- for (const item of message.content) {
- const toolResult = item as Record<string, unknown>;
- result.push({
- role: "tool",
- tool_call_id: toolResult.toolCallId,
- content: toolResult.content,
- });
- }
- } else {
- result.push(message);
- }
- }
-
- return result;
-}
-
-function preprocessData(data: unknown, ctx?: NormalizerContext): unknown {
- if (!data) return data;
-
- // Extract tools from context metadata (observation.metadata.tools)
- let toolsFromContext: unknown[] | undefined;
- if (ctx?.metadata && typeof ctx.metadata === "object") {
- const meta = ctx.metadata as Record<string, unknown>;
- if (Array.isArray(meta.tools)) {
- toolsFromContext = meta.tools.map(flattenToolDefinition);
- }
- }
-
- // Handle wrapped format with messages and tools
- // {messages: [...], tools: [...]} or {messages: [...], providerOptions: {...}}
- if (typeof data === "object" && !Array.isArray(data) && "messages" in data) {
- const obj = data as Record<string, unknown>;
- const messagesArray = obj.messages as unknown[];
-
- if (Array.isArray(messagesArray)) {
- let tools: unknown[] | undefined;
-
- if (Array.isArray(obj.tools)) {
- tools = (obj.tools as unknown[]).map(flattenToolDefinition);
- }
-
- const normalized = messagesArray.map(normalizeMessage);
-
- const split = splitToolResultMessages(normalized);
-
- // Attach tools to messages if present
- if (tools && tools.length > 0) {
- return split.map((msg) => ({
- ...(msg as Record<string, unknown>),
- tools,
- }));
- }
-
- return split;
- }
- }
-
- if (Array.isArray(data)) {
- // is an array of raw tool call objects?
- // Example: [{toolCallId: "...", toolName: "...", input: {...}}, ...]
- const rawToolCallArrayResult = AISDKRawToolCallArraySchema.safeParse(data);
-
- if (rawToolCallArrayResult.success) {
- // Convert raw tool calls into a single assistant message with tool_calls
- const toolCalls = data.map((item) => {
- const tc = item as Record<string, unknown>;
- const args = tc.args ?? tc.input;
-
- return {
- id: tc.toolCallId,
- name: tc.toolName,
- arguments:
- typeof args === "string" ? args : JSON.stringify(args ?? {}),
- type: "function",
- };
- });
-
- const assistantMessage: Record<string, unknown> = {
- role: "assistant",
- content: "",
- tool_calls: toolCalls,
- };
-
- // Attach tools from context if available
- if (toolsFromContext && toolsFromContext.length > 0) {
- assistantMessage.tools = toolsFromContext;
- }
-
- return [assistantMessage];
- }
-
- // otherwise it's an array of messages
- const normalized = data.map(normalizeMessage);
- const split = splitToolResultMessages(normalized);
-
- // Attach tools from context metadata if present
- if (toolsFromContext && toolsFromContext.length > 0) {
- return split.map((msg) => ({
- ...(msg as Record<string, unknown>),
- tools: toolsFromContext,
- }));
- }
-
- return split;
- }
-
- // if it's not an array but just a single message
- if (typeof data === "object" && "role" in data) {
- return normalizeMessage(data);
- }
-
- return data;
-}
-
-export const aisdkAdapter: ProviderAdapter = {
- id: "aisdk",
-
- detect(ctx: NormalizerContext): boolean {
- const meta = parseMetadata(ctx.metadata);
-
- // EXPLICIT: Framework hint
- if (ctx.framework === "aisdk" || ctx.framework === "aisdk-v5") return true;
-
- // STRONG INDICATORS: AI SDK v5 telemetry markers
- if (meta && typeof meta === "object") {
- if ("scope" in meta && typeof meta.scope === "object") {
- const scope = meta.scope as Record<string, unknown>;
- if (scope.name === "ai") return true;
- }
-
- if ("attributes" in meta && typeof meta.attributes === "object") {
- const attrs = meta.attributes as Record<string, unknown> | null;
- if (
- attrs &&
- typeof attrs["operation.name"] === "string" &&
- attrs["operation.name"].startsWith("ai.")
- ) {
- return true;
- }
- }
- }
-
- // STRUCTURAL: Schema-based detection (for edge cases without metadata)
- if (AISDKToolCallMessageSchema.safeParse(ctx.metadata).success) return true;
- if (AISDKToolResultMessageSchema.safeParse(ctx.metadata).success)
- return true;
- if (AISDKMessagesArraySchema.safeParse(ctx.metadata).success) return true;
-
- if (AISDKToolCallMessageSchema.safeParse(ctx.data).success) return true;
- if (AISDKToolResultMessageSchema.safeParse(ctx.data).success) return true;
- if (AISDKMessagesArraySchema.safeParse(ctx.data).success) return true;
-
- // Raw tool call array detection (OUTPUT format)
- if (AISDKRawToolCallArraySchema.safeParse(ctx.data).success) return true;
-
- return false;
- },
-
- preprocess(
- data: unknown,
- _kind: "input" | "output",
- ctx: NormalizerContext,
- ): unknown {
- return preprocessData(data, ctx);
- },
-};
+export { aisdkAdapter } from "@langfuse/shared";
diff --git a/web/src/utils/chatml/adapters/gemini.ts b/web/src/utils/chatml/adapters/gemini.ts
index abba207a3b..11437c9c2b 100644
--- a/web/src/utils/chatml/adapters/gemini.ts
+++ b/web/src/utils/chatml/adapters/gemini.ts
@@ -1,467 +1 @@
-import type { NormalizerContext, ProviderAdapter } from "../types";
-import {
- parseMetadata,
- stringifyToolResultContent,
- isRichToolResult,
-} from "../helpers";
-import { z } from "zod/v4";
-
-/**
- * Detection schemas for Gemini/VertexAI formats
- *
- * Two main format families (inner structure is identical):
- * 1. Raw Gemini API (Vertex): {candidates: [{content: {parts, role}}]}
- * 2. Google ADK: {content: {parts, role}} or {config, contents: [{parts, role}]}
- */
-
-// Raw Gemini API response: {candidates: [{content: {...}}]}
-const GeminiRawAPISchema = z.looseObject({
- candidates: z.array(
- z.looseObject({
- content: z.looseObject({
- parts: z.array(z.any()).optional(),
- role: z.string().optional(),
- }),
- }),
- ),
-});
-
-// ADK output format: {content: {parts: [...], role: "..."}}
-const GeminiADKOutputSchema = z.looseObject({
- content: z.looseObject({
- parts: z.array(z.any()),
- role: z.string(),
- }),
-});
-
-// ADK input format: {config: {tools, system_instruction}, contents: [...]}
-const GeminiADKInputSchema = z.looseObject({
- config: z.looseObject({
- tools: z.array(z.any()).optional(),
- system_instruction: z.string().optional(),
- }),
- contents: z.array(z.any()),
-});
-
-// Simple request format: {contents: [{parts: [...], role: "..."}]}
-const GeminiRequestSchema = z.looseObject({
- contents: z.array(
- z.looseObject({
- parts: z.array(z.any()),
- role: z.string().optional(),
- }),
- ),
-});
-
-/**
- * Case-insensitive field accessor
- * Handles both snake_case and camelCase (e.g., function_call OR functionCall)
- */
-function getField(obj: unknown, snakeName: string, camelName: string): unknown {
- if (!obj || typeof obj !== "object") return undefined;
- const o = obj as Record<string, unknown>;
- return o[snakeName] ?? o[camelName];
-}
-
-// Note: Gemini tools come from config.tools with function_declarations, not from messages
-// The format {role: "tool", content: {type: "function"}} is LangGraph, handled by langgraph adapter
-
-/**
- * Extract both tool calls and text from parts array
- * Handles: function_call/functionCall, text, function_response/functionResponse
- * snake_case is from python SDK while camelCase is from JavaScript SDK / REST
- */
-function extractFromParts(parts: unknown[]): {
- toolCalls: Array<Record<string, unknown>>;
- text: string;
-} {
- const toolCalls: Array<Record<string, unknown>> = [];
- const textParts: string[] = [];
-
- for (const part of parts) {
- if (typeof part === "string") {
- textParts.push(part);
- continue;
- }
- if (!part || typeof part !== "object") continue;
-
- const p = part as Record<string, unknown>;
-
- // Check for function_call OR functionCall (case-insensitive)
- const fc = getField(p, "function_call", "functionCall");
- if (fc && typeof fc === "object") {
- const functionCall = fc as Record<string, unknown>;
- toolCalls.push({
- id: functionCall.id || "",
- name: functionCall.name,
- arguments:
- typeof functionCall.args === "string"
- ? functionCall.args
- : JSON.stringify(functionCall.args ?? {}),
- type: "function",
- });
- continue;
- }
-
- // {text: "..."} or {type: "text", text: "..."}
- // text can be a string (normal response) or an object (when responseMimeType: "application/json")
- if (p.text !== undefined && p.text !== null) {
- textParts.push(
- typeof p.text === "string" ? p.text : JSON.stringify(p.text, null, 2),
- );
- continue;
- }
-
- // {function_response: {name, response}} OR {functionResponse: {name, response}}
- const fr = getField(p, "function_response", "functionResponse");
- if (fr && typeof fr === "object") {
- const functionResponse = fr as Record<string, unknown>;
- textParts.push(JSON.stringify(functionResponse.response || {}));
- }
- }
-
- return {
- toolCalls,
- text: textParts.join(""),
- };
-}
-
-/**
- * Extract tool declarations from Google ADK tools array
- * Handles: {function_declarations: [{name, description, parameters}]}
- */
-function extractToolDeclarations(tools: unknown[]): Array<{
- name: string;
- description?: string;
- parameters?: Record<string, unknown>;
-}> {
- const declarations: Array<{
- name: string;
- description?: string;
- parameters?: Record<string, unknown>;
- }> = [];
-
- for (const tool of tools) {
- if (!tool || typeof tool !== "object") continue;
- const t = tool as Record<string, unknown>;
-
- // Check for function_declarations OR functionDeclarations
- const fd = getField(t, "function_declarations", "functionDeclarations");
- if (fd && Array.isArray(fd)) {
- for (const decl of fd as Array<Record<string, unknown>>) {
- const toolDef: Record<string, unknown> = {
- name: (decl.name as string) || "",
- };
- if (decl.description !== null && decl.description !== undefined) {
- toolDef.description = decl.description;
- }
- if (decl.parameters !== null && decl.parameters !== undefined) {
- toolDef.parameters = decl.parameters;
- }
- declarations.push(
- toolDef as {
- name: string;
- description?: string;
- parameters?: Record<string, unknown>;
- },
- );
- }
- }
- }
-
- return declarations;
-}
-
-// normalize a single Gemini message to ChatML format
-function normalizeGeminiMessage(msg: unknown): Record<string, unknown> {
- if (!msg || typeof msg !== "object") return {};
-
- const message = msg as Record<string, unknown>;
- let normalized = { ...message };
-
- // convert Gemini "model" role → "assistant"
- // if (message.role === "model") {
- // normalized.role = "assistant";
- // }
-
- // handle direct tool call message format
- // {type: "tool_call", name: "...", args: {...}} → {role: "assistant", tool_calls: [...]}
- if (
- normalized.type === "tool_call" &&
- normalized.name &&
- typeof normalized.name === "string"
- ) {
- const toolCall: Record<string, unknown> = {
- id: normalized.id || "",
- name: normalized.name,
- arguments:
- typeof normalized.args === "string"
- ? normalized.args
- : JSON.stringify(normalized.args ?? {}),
- type: "function",
- };
-
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- const { type: _type, name: _name, args: _args, ...rest } = normalized;
- normalized = {
- ...rest,
- role: rest.role || "assistant",
- tool_calls: [toolCall],
- };
- }
-
- // normalize existing tool_calls array
- if (normalized.tool_calls && Array.isArray(normalized.tool_calls)) {
- normalized.tool_calls = normalized.tool_calls.map((tc) => {
- if (!tc || typeof tc !== "object") return {};
- const toolCall = tc as Record<string, unknown>;
-
- // Convert Gemini format {type: "tool_call", name, args} → flat format
- if (toolCall.type === "tool_call" && "args" in toolCall) {
- return {
- id: toolCall.id || "",
- name: toolCall.name,
- arguments:
- typeof toolCall.args === "string"
- ? toolCall.args
- : JSON.stringify(toolCall.args ?? {}),
- type: "function",
- };
- }
-
- return toolCall;
- });
- }
-
- // process top-level parts array
- // Gemini format: {parts: [{function_call/text/function_response}], role: "..."}
- if (normalized.parts && Array.isArray(normalized.parts)) {
- const { toolCalls, text } = extractFromParts(normalized.parts);
- if (toolCalls.length > 0) {
- normalized.tool_calls = toolCalls;
- }
- if (text) {
- normalized.content = text;
- // Remove parts to avoid showing in passthrough
- delete normalized.parts;
- }
- }
-
- // process nested content.parts[]
- // Gemini format: {content: {parts: [{function_call: {...}}], role: "model"}}
- if (
- normalized.content &&
- typeof normalized.content === "object" &&
- !Array.isArray(normalized.content) &&
- "parts" in normalized.content
- ) {
- const content = normalized.content as Record<string, unknown>;
- if (Array.isArray(content.parts)) {
- const { toolCalls } = extractFromParts(content.parts);
- if (toolCalls.length > 0) {
- normalized.tool_calls = toolCalls;
- }
-
- // Extract role if nested
- if (content.role && typeof content.role === "string") {
- normalized.role = content.role;
- }
- }
- }
-
- // process content as array (structured content format)
- // Gemini format: {content: [{type: "text", text: "..."}]}
- if (Array.isArray(normalized.content)) {
- const { text } = extractFromParts(normalized.content);
- if (text) {
- normalized.content = text;
- }
- }
-
- // For tool messages with rich object content, spread into message
- // so it goes to json passthrough field and renders as PrettyJsonView.
- // Rich = nested structure OR 3+ keys. Simple <=2 scalar keys.
- if (
- normalized.role === "tool" &&
- typeof normalized.content === "object" &&
- normalized.content !== null &&
- !Array.isArray(normalized.content)
- ) {
- if (isRichToolResult(normalized.content)) {
- // Rich object: spread for table rendering
- const { content, ...rest } = normalized;
- return { ...rest, ...content };
- } else {
- // Simple object: stringify for text rendering
- normalized.content = stringifyToolResultContent(normalized.content);
- }
- }
-
- return normalized;
-}
-
-// normalize messages
-function normalizeMessages(data: unknown[]): unknown[] {
- return data.map(normalizeGeminiMessage);
-}
-
-// unwrap outer wrappers first then normalize inner structure
-function preprocessData(data: unknown): unknown {
- if (!data) return data;
-
- // ========================================
- // STEP 1: Unwrap Raw Gemini API format
- // ========================================
- // {candidates: [{content: {parts, role}}]} → {parts, role, ...otherFields}
- if (GeminiRawAPISchema.safeParse(data).success) {
- const obj = data as Record<string, unknown>;
- const candidates = obj.candidates as Array<Record<string, unknown>>;
- if (candidates[0]?.content) {
- // Unwrap: merge first candidate's content with other top-level fields
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- const { candidates: _candidates, ...otherFields } = obj;
- return normalizeGeminiMessage({
- ...candidates[0].content,
- ...otherFields,
- });
- }
- }
-
- // ========================================
- // STEP 2: Unwrap ADK output format
- // ========================================
- // {content: {parts, role}, finish_reason: "..."} → {parts, role, finish_reason: "..."}
- if (GeminiADKOutputSchema.safeParse(data).success) {
- const obj = data as Record<string, unknown>;
- const content = obj.content as Record<string, unknown>;
- if ("parts" in content && Array.isArray(content.parts)) {
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- const { content: _content, ...otherFields } = obj;
- return normalizeGeminiMessage({ ...content, ...otherFields });
- }
- }
-
- // ========================================
- // STEP 3: Handle ADK input format
- // ========================================
- // {config: {tools, system_instruction}, contents: [...]}
- if (GeminiADKInputSchema.safeParse(data).success) {
- const obj = data as Record<string, unknown>;
- const config = obj.config as Record<string, unknown> | undefined;
- const contents = obj.contents;
-
- if (config && Array.isArray(contents)) {
- const messages: unknown[] = [];
-
- // Extract system_instruction from config and prepend as system message
- const systemInstruction = getField(
- config,
- "system_instruction",
- "systemInstruction",
- );
- if (systemInstruction && typeof systemInstruction === "string") {
- messages.push({
- role: "system",
- content: systemInstruction,
- });
- }
-
- messages.push(...contents);
-
- // Extract and attach tools if present
- if ("tools" in config && Array.isArray(config.tools)) {
- const extractedTools = extractToolDeclarations(config.tools);
-
- if (extractedTools.length > 0) {
- return normalizeMessages(messages).map((msg) => ({
- ...(msg as Record<string, unknown>),
- tools: extractedTools,
- }));
- }
- }
-
- // No tools, just normalize messages
- return normalizeMessages(messages);
- }
- }
-
- // ========================================
- // STEP 4: Handle simple request format
- // ========================================
- // {contents: [{parts, role}], model: "..."}
- if (GeminiRequestSchema.safeParse(data).success) {
- const obj = data as Record<string, unknown>;
- return normalizeMessages(obj.contents as unknown[]);
- }
-
- // ========================================
- // STEP 5: Handle arrays
- // ========================================
- if (Array.isArray(data)) {
- return normalizeMessages(data);
- }
-
- // ========================================
- // STEP 6: Handle messages wrapper
- // ========================================
- if (typeof data === "object" && "messages" in data) {
- const obj = data as Record<string, unknown>;
- return {
- ...obj,
- messages: Array.isArray(obj.messages)
- ? normalizeMessages(obj.messages)
- : obj.messages,
- };
- }
-
- return data;
-}
-
-export const geminiAdapter: ProviderAdapter = {
- id: "gemini",
-
- detect(ctx: NormalizerContext): boolean {
- const meta = parseMetadata(ctx.metadata);
-
- // HINTS: Fast checks for explicit Gemini indicators
- if (ctx.framework === "gemini") return true;
- if (ctx.observationName?.toLowerCase().includes("gemini")) return true;
- if (ctx.observationName?.toLowerCase().includes("vertex")) return true;
- if (meta?.ls_provider === "google_vertexai") return true;
-
- // Metadata attributes check
- if (meta && typeof meta === "object" && "attributes" in meta) {
- const attributes = (meta as Record<string, unknown>).attributes;
- if (
- attributes &&
- typeof attributes === "object" &&
- (attributes as Record<string, unknown>)["gen_ai.system"] ===
- "gcp.vertex.agent"
- ) {
- return true;
- }
- }
-
- // STRUCTURAL: Schema-based detection on metadata (check metadata first for performance)
- if (GeminiRequestSchema.safeParse(ctx.metadata).success) return true;
- if (GeminiADKInputSchema.safeParse(ctx.metadata).success) return true;
- if (GeminiRawAPISchema.safeParse(ctx.metadata).success) return true;
- if (GeminiADKOutputSchema.safeParse(ctx.metadata).success) return true;
-
- // Schema-based detection on data (slower, do last)
- if (GeminiRequestSchema.safeParse(ctx.data).success) return true;
- if (GeminiADKInputSchema.safeParse(ctx.data).success) return true;
- if (GeminiRawAPISchema.safeParse(ctx.data).success) return true;
- if (GeminiADKOutputSchema.safeParse(ctx.data).success) return true;
-
- return false;
- },
-
- preprocess(
- data: unknown,
- _kind: "input" | "output",
- _ctx: NormalizerContext,
- ): unknown {
- return preprocessData(data);
- },
-};
+export { geminiAdapter } from "@langfuse/shared";
diff --git a/web/src/utils/chatml/adapters/generic.ts b/web/src/utils/chatml/adapters/generic.ts
index 5a45536864..d17864b59a 100644
--- a/web/src/utils/chatml/adapters/generic.ts
+++ b/web/src/utils/chatml/adapters/generic.ts
@@ -1,150 +1 @@
-import type { NormalizerContext, ProviderAdapter } from "../types";
-
-function normalizeGoogleMessage(msg: unknown): Record<string, unknown> {
- if (!msg || typeof msg !== "object") return {};
-
- const message = msg as Record<string, unknown>;
- let normalized = { ...message };
-
- // Google/Gemini: "model" role → "assistant"
- if (message.role === "model") {
- normalized.role = "assistant";
- }
-
- // Google/Gemini/Microsoft Agent: "parts" field → "content" field
- if (message.parts && Array.isArray(message.parts)) {
- // Check if parts contain function_call, function_response, or Microsoft Agent tool calls
- const hasFunctionCall = message.parts.some((p: unknown) => {
- // Null guard: ensure p exists and is an object before accessing properties
- if (!p || typeof p !== "object") {
- return false;
- }
- const part = p as Record<string, unknown>;
- return part.function_call || part.type === "tool_call";
- });
- const hasFunctionResponse = message.parts.some((p: unknown) => {
- // Null guard: ensure p exists and is an object before accessing properties
- if (!p || typeof p !== "object") {
- return false;
- }
- const part = p as Record<string, unknown>;
- return part.function_response || part.type === "tool_call_response";
- });
-
- if (hasFunctionCall || hasFunctionResponse) {
- // Keep parts as structured content array
- normalized.content = message.parts;
- } else {
- // Extract text from parts
- const content = message.parts
- .map((part: unknown) => {
- if (typeof part === "object" && part !== null) {
- const p = part as Record<string, unknown>;
- // Support both Google's "text" and Microsoft's "content" fields
- if (p.text) {
- return p.text;
- }
- if (p.content && typeof p.content === "string") {
- return p.content;
- }
- }
- // Only stringify if it's actually a simple value, not an object
- if (typeof part === "string" || typeof part === "number") {
- return String(part);
- }
- return "";
- })
- .filter((text: unknown) => text !== "")
- .join("");
- normalized.content = content;
- }
- delete normalized.parts;
- }
-
- return normalized;
-}
-
-function preprocessData(data: unknown): unknown {
- if (!data) return data;
-
- // Handle Google output format: {candidates: [{content: {parts, role}}]}
- if (
- typeof data === "object" &&
- "candidates" in data &&
- Array.isArray((data as Record<string, unknown>).candidates)
- ) {
- const obj = data as Record<string, unknown>;
- const candidate = (obj.candidates as Record<string, unknown>[])[0];
- if (candidate?.content) {
- return normalizeGoogleMessage(candidate.content);
- }
- }
-
- // Handle Google input format: {model: "...", contents: [...]} or {contents: "string"}
- if (typeof data === "object" && "contents" in data && !("messages" in data)) {
- const obj = data as Record<string, unknown>;
- const contents = obj.contents;
- const messages: Record<string, unknown>[] = [];
-
- // Handle system_instruction if present
- const config = obj.config as Record<string, unknown> | undefined;
- if (config?.system_instruction) {
- messages.push({
- role: "system",
- content: config.system_instruction,
- });
- }
-
- // Convert contents to ChatML format
- if (typeof contents === "string") {
- messages.push({ role: "user", content: contents });
- } else if (Array.isArray(contents)) {
- messages.push(...contents.map(normalizeGoogleMessage));
- }
-
- return messages.length > 0 ? messages : data;
- }
-
- // Array of messages
- if (Array.isArray(data)) {
- // Handle nested array format: [[ChatML...]]
- if (data.length === 1 && Array.isArray(data[0])) {
- return data[0].map(normalizeGoogleMessage);
- }
- return data.map(normalizeGoogleMessage);
- }
-
- // Object with messages key
- if (typeof data === "object" && "messages" in data) {
- const obj = data as Record<string, unknown>;
- return {
- ...obj,
- messages: Array.isArray(obj.messages)
- ? obj.messages.map(normalizeGoogleMessage)
- : obj.messages,
- };
- }
-
- // Single message
- if (typeof data === "object" && ("role" in data || "parts" in data)) {
- return normalizeGoogleMessage(data);
- }
-
- return data;
-}
-
-export const genericAdapter: ProviderAdapter = {
- id: "generic",
-
- detect(_ctx: NormalizerContext): boolean {
- return true; // fallback
- },
-
- preprocess(
- data: unknown,
- _kind: "input" | "output",
- _ctx: NormalizerContext,
- ): unknown {
- return preprocessData(data);
- },
-};
+export { genericAdapter } from "@langfuse/shared";
diff --git a/web/src/utils/chatml/adapters/index.ts b/web/src/utils/chatml/adapters/index.ts
index 81b96b20e7..07600de183 100644
--- a/web/src/utils/chatml/adapters/index.ts
+++ b/web/src/utils/chatml/adapters/index.ts
@@ -1,57 +1,13 @@
-import type { NormalizerContext, ProviderAdapter } from "../types";
-import { mapToChatMl, mapOutputToChatMl } from "../core";
-import { langgraphAdapter } from "./langgraph";
-import { aisdkAdapter } from "./aisdk";
-import { openAIAdapter } from "./openai";
-import { geminiAdapter } from "./gemini";
-import { microsoftAgentAdapter } from "./microsoft-agent";
-import { pydanticAIAdapter } from "./pydantic-ai";
-import { genericAdapter } from "./generic";
-
-const adapters: ProviderAdapter[] = [
- langgraphAdapter, // Must be before openAI (both use langfuse-sdk scope)
- aisdkAdapter, // Vercel AI SDK v5 (for all LLM providers like OpenAI, Bedrock, Anthropic, etc.)
- openAIAdapter, // OpenAI (Chat Completions & Responses API)
- geminiAdapter, // Gemini/VertexAI format
- microsoftAgentAdapter, // Microsoft Agent Framework
- pydanticAIAdapter, // Pydantic AI framework
- // Add more adapters here as needed
- genericAdapter, // Always last (fallback)
-];
-
-function selectAdapter(ctx: NormalizerContext): ProviderAdapter {
- // Explicit override
- if (ctx.framework) {
- const adapter = adapters.find((a) => a.id === ctx.framework);
- if (adapter) return adapter;
- }
-
- // First adapter that matches wins
- for (const adapter of adapters) {
- if (adapter.detect(ctx)) {
- return adapter;
- }
- }
-
- return genericAdapter;
-}
-
-export function normalizeInput(input: unknown, ctx: NormalizerContext = {}) {
- const adapter = selectAdapter({
- ...ctx,
- metadata: ctx.metadata ?? input,
- data: input,
- });
- const preprocessed = adapter.preprocess(input, "input", ctx);
- return mapToChatMl(preprocessed);
-}
-
-export function normalizeOutput(output: unknown, ctx: NormalizerContext = {}) {
- const adapter = selectAdapter({
- ...ctx,
- metadata: ctx.metadata ?? output,
- data: output,
- });
- const preprocessed = adapter.preprocess(output, "output", ctx);
- return mapOutputToChatMl(preprocessed);
-}
+// Re-export everything from shared
+export {
+ selectAdapter,
+ langgraphAdapter,
+ aisdkAdapter,
+ openAIAdapter,
+ geminiAdapter,
+ microsoftAgentAdapter,
+ pydanticAIAdapter,
+ genericAdapter,
+ normalizeInput,
+ normalizeOutput,
+} from "@langfuse/shared";
diff --git a/web/src/utils/chatml/adapters/langgraph.ts b/web/src/utils/chatml/adapters/langgraph.ts
index ec4726b12f..a42349bb5a 100644
--- a/web/src/utils/chatml/adapters/langgraph.ts
+++ b/web/src/utils/chatml/adapters/langgraph.ts
@@ -1,378 +1 @@
-import type { NormalizerContext, ProviderAdapter } from "../types";
-import {
- removeNullFields,
- stringifyToolResultContent,
- parseMetadata,
- isRichToolResult,
-} from "../helpers";
-import { z } from "zod/v4";
-
-// Detection schemas for LangChain/LangGraph formats
-
-// LangChain message with type field (no role)
-const LangChainMessageSchema = z.array(
- z.looseObject({
- type: z.enum(["human", "ai", "tool", "system"]),
- content: z.any(),
- }),
-);
-
-// LangGraph message with additional_kwargs
-const LangGraphMessageSchema = z
- .array(
- z.looseObject({
- role: z.string().optional(),
- additional_kwargs: z
- .looseObject({
- tool_calls: z.array(z.any()).optional(),
- })
- .optional(),
- }),
- )
- .refine(
- (data) => {
- // Reject if any message has top-level parts (Microsoft Agent/Gemini format)
- return !data.some(
- (msg) =>
- typeof msg === "object" &&
- msg !== null &&
- "parts" in msg &&
- Array.isArray((msg as Record<string, unknown>).parts),
- );
- },
- { message: "Messages with top-level parts are not LangGraph format" },
- );
-
-// Wrapped messages format
-const LangGraphWrappedSchema = z.looseObject({
- messages: z.array(z.any()),
-});
-
-/**
- * Detect if a message is a tool definition (not a tool result)
- * LangGraph format: {role: "tool", content: {type: "function", function: {...}}}
- * Tool results have tool_call_id, tool definitions do not
- */
-function isLangGraphToolDefinition(msg: unknown): boolean {
- if (!msg || typeof msg !== "object") return false;
-
- const message = msg as Record<string, unknown>;
-
- return (
- message.role === "tool" &&
- typeof message.content === "object" &&
- message.content !== null &&
- !Array.isArray(message.content) &&
- (message.content as Record<string, unknown>).type === "function" &&
- !!(message.content as Record<string, unknown>).function &&
- !message.tool_call_id // Tool definitions don't have tool_call_id
- );
-}
-
-// extract tool definitions from messages array
-function extractToolDefinitions(messages: unknown[]): Array<{
- name: string;
- description?: string;
- parameters?: Record<string, unknown>;
-}> {
- return messages.filter(isLangGraphToolDefinition).map((msg) => {
- const message = msg as Record<string, unknown>;
- const func = (message.content as Record<string, unknown>)
- .function as Record<string, unknown>;
-
- const toolDef: Record<string, unknown> = {
- name: (func.name as string) || "",
- };
- if (func.description !== null && func.description !== undefined) {
- toolDef.description = func.description;
- }
- if (func.parameters !== null && func.parameters !== undefined) {
- toolDef.parameters = func.parameters;
- }
-
- return toolDef as {
- name: string;
- description?: string;
- parameters?: Record<string, unknown>;
- };
- });
-}
-
-function normalizeMessage(msg: unknown): Record<string, unknown> {
- if (!msg || typeof msg !== "object") return {};
-
- let normalized = removeNullFields(msg);
-
- // LangGraph/LangChain: "type" field → "role" field
- if (normalized.type && !normalized.role) {
- const typeToRole: Record<string, string> = {
- human: "user",
- ai: "assistant",
- tool: "tool",
- system: "system",
- };
- const type = String(normalized.type);
- if (typeToRole[type]) {
- normalized.role = typeToRole[type];
- normalized._originalType = type;
- }
- }
-
- // LangGraph: tool_calls in additional_kwargs → top level
- if (
- normalized.additional_kwargs &&
- typeof normalized.additional_kwargs === "object"
- ) {
- const additionalKwargs = normalized.additional_kwargs as Record<
- string,
- unknown
- >;
-
- // Handle tool_calls from additional_kwargs
- if (additionalKwargs.tool_calls) {
- if (!normalized.tool_calls) {
- // No top-level tool_calls, extract from additional_kwargs
- normalized.tool_calls = additionalKwargs.tool_calls;
- }
- // IMPORTANT: Always remove tool_calls from additional_kwargs to prevent
- // ChatMlSchema from overwriting our processed version when it spreads additional_kwargs
- // This handles both cases:
- // 1. LangGraph format: tool_calls extracted from additional_kwargs
- // 2. LangChain format: top-level tool_calls already exists, prevent overwrite
- // Don't mutate original object - JSON view needs to show original data
- // Filter out null fields to prevent them from creating extra json blocks in UI
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- const { tool_calls: _removed, ...restKwargs } = additionalKwargs;
- normalized.additional_kwargs = removeNullFields(restKwargs);
- }
-
- // Keep other fields in additional_kwargs (non-null values) for JSON view
- // ChatMlSchema will spread these into passthrough json field
- }
-
- // Flatten nested tool_calls format to flat ChatML format
- // LangGraph can have OpenAI-style nested format: {id, type, function: {name, arguments}}
- // Convert to flat format: {id, name, arguments, type}
- if (normalized.tool_calls && Array.isArray(normalized.tool_calls)) {
- const sanitizedToolCalls = (normalized.tool_calls as unknown[]).filter(
- (tc): tc is Record<string, unknown> =>
- Boolean(tc) && typeof tc === "object",
- );
-
- normalized.tool_calls = sanitizedToolCalls.map((tc) => {
- // If nested format (has function.name), flatten it
- if (tc.function && typeof tc.function === "object") {
- const func = tc.function as Record<string, unknown>;
- return {
- id: tc.id,
- name: func.name,
- arguments:
- typeof func.arguments === "string"
- ? func.arguments
- : JSON.stringify(func.arguments ?? {}),
- type: tc.type || "function",
- ...(tc.index !== undefined ? { index: tc.index } : {}),
- };
- }
- // Already flat format - handle both 'args' (LangChain) and 'arguments' (OpenAI)
- // LangChain uses 'args', OpenAI uses 'arguments'
- const argsValue = tc.args ?? tc.arguments;
- return {
- ...tc,
- name: tc.name,
- arguments:
- typeof argsValue === "string"
- ? argsValue
- : JSON.stringify(argsValue ?? {}),
- };
- });
- }
-
- // For tool messages with rich object content, spread into message
- // so it goes to json passthrough field → renders as PrettyJsonView.
- // Rich = nested structure OR 3+ keys. Simple <=2 scalar keys.
- if (
- normalized.role === "tool" &&
- typeof normalized.content === "object" &&
- normalized.content !== null &&
- !Array.isArray(normalized.content)
- ) {
- if (isRichToolResult(normalized.content)) {
- // Rich object: spread for table rendering
- const { content, ...rest } = normalized;
- return { ...rest, ...content };
- } else {
- // Simple object: stringify for text rendering
- normalized.content = stringifyToolResultContent(normalized.content);
- }
- }
-
- return normalized;
-}
-
-function filterAndNormalizeMessages(data: unknown[]): unknown[] {
- return data
- .filter((msg) => !isLangGraphToolDefinition(msg))
- .map(normalizeMessage);
-}
-
-function preprocessData(data: unknown): unknown {
- if (!data) return data;
-
- // Array of messages
- if (Array.isArray(data)) {
- const extractedTools = extractToolDefinitions(data);
- const normalizedMessages = filterAndNormalizeMessages(data);
-
- if (extractedTools.length > 0) {
- // Attach tools to all messages
- return normalizedMessages.map((msg) => ({
- ...(msg as Record<string, unknown>),
- tools: extractedTools,
- }));
- }
-
- return normalizedMessages;
- }
-
- // Object with messages key
- if (typeof data === "object" && "messages" in data) {
- const obj = data as Record<string, unknown>;
- if (Array.isArray(obj.messages)) {
- const extractedTools = extractToolDefinitions(obj.messages);
- const normalizedMessages = filterAndNormalizeMessages(obj.messages);
-
- if (extractedTools.length > 0) {
- return {
- ...obj,
- messages: normalizedMessages.map((msg) => ({
- ...(msg as Record<string, unknown>),
- tools: extractedTools,
- })),
- };
- }
-
- return {
- ...obj,
- messages: normalizedMessages,
- };
- }
- }
-
- // Single message - wrap in array for consistency
- if (typeof data === "object" && ("role" in data || "type" in data)) {
- return [normalizeMessage(data)];
- }
-
- return data;
-}
-
-export const langgraphAdapter: ProviderAdapter = {
- id: "langgraph",
-
- detect(ctx: NormalizerContext): boolean {
- const meta = parseMetadata(ctx.metadata);
-
- // EXPLICIT: Framework hint
- if (ctx.framework === "langgraph") return true;
-
- // REJECTIONS: Reject AI SDK v5 and OpenAI Agents SDK formats
- if (meta && typeof meta === "object") {
- // Check scope.name for AI SDK or OpenAI Agents
- if ("scope" in meta && typeof meta.scope === "object") {
- const scope = meta.scope as Record<string, unknown>;
-
- // Reject AI SDK v5 (scope.name === "ai")
- if (scope.name === "ai") return false;
-
- // Reject OpenAI Agents SDK
- if (
- scope.name === "openinference.instrumentation.openai_agents" ||
- (typeof scope.name === "string" &&
- scope.name.includes("openai_agents"))
- ) {
- return false;
- }
- }
-
- // Check attributes["operation.name"] for AI SDK pattern
- if ("attributes" in meta && typeof meta.attributes === "object") {
- const attrs = meta.attributes as Record<string, unknown> | null;
- if (
- attrs &&
- typeof attrs["operation.name"] === "string" &&
- attrs["operation.name"].startsWith("ai.")
- ) {
- return false;
- }
- }
- }
-
- // HINTS: LangGraph/LangChain-specific metadata markers
- if (meta && typeof meta === "object") {
- // LangGraph markers
- if (
- "langgraph_step" in meta ||
- "langgraph_node" in meta ||
- "langgraph_path" in meta ||
- "langgraph_checkpoint_ns" in meta ||
- meta.framework === "langgraph" ||
- (Array.isArray(meta.tags) && meta.tags.includes("langgraph"))
- ) {
- return true;
- }
-
- // LangSmith/LangChain markers (ls_ prefix indicates LangChain ecosystem)
- const hasLangChainMarkers = Object.keys(meta).some((key) =>
- key.startsWith("ls_"),
- );
- if (hasLangChainMarkers) {
- return true;
- }
- }
-
- // STRUCTURAL: Schema-based detection on metadata
- if (LangChainMessageSchema.safeParse(ctx.metadata).success) return true;
- if (LangGraphMessageSchema.safeParse(ctx.metadata).success) return true;
-
- // Check wrapped messages format
- if (LangGraphWrappedSchema.safeParse(ctx.metadata).success) {
- const wrapped = ctx.metadata as { messages: unknown[]; tools?: unknown };
- // reject OpenAI Chat Completions format {tools: [...], messages: [...]}
- if (Array.isArray(wrapped.tools)) {
- return false;
- }
- if (LangChainMessageSchema.safeParse(wrapped.messages).success)
- return true;
- if (LangGraphMessageSchema.safeParse(wrapped.messages).success)
- return true;
- }
-
- // finally Schema-based detection on data b/c of performance
- if (LangChainMessageSchema.safeParse(ctx.data).success) return true;
- if (LangGraphMessageSchema.safeParse(ctx.data).success) return true;
-
- // Check wrapped messages format on data
- if (LangGraphWrappedSchema.safeParse(ctx.data).success) {
- const wrapped = ctx.data as { messages: unknown[]; tools?: unknown };
- // reject OpenAI Chat Completions format {tools: [...], messages: [...]}
- if (Array.isArray(wrapped.tools)) {
- return false;
- }
- if (LangChainMessageSchema.safeParse(wrapped.messages).success)
- return true;
- if (LangGraphMessageSchema.safeParse(wrapped.messages).success)
- return true;
- }
-
- return false;
- },
-
- preprocess(
- data: unknown,
- _kind: "input" | "output",
- _ctx: NormalizerContext,
- ): unknown {
- return preprocessData(data);
- },
-};
+export { langgraphAdapter } from "@langfuse/shared";
diff --git a/web/src/utils/chatml/adapters/microsoft-agent.ts b/web/src/utils/chatml/adapters/microsoft-agent.ts
index b4d935cc64..b8da7ff92c 100644
--- a/web/src/utils/chatml/adapters/microsoft-agent.ts
+++ b/web/src/utils/chatml/adapters/microsoft-agent.ts
@@ -1,287 +1 @@
-import type { NormalizerContext, ProviderAdapter } from "../types";
-import {
- parseMetadata,
- getNestedProperty,
- stringifyToolResultContent,
- isRichToolResult,
-} from "../helpers";
-import { z } from "zod/v4";
-
-/**
- * Detection schemas for Microsoft Agent Framework format
- *
- * Microsoft Agent Framework uses a ChatML-like format with parts arrays:
- * - Messages: {role: "user|assistant|tool", parts: [{type, ...}]}
- * - Tool calls: {type: "tool_call", id: [...], name, arguments}
- * - Tool responses: {type: "tool_call_response", id: [...], response}
- * - Text: {type: "text", content}
- */
-
-// Microsoft Agent message with parts array
-const MicrosoftAgentMessageSchema = z.looseObject({
- role: z.enum(["user", "assistant", "tool"]),
- parts: z.array(
- z.looseObject({
- type: z.enum(["text", "tool_call", "tool_call_response"]),
- }),
- ),
-});
-
-// Array of Microsoft Agent messages
-const MicrosoftAgentMessagesSchema = z.array(MicrosoftAgentMessageSchema);
-
-/**
- * Extract tool calls and text content from parts array
- * Handles: text, tool_call, tool_call_response
- */
-function extractFromParts(parts: unknown[]): {
- toolCalls: Array<Record<string, unknown>>;
- text: string;
- toolCallId?: string;
-} {
- const toolCalls: Array<Record<string, unknown>> = [];
- const textParts: string[] = [];
- let toolCallId: string | undefined;
-
- for (const part of parts) {
- if (!part || typeof part !== "object") continue;
-
- const p = part as Record<string, unknown>;
-
- // Handle tool_call: {type: "tool_call", id: [...], name, arguments}
- if (p.type === "tool_call") {
- // uses array IDs: ["run_id", "call_id"], we just need the call id,
- let callId = "";
- if (Array.isArray(p.id)) {
- const callIdMatch = p.id.find(
- (id) => typeof id === "string" && id.startsWith("call_"),
- );
- callId = callIdMatch || p.id[p.id.length - 1] || "";
- } else if (typeof p.id === "string") {
- callId = p.id;
- }
-
- toolCalls.push({
- id: callId,
- name: p.name,
- arguments:
- typeof p.arguments === "string"
- ? p.arguments
- : JSON.stringify(p.arguments ?? {}),
- type: "function",
- });
- continue;
- }
-
- // Handle text: {type: "text", content}
- if (p.type === "text" && typeof p.content === "string") {
- textParts.push(p.content);
- continue;
- }
-
- // Handle tool_call_response: {type: "tool_call_response", id: [...], response}
- if (p.type === "tool_call_response") {
- // we just need the call_id, again
- if (Array.isArray(p.id)) {
- const callIdMatch = p.id.find(
- (id) => typeof id === "string" && id.startsWith("call_"),
- );
- toolCallId = callIdMatch || p.id[p.id.length - 1] || "";
- } else if (typeof p.id === "string") {
- toolCallId = p.id;
- }
- textParts.push(stringifyToolResultContent(p.response));
- }
- }
-
- return {
- toolCalls,
- text: textParts.join(""),
- toolCallId,
- };
-}
-
-/**
- * Extract tool definitions from metadata.attributes["gen_ai.tool.definitions"]
- * Microsoft Agent Framework uses OpenAI-style tool definitions
- */
-function extractToolDefinitions(tools: unknown): Array<{
- name: string;
- description?: string;
- parameters?: Record<string, unknown>;
-}> {
- if (!Array.isArray(tools)) return [];
-
- const definitions: Array<{
- name: string;
- description?: string;
- parameters?: Record<string, unknown>;
- }> = [];
-
- for (const tool of tools) {
- if (!tool || typeof tool !== "object") continue;
- const t = tool as Record<string, unknown>;
-
- // Handle OpenAI-style tool definitions: {type: "function", function: {name, description, parameters}}
- // intentionally not imported from openai for separation of concerns
- if (t.type === "function" && t.function && typeof t.function === "object") {
- const func = t.function as Record<string, unknown>;
- const toolDef: Record<string, unknown> = {
- name: func.name || "",
- };
- if (func.description !== null && func.description !== undefined) {
- toolDef.description = func.description;
- }
- if (func.parameters !== null && func.parameters !== undefined) {
- toolDef.parameters = func.parameters;
- }
- definitions.push(
- toolDef as {
- name: string;
- description?: string;
- parameters?: Record<string, unknown>;
- },
- );
- }
- }
-
- return definitions;
-}
-
-// Normalize a single Microsoft Agent message to our ChatML format
-function normalizeMicrosoftAgentMessage(msg: unknown): Record<string, unknown> {
- if (!msg || typeof msg !== "object") return {};
-
- const message = msg as Record<string, unknown>;
- const normalized = { ...message };
-
- if (normalized.parts && Array.isArray(normalized.parts)) {
- const { toolCalls, text, toolCallId } = extractFromParts(normalized.parts);
-
- if (toolCalls.length > 0) {
- normalized.tool_calls = toolCalls;
- }
-
- if (text) {
- normalized.content = text;
- }
-
- // Set tool_call_id for tool messages (from tool_call_response)
- if (toolCallId && normalized.role === "tool") {
- normalized.tool_call_id = toolCallId;
- }
-
- // prevent showing in passthrough
- delete normalized.parts;
- }
-
- // For tool messages with rich object content, spread into message
- // so it goes to json passthrough field → renders as PrettyJsonView.
- // Rich = nested structure OR 3+ keys. Simple <=2 scalar keys.
- if (
- normalized.role === "tool" &&
- typeof normalized.content === "object" &&
- normalized.content !== null &&
- !Array.isArray(normalized.content)
- ) {
- if (isRichToolResult(normalized.content)) {
- // Rich object: spread for table rendering
- const { content, ...rest } = normalized;
- return { ...rest, ...content };
- } else {
- // Simple object: stringify for text rendering
- normalized.content = stringifyToolResultContent(normalized.content);
- }
- }
-
- return normalized;
-}
-
-function normalizeMessages(data: unknown[]): unknown[] {
- return data.map(normalizeMicrosoftAgentMessage);
-}
-
-function preprocessData(data: unknown, ctx: NormalizerContext): unknown {
- if (!data) return data;
-
- if (Array.isArray(data)) {
- const normalized = normalizeMessages(data);
-
- // extract tool definitions from metadata
- const meta = parseMetadata(ctx.metadata);
- const toolDefinitions = getNestedProperty(
- meta,
- "attributes",
- "gen_ai.tool.definitions",
- );
-
- if (toolDefinitions) {
- const tools = extractToolDefinitions(toolDefinitions);
- if (tools.length > 0) {
- return normalized.map((msg) => ({
- ...(msg as Record<string, unknown>),
- tools,
- }));
- }
- }
-
- return normalized;
- }
-
- // messages wrapper
- if (typeof data === "object" && "messages" in data) {
- const obj = data as Record<string, unknown>;
- return {
- ...obj,
- messages: Array.isArray(obj.messages)
- ? normalizeMessages(obj.messages)
- : obj.messages,
- };
- }
-
- // single message
- if (typeof data === "object" && "role" in data) {
- return normalizeMicrosoftAgentMessage(data);
- }
-
- return data;
-}
-
-export const microsoftAgentAdapter: ProviderAdapter = {
- id: "microsoft-agent",
-
- detect(ctx: NormalizerContext): boolean {
- const meta = parseMetadata(ctx.metadata);
-
- // HINTS: Fast checks for explicit Microsoft Agent Framework indicators
- if (ctx.framework === "microsoft-agent") return true;
-
- const scopeName = getNestedProperty(meta, "scope", "name");
- if (scopeName === "agent_framework") return true;
-
- const providerName = getNestedProperty(
- meta,
- "attributes",
- "gen_ai.provider.name",
- );
- if (providerName === "microsoft.agent_framework") return true;
-
- // STRUCTURAL: Schema-based detection on metadata
- if (MicrosoftAgentMessagesSchema.safeParse(ctx.metadata).success)
- return true;
-
- // Schema-based detection on data (slower, do last)
- if (MicrosoftAgentMessagesSchema.safeParse(ctx.data).success) return true;
- if (MicrosoftAgentMessageSchema.safeParse(ctx.data).success) return true;
-
- return false;
- },
-
- preprocess(
- data: unknown,
- _kind: "input" | "output",
- ctx: NormalizerContext,
- ): unknown {
- return preprocessData(data, ctx);
- },
-};
+export { microsoftAgentAdapter } from "@langfuse/shared";
diff --git a/web/src/utils/chatml/adapters/openai.ts b/web/src/utils/chatml/adapters/openai.ts
index 61558e37b6..32e6acedb5 100644
--- a/web/src/utils/chatml/adapters/openai.ts
+++ b/web/src/utils/chatml/adapters/openai.ts
@@ -1,402 +1 @@
-import type { NormalizerContext, ProviderAdapter } from "../types";
-import {
- removeNullFields,
- stringifyToolResultContent,
- parseMetadata,
- isRichToolResult,
-} from "../helpers";
-import { z } from "zod/v4";
-
-/**
- * Detection schemas for OpenAI formats
- * These are permissive - only validate structural markers, not full API contracts
- */
-
-// INPUT SCHEMAS (requests)
-const OpenAIInputChatCompletionsSchema = z.looseObject({
- messages: z.array(z.any()),
- tools: z.array(z.any()).optional(),
-});
-
-const OpenAIInputMessagesSchema = z
- .array(
- z.looseObject({
- role: z.enum(["system", "user", "assistant", "tool", "function"]),
- }),
- )
- .refine(
- (data) => {
- // Reject if any message has top-level parts (Microsoft Agent/Gemini format)
- // OpenAI uses parts inside content, not at message level
- return !data.some(
- (msg) =>
- typeof msg === "object" &&
- msg !== null &&
- "parts" in msg &&
- Array.isArray((msg as Record<string, unknown>).parts),
- );
- },
- { message: "Messages with top-level parts are not OpenAI format" },
- );
-
-// OUTPUT SCHEMAS (responses)
-const OpenAIOutputResponsesSchema = z.looseObject({
- output: z.array(z.any()),
- tools: z.array(z.any()).optional(),
-});
-
-const OpenAIOutputChoicesSchema = z.looseObject({
- model: z.string(),
- choices: z.array(z.any()),
-});
-
-const OpenAIOutputSingleMessageSchema = z.looseObject({
- role: z.string(),
- tool_calls: z.array(
- z.looseObject({
- type: z.string(),
- function: z.looseObject({
- name: z.string(),
- }),
- }),
- ),
-});
-
-function normalizeMessage(msg: unknown): Record<string, unknown> {
- if (!msg || typeof msg !== "object") return {};
-
- // we want to do type-based conversions BEFORE removeNullFields
- // because removeNullFields moves unrecognized fields to json passthrough
- let working = msg as Record<string, unknown>;
-
- // Convert direct function call message to tool_calls array format
- // Format: { type: "function_call", name: "...", arguments: {...}, call_id: "..." }
- // Convert to: { role: "assistant", tool_calls: [{ id, name, arguments, type }] }
- if (
- (working.type === "function_call" || working.type === "tool_call") &&
- working.name &&
- typeof working.name === "string"
- ) {
- const toolCall: Record<string, unknown> = {
- id: working.call_id || working.id || "",
- name: working.name,
- arguments:
- typeof working.arguments === "string"
- ? working.arguments
- : JSON.stringify(working.arguments ?? {}),
- type: "function",
- };
-
- /* eslint-disable @typescript-eslint/no-unused-vars */
- const {
- type: _type,
- name: _name,
- arguments: _args,
- call_id: _call_id,
- id: _id,
- status: _status,
- ...rest
- } = working;
- /* eslint-enable @typescript-eslint/no-unused-vars */
- working = {
- ...rest,
- role: rest.role || "assistant",
- tool_calls: [toolCall],
- };
- }
-
- // Convert function_call_output to standard tool message format
- // Format: { type: "function_call_output", call_id: "...", output: "..." }
- // Convert to: { role: "tool", tool_call_id: "...", content: "..." }
- if (working.type === "function_call_output") {
- const content =
- typeof working.output === "string"
- ? working.output
- : JSON.stringify(working.output ?? "");
-
- /* eslint-disable @typescript-eslint/no-unused-vars */
- const { type: _type, call_id, output: _output, ...rest } = working;
- /* eslint-enable @typescript-eslint/no-unused-vars */
-
- working = {
- ...rest,
- role: "tool",
- tool_call_id: call_id,
- content,
- };
- }
-
- // Now apply removeNullFields after conversions
- let normalized = removeNullFields(working);
-
- // Extract text from OpenAI Agents output_text format
- // Format: content: [{type: "output_text", text: "..."}]
- if (
- normalized.content &&
- Array.isArray(normalized.content) &&
- normalized.content.length > 0
- ) {
- const firstItem = normalized.content[0];
- if (
- firstItem &&
- typeof firstItem === "object" &&
- (firstItem as Record<string, unknown>).type === "output_text" &&
- typeof (firstItem as Record<string, unknown>).text === "string"
- ) {
- // Extract just the text for simple output
- normalized.content = (firstItem as Record<string, unknown>).text;
- }
- }
-
- // Normalize camelCase toolCalls to snake_case tool_calls (VAPI framework does this, otherwise it matches OpenAI)
- if ("toolCalls" in normalized && Array.isArray(normalized.toolCalls)) {
- normalized.tool_calls = normalized.toolCalls;
- delete normalized.toolCalls;
- }
-
- // Flatten OpenAI nested tool_calls format: function.name → name, function.arguments → arguments
- // Format: { id, type: "function", function: { name, arguments } }
- // Convert to: { id, name, arguments, type }
- if (normalized.tool_calls && Array.isArray(normalized.tool_calls)) {
- const sanitizedToolCalls = (normalized.tool_calls as unknown[]).filter(
- (tc): tc is Record<string, unknown> =>
- Boolean(tc) && typeof tc === "object",
- );
-
- normalized.tool_calls = sanitizedToolCalls.map((tc) => {
- if (tc.function && typeof tc.function === "object") {
- const func = tc.function as Record<string, unknown>;
- return {
- id: tc.id,
- name: func.name,
- arguments:
- typeof func.arguments === "string"
- ? func.arguments
- : JSON.stringify(func.arguments ?? {}),
- type: tc.type || "function",
- index: tc.index,
- };
- }
- // Already flat format, just ensure arguments is stringified
- return {
- ...tc,
- arguments:
- typeof tc.arguments === "string"
- ? tc.arguments
- : JSON.stringify(tc.arguments ?? {}),
- };
- });
- }
-
- // For tool messages with rich object content, spread into message
- // so it goes to json passthrough field and renders as PrettyJsonView.
- // Rich = nested structure OR 3+ keys. Simple <=2 scalar keys.
- if (
- normalized.role === "tool" &&
- typeof normalized.content === "object" &&
- normalized.content !== null &&
- !Array.isArray(normalized.content)
- ) {
- if (isRichToolResult(normalized.content)) {
- // Rich object: spread for table rendering
- const { content, ...rest } = normalized;
- return { ...rest, ...content };
- } else {
- // Simple object: stringify for text rendering
- normalized.content = stringifyToolResultContent(normalized.content);
- }
- }
-
- return normalized;
-}
-
-/**
- * Flatten tool definition from nested or flat format to standard format
- * Handles both Chat Completions {type, function: {name, ...}} and flat {name, ...}
- */
-function flattenToolDefinition(tool: unknown): Record<string, unknown> {
- if (typeof tool !== "object" || !tool) return {};
-
- const t = tool as Record<string, unknown>;
- // Handle nested {type, function: {name, ...}} or flat {name, ...}
- const toolFunc = (t.function as Record<string, unknown> | undefined) ?? t;
-
- const toolDef: Record<string, unknown> = {
- name: toolFunc.name,
- description: toolFunc.description ?? "",
- };
- if (toolFunc.parameters != null) toolDef.parameters = toolFunc.parameters;
- return toolDef;
-}
-
-function preprocessData(data: unknown): unknown {
- if (!data) return data;
-
- // OpenAI Chat Completions API: {tools, messages} OR Responses API: {tools, output}
- // References:
- // - https://platform.openai.com/docs/api-reference/chat/create
- // - https://platform.openai.com/docs/api-reference/responses
- if (
- typeof data === "object" &&
- !Array.isArray(data) &&
- "tools" in data &&
- (("messages" in data && !("output" in data)) || "output" in data)
- ) {
- const obj = data as Record<string, unknown>;
- const messagesArray = (obj.messages ?? obj.output) as unknown[];
-
- if (Array.isArray(messagesArray) && Array.isArray(obj.tools)) {
- // Attach tools to all messages
- return messagesArray.map((msg) => ({
- ...normalizeMessage(msg),
- tools: (obj.tools as unknown[]).map(flattenToolDefinition),
- }));
- }
- }
-
- // Responses API without tools: {output: [...]}
- if (
- typeof data === "object" &&
- !Array.isArray(data) &&
- "output" in data &&
- !("messages" in data) &&
- !("tools" in data)
- ) {
- const obj = data as Record<string, unknown>;
- if (Array.isArray(obj.output)) {
- return (obj.output as unknown[]).map(normalizeMessage);
- }
- }
-
- // Chat Completions response: {choices: [{message: {...}}]}
- if (typeof data === "object" && !Array.isArray(data) && "choices" in data) {
- const obj = data as Record<string, unknown>;
- if (Array.isArray(obj.choices) && obj.choices.length > 0) {
- const firstChoice = obj.choices[0] as Record<string, unknown>;
- if (
- firstChoice &&
- typeof firstChoice === "object" &&
- "message" in firstChoice
- ) {
- return normalizeMessage(firstChoice.message);
- }
- }
- }
-
- // Array of messages
- if (Array.isArray(data)) {
- return data.map(normalizeMessage);
- }
-
- // Object with messages key
- if (typeof data === "object" && "messages" in data) {
- const obj = data as Record<string, unknown>;
- return {
- ...obj,
- messages: Array.isArray(obj.messages)
- ? obj.messages.map(normalizeMessage)
- : obj.messages,
- };
- }
-
- // Single message
- if (typeof data === "object" && "role" in data) {
- return normalizeMessage(data);
- }
-
- return data;
-}
-
-export const openAIAdapter: ProviderAdapter = {
- id: "openai",
-
- detect(ctx: NormalizerContext): boolean {
- const meta = parseMetadata(ctx.metadata);
-
- // REJECTIONS: Explicit rejection of LangGraph/LangChain formats
- if (meta && typeof meta === "object") {
- // LangGraph
- if (
- "langgraph_step" in meta ||
- "langgraph_node" in meta ||
- "langgraph_path" in meta ||
- meta.framework === "langgraph" ||
- (Array.isArray(meta.tags) && meta.tags.includes("langgraph"))
- ) {
- return false;
- }
-
- // LangChain (type without role)
- if (
- ctx.metadata &&
- typeof ctx.metadata === "object" &&
- "messages" in ctx.metadata
- ) {
- const messages = (ctx.metadata as Record<string, unknown>).messages;
- if (Array.isArray(messages)) {
- const hasLangChainType = messages.some((msg: unknown) => {
- // Null guard: ensure msg exists and is an object before accessing properties
- if (!msg || typeof msg !== "object") {
- return false;
- }
- const message = msg as Record<string, unknown>;
- return (
- message.type &&
- typeof message.type === "string" &&
- ["human", "ai", "tool", "system"].includes(message.type) &&
- !("role" in message)
- );
- });
- if (hasLangChainType) return false;
- }
- }
- }
-
- // HINTS: Fast checks for explicit OpenAI indicators
- if (ctx.framework === "openai") return true;
- if (ctx.observationName?.toLowerCase().includes("openai")) return true;
- if (meta?.ls_provider === "openai") return true;
-
- // Metadata attributes check
- if (meta && typeof meta === "object" && "attributes" in meta) {
- const attributes = (meta as Record<string, unknown>).attributes;
- if (
- attributes &&
- typeof attributes === "object" &&
- (attributes as Record<string, unknown>)["llm.system"] === "openai"
- ) {
- return true;
- }
- }
-
- // STRUCTURAL: Schema-based detection on metadata
- if (OpenAIInputChatCompletionsSchema.safeParse(ctx.metadata).success)
- return true;
- if (OpenAIInputMessagesSchema.safeParse(ctx.metadata).success) return true;
- if (OpenAIOutputResponsesSchema.safeParse(ctx.metadata).success)
- return true;
- if (OpenAIOutputChoicesSchema.safeParse(ctx.metadata).success) return true;
- if (OpenAIOutputSingleMessageSchema.safeParse(ctx.metadata).success)
- return true;
-
- // finally, test on data if available. we might've done this already if we passed
- // data into metadata. we only do this last due to performance concerns.
- if (OpenAIInputChatCompletionsSchema.safeParse(ctx.data).success)
- return true;
- if (OpenAIInputMessagesSchema.safeParse(ctx.data).success) return true;
- if (OpenAIOutputResponsesSchema.safeParse(ctx.data).success) return true;
- if (OpenAIOutputChoicesSchema.safeParse(ctx.data).success) return true;
- if (OpenAIOutputSingleMessageSchema.safeParse(ctx.data).success)
- return true;
-
- return false;
- },
-
- preprocess(
- data: unknown,
- _kind: "input" | "output",
- _ctx: NormalizerContext,
- ): unknown {
- return preprocessData(data);
- },
-};
+export { openAIAdapter } from "@langfuse/shared";
diff --git a/web/src/utils/chatml/adapters/pydantic-ai.ts b/web/src/utils/chatml/adapters/pydantic-ai.ts
index 9db49e6453..c4ce5301fe 100644
--- a/web/src/utils/chatml/adapters/pydantic-ai.ts
+++ b/web/src/utils/chatml/adapters/pydantic-ai.ts
@@ -1,227 +1 @@
-import type { NormalizerContext, ProviderAdapter } from "../types";
-import { removeNullFields, parseMetadata, getNestedProperty } from "../helpers";
-import { z } from "zod/v4";
-
-/**
- * Pydantic AI adapter
- * Handles pydantic-ai's parts-based message format
- *
- * Pydantic AI uses parts arrays:
- * - Text: {type: "text", content: "..."}
- * - Tool calls: {type: "tool_call", id, name, arguments}
- * - Tool responses: {type: "tool_call_response", id, name, result}
- * Tools are in: metadata.attributes.model_request_parameters.function_tools
- */
-
-// Detection schema
-const PydanticAIMessagesSchema = z.array(
- z.looseObject({
- role: z.enum(["system", "user", "assistant"]),
- parts: z.array(z.any()),
- }),
-);
-
-/**
- * Extract tool calls, text, and tool responses from parts array
- */
-function extractFromParts(parts: unknown[]): {
- toolCalls: Array<Record<string, unknown>>;
- toolResponses: Array<Record<string, unknown>>;
- text: string;
-} {
- const toolCalls: Array<Record<string, unknown>> = [];
- const toolResponses: Array<Record<string, unknown>> = [];
- const textParts: string[] = [];
-
- for (const part of parts) {
- if (!part || typeof part !== "object") continue;
- const p = part as Record<string, unknown>;
-
- if (p.type === "text" && typeof p.content === "string") {
- textParts.push(p.content);
- } else if (p.type === "tool_call") {
- toolCalls.push({
- id: p.id,
- name: p.name,
- arguments:
- typeof p.arguments === "string"
- ? p.arguments
- : JSON.stringify(p.arguments ?? {}),
- type: "function",
- });
- } else if (p.type === "tool_call_response") {
- toolResponses.push({
- tool_call_id: p.id,
- content:
- typeof p.result === "string"
- ? p.result
- : JSON.stringify(p.result ?? ""),
- });
- }
- }
-
- return { toolCalls, toolResponses, text: textParts.join("") };
-}
-
-/**
- * Normalize pydantic-ai tool definition to standard format
- */
-function normalizeToolDefinition(tool: unknown): Record<string, unknown> {
- if (!tool || typeof tool !== "object") return {};
-
- const t = tool as Record<string, unknown>;
- const normalized: Record<string, unknown> = {
- name: t.name,
- description: t.description || "",
- };
-
- // pydantic-ai uses parameters_json_schema instead of parameters
- if (t.parameters_json_schema) {
- normalized.parameters = t.parameters_json_schema;
- }
-
- return normalized;
-}
-
-/**
- * Extract tool definitions from pydantic-ai metadata
- * Tools are in: metadata.attributes.model_request_parameters.function_tools
- */
-function extractToolDefinitions(
- metadata: unknown,
-): Array<Record<string, unknown>> {
- const meta = parseMetadata(metadata);
- if (!meta) return [];
-
- const tools = getNestedProperty(
- meta,
- "attributes",
- "model_request_parameters",
- "function_tools",
- );
-
- if (Array.isArray(tools)) {
- return tools.map(normalizeToolDefinition);
- }
-
- return [];
-}
-
-/**
- * Normalize a single pydantic-ai message
- * Returns either a single message or array of messages (for tool responses)
- */
-function normalizeMessage(
- msg: unknown,
-): Record<string, unknown> | Record<string, unknown>[] {
- if (!msg || typeof msg !== "object") return {};
-
- const message = msg as Record<string, unknown>;
-
- // If no parts, return as-is
- if (!Array.isArray(message.parts)) {
- return removeNullFields(message);
- }
-
- const { toolCalls, toolResponses, text } = extractFromParts(message.parts);
-
- // Extract other fields (exclude role and parts)
- const { role: _role, parts: _parts, ...rest } = message;
-
- // Assistant message with tool calls
- if (message.role === "assistant" && toolCalls.length > 0) {
- return removeNullFields({
- role: "assistant",
- content: text || "",
- tool_calls: toolCalls,
- ...rest,
- });
- }
-
- // User message with tool responses - split into separate tool messages
- if (message.role === "user" && toolResponses.length > 0) {
- return toolResponses.map((tr) =>
- removeNullFields({
- role: "tool",
- ...tr,
- }),
- );
- }
-
- // Regular text message
- return removeNullFields({
- role: message.role,
- content: text || "",
- ...rest,
- });
-}
-
-function normalizeMessages(data: unknown[]): unknown[] {
- return data.flatMap((msg) => {
- const normalized = normalizeMessage(msg);
- return Array.isArray(normalized) ? normalized : [normalized];
- });
-}
-
-function preprocessData(data: unknown, ctx: NormalizerContext): unknown {
- if (!data) return data;
-
- // Handle array of messages
- if (Array.isArray(data)) {
- const normalized = normalizeMessages(data);
-
- // Extract and attach tool definitions from metadata
- const tools = extractToolDefinitions(ctx.metadata);
- if (tools.length > 0) {
- return normalized.map((msg) => ({
- ...(msg as Record<string, unknown>),
- tools,
- }));
- }
-
- return normalized;
- }
-
- // messages wrapper
- if (typeof data === "object" && "messages" in data) {
- const obj = data as Record<string, unknown>;
- return {
- ...obj,
- messages: Array.isArray(obj.messages)
- ? normalizeMessages(obj.messages)
- : obj.messages,
- };
- }
-
- // Single message
- return normalizeMessage(data);
-}
-
-export const pydanticAIAdapter: ProviderAdapter = {
- id: "pydantic-ai",
-
- detect(ctx: NormalizerContext): boolean {
- const meta = parseMetadata(ctx.metadata);
-
- if (ctx.framework === "pydantic-ai") return true;
-
- const scopeName = getNestedProperty(meta, "scope", "name");
- if (scopeName === "pydantic-ai") return true;
-
- // STRUCTURAL: Schema-based detection on metadata (check metadata first for performance)
- if (PydanticAIMessagesSchema.safeParse(ctx.metadata).success) return true;
-
- // Schema-based detection on data (slower, do last)
- if (PydanticAIMessagesSchema.safeParse(ctx.data).success) return true;
-
- return false;
- },
-
- preprocess(
- data: unknown,
- _kind: "input" | "output",
- ctx: NormalizerContext,
- ): unknown {
- return preprocessData(data, ctx);
- },
-};
+export { pydanticAIAdapter } from "@langfuse/shared";
diff --git a/web/src/utils/chatml/extractTools.ts b/web/src/utils/chatml/extractTools.ts
index c9566068ef..bc98f0eae5 100644
--- a/web/src/utils/chatml/extractTools.ts
+++ b/web/src/utils/chatml/extractTools.ts
@@ -1,7 +1,6 @@
import { z } from "zod/v4";
-import { OpenAIToolSchema } from "@langfuse/shared";
+import { OpenAIToolSchema, extractAdditionalInput } from "@langfuse/shared";
import type { PlaygroundTool } from "@/src/features/playground/page/types";
-import { extractAdditionalInput } from "./core";
/**
* Helper to map parsed OpenAI tool schemas to PlaygroundTool format.
diff --git a/web/src/utils/chatml/helpers.ts b/web/src/utils/chatml/helpers.ts
index b6adc84a2d..65150e28dc 100644
--- a/web/src/utils/chatml/helpers.ts
+++ b/web/src/utils/chatml/helpers.ts
@@ -1,99 +1,8 @@
-export function removeNullFields(obj: unknown): Record<string, unknown> {
- if (!obj || typeof obj !== "object") return {};
-
- const cleaned: Record<string, unknown> = { ...obj };
-
- Object.keys(cleaned).forEach((key) => {
- if (cleaned[key] === null) {
- delete cleaned[key];
- }
- });
-
- return cleaned;
-}
-
-export function stringifyToolCallArgs(
- toolCall: Record<string, unknown>,
-): Record<string, unknown> {
- if (!toolCall?.function) return toolCall;
-
- const func = toolCall.function as Record<string, unknown>;
- return {
- ...toolCall,
- function: {
- ...func,
- arguments:
- typeof func.arguments === "string"
- ? func.arguments
- : JSON.stringify(func.arguments ?? {}),
- },
- };
-}
-
-export function stringifyToolResultContent(content: unknown): string {
- if (typeof content === "string") return content;
- if (content === null || content === undefined) return "";
- return JSON.stringify(content);
-}
-
-/**
- * used to check if a tool call is "complex" to render as PrettyJsonView table
- * or stringify it and render it as pure string. only used for role: tool type
- * calls. used for tool calls themselves, not for tool selections by an LLM.
- *
- * Rich = has nested structure OR has more than 2 top-level keys
- * Simple <= 2 keys with only scalar values (strings, numbers, booleans, null)
- */
-export function isRichToolResult(content: unknown): boolean {
- if (!content || typeof content !== "object" || Array.isArray(content)) {
- return false;
- }
-
- const keys = Object.keys(content);
-
- // More than 2 keys → probably rich/structured data
- if (keys.length > 2) return true;
-
- // Check if any value is an object or array (nested structure)
- for (const key of keys) {
- const value = (content as Record<string, unknown>)[key];
- if (value && typeof value === "object") {
- return true; // Has nested structure
- }
- }
-
- // 1-2 keys with only scalar values: simple
- return false;
-}
-
-export function parseMetadata(
- metadata: unknown,
-): Record<string, unknown> | null {
- if (!metadata) return null;
-
- if (typeof metadata === "string") {
- try {
- return JSON.parse(metadata);
- } catch {
- return null;
- }
- }
-
- if (typeof metadata === "object") {
- return metadata as Record<string, unknown>;
- }
-
- return null;
-}
-
-export function getNestedProperty(
- obj: Record<string, unknown> | null | undefined,
- ...path: string[]
-): unknown {
- let current: unknown = obj;
- for (const key of path) {
- if (!current || typeof current !== "object") return undefined;
- current = (current as Record<string, unknown>)[key];
- }
- return current;
-}
+export {
+ removeNullFields,
+ stringifyToolCallArgs,
+ stringifyToolResultContent,
+ isRichToolResult,
+ parseMetadata,
+ getNestedProperty,
+} from "@langfuse/shared";
diff --git a/web/src/utils/chatml/index.ts b/web/src/utils/chatml/index.ts
index 65491b9a28..2b4f743e88 100644
--- a/web/src/utils/chatml/index.ts
+++ b/web/src/utils/chatml/index.ts
@@ -1,11 +1,14 @@
+// Re-export from shared (core functions moved to enable worker testing)
export {
mapToChatMl,
mapOutputToChatMl,
cleanLegacyOutput,
extractAdditionalInput,
combineInputOutputMessages,
-} from "./core";
-
-export { normalizeInput, normalizeOutput } from "./adapters";
-
-export type { NormalizerContext, ProviderAdapter, ToolEvent } from "./types";
+ normalizeInput,
+ normalizeOutput,
+ selectAdapter,
+ type NormalizerContext,
+ type ProviderAdapter,
+ type ToolEvent,
+} from "@langfuse/shared";
diff --git a/web/src/utils/chatml/jumptoplayground.clienttest.ts b/web/src/utils/chatml/jumptoplayground.clienttest.ts
index 8d8eb7f3f0..239dc0bfca 100644
--- a/web/src/utils/chatml/jumptoplayground.clienttest.ts
+++ b/web/src/utils/chatml/jumptoplayground.clienttest.ts
@@ -1,5 +1,6 @@
// Mock the problematic @langfuse/shared import before importing our functions
jest.mock("@langfuse/shared", () => {
+ const actual = jest.requireActual("@langfuse/shared");
const { z } = require("zod/v4");
const OpenAITextContentPart = z.object({
@@ -19,6 +20,7 @@ jest.mock("@langfuse/shared", () => {
});
return {
+ ...actual,
ChatMessageRole: {
System: "system",
Developer: "developer",
diff --git a/web/src/utils/chatml/playgroundConverter.ts b/web/src/utils/chatml/playgroundConverter.ts
index 9ea096597a..cb8f47a4b8 100644
--- a/web/src/utils/chatml/playgroundConverter.ts
+++ b/web/src/utils/chatml/playgroundConverter.ts
@@ -1,4 +1,5 @@
-import type { ChatMlMessageSchema } from "@/src/components/schemas/ChatMlSchema";
+import { type z } from "zod/v4";
+import { type ChatMlMessageSchema } from "@langfuse/shared";
import {
ChatMessageRole,
ChatMessageType,
@@ -8,6 +9,8 @@ import {
type PlaceholderMessage,
} from "@langfuse/shared";
+type ChatMlMessage = z.infer<typeof ChatMlMessageSchema>;
+
// convert content to string format expected by playground
function contentToString(content: unknown): string {
if (typeof content === "string") {
@@ -47,7 +50,7 @@ function contentToString(content: unknown): string {
}
export function convertChatMlToPlayground(
- msg: ChatMlMessageSchema,
+ msg: ChatMlMessage,
): ChatMessage | PlaceholderMessage | null {
// Handle placeholder messages
if (msg.type === "placeholder") {
diff --git a/web/src/utils/chatml/types.ts b/web/src/utils/chatml/types.ts
index 6b4ea37bb8..916e760aae 100644
--- a/web/src/utils/chatml/types.ts
+++ b/web/src/utils/chatml/types.ts
@@ -1,33 +1,5 @@
-export type NormalizerContext = {
- metadata?: unknown;
- observationName?: string;
- framework?: string; // for explicit overrides
- data?: unknown; // Optional: actual input/output content for structural detection
-};
-
-// Unified tool event representation across all providers
-export type ToolEvent =
- | {
- type: "call";
- id?: string;
- name: string;
- argsJson: string; // Always JSON string for consistency
- }
- | {
- type: "result";
- id?: string;
- content: string; // Always string (stringify objects)
- status?: "ok" | "error";
- };
-
-// Minimal provider adapter interface
-export interface ProviderAdapter {
- id: string;
- detect(ctx: NormalizerContext): boolean;
- preprocess(
- data: unknown,
- kind: "input" | "output",
- ctx: NormalizerContext,
- ): unknown;
- extractToolEvents?(message: Record<string, unknown>): ToolEvent[];
-}
+export type {
+ NormalizerContext,
+ ProviderAdapter,
+ ToolEvent,
+} from "@langfuse/shared";
diff --git a/web/src/utils/chatml/adapters/aisdk.clienttest.ts b/worker/src/__tests__/chatml/adapters/aisdk.test.ts
similarity index 93%
rename from web/src/utils/chatml/adapters/aisdk.clienttest.ts
rename to worker/src/__tests__/chatml/adapters/aisdk.test.ts
index 528506e027..a0fe811efc 100644
--- a/web/src/utils/chatml/adapters/aisdk.clienttest.ts
+++ b/worker/src/__tests__/chatml/adapters/aisdk.test.ts
@@ -1,35 +1,9 @@
-// BaseChatMlMessageSchema was extracted to shared package in IO read-time extraction
-// now ChatMlSchema.ts imports it, so our test import chain pulls it in:
-// aisdk.clienttest → adapters/index → core → ChatMlSchema → @langfuse/shared
-jest.mock("@langfuse/shared", () => {
- const { z } = require("zod/v4");
-
- return {
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
- BaseChatMlMessageSchema: z
- .object({
- role: z.string().optional(),
- name: z.string().optional(),
- content: z
- .union([z.record(z.string(), z.any()), z.string(), z.array(z.any())])
- .optional(),
- tool_calls: z.array(z.any()).optional(),
- tool_call_id: z.string().optional(),
- additional_kwargs: z.record(z.string(), z.any()).optional(),
- })
- .passthrough(),
- };
-});
-
-import { normalizeInput } from "./index";
-import { aisdkAdapter } from "./aisdk";
+import { describe, it, expect } from "vitest";
+import {
+ aisdkAdapter,
+ normalizeInput,
+ type NormalizerContext,
+} from "@langfuse/shared";
describe("AI SDK Adapter", () => {
describe("detection", () => {
diff --git a/web/src/utils/chatml/adapters/gemini.clienttest.ts b/worker/src/__tests__/chatml/adapters/gemini.test.ts
similarity index 88%
rename from web/src/utils/chatml/adapters/gemini.clienttest.ts
rename to worker/src/__tests__/chatml/adapters/gemini.test.ts
index 4bf5e18d87..2f615716a9 100644
--- a/web/src/utils/chatml/adapters/gemini.clienttest.ts
+++ b/worker/src/__tests__/chatml/adapters/gemini.test.ts
@@ -1,40 +1,21 @@
-jest.mock("@langfuse/shared", () => {
- const { z } = require("zod/v4");
+import { describe, it, expect } from "vitest";
+import {
+ geminiAdapter,
+ selectAdapter,
+ SimpleChatMlArraySchema,
+ type NormalizerContext,
+} from "@langfuse/shared";
- return {
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
- BaseChatMlMessageSchema: z
- .object({
- role: z.string().optional(),
- name: z.string().optional(),
- content: z
- .union([
- z.record(z.string(), z.any()),
- z.string(),
- z.array(z.any()),
- z.any(), // Simplified - was OpenAIContentSchema
- ])
- .nullish(),
- audio: z.any().optional(),
- additional_kwargs: z.record(z.string(), z.any()).optional(),
- tools: z.array(z.any()).optional(),
- tool_calls: z.array(z.any()).optional(),
- tool_call_id: z.string().optional(),
- })
- .passthrough(),
- };
-});
-
-import { geminiAdapter } from "./gemini";
-import type { NormalizerContext } from "../types";
-import { normalizeInput } from "./index";
+// Test helper
+function normalizeInput(input: unknown, ctx: NormalizerContext = {}) {
+ const adapter = selectAdapter({
+ ...ctx,
+ metadata: ctx.metadata ?? input,
+ data: input,
+ });
+ const preprocessed = adapter.preprocess(input, "input", ctx);
+ return SimpleChatMlArraySchema.safeParse(preprocessed);
+}
describe("geminiAdapter", () => {
describe("detect", () => {
diff --git a/web/src/utils/chatml/adapters/generic.clienttest.ts b/worker/src/__tests__/chatml/adapters/generic.test.ts
similarity index 78%
rename from web/src/utils/chatml/adapters/generic.clienttest.ts
rename to worker/src/__tests__/chatml/adapters/generic.test.ts
index 5b79a05855..b3aa6fbcc1 100644
--- a/web/src/utils/chatml/adapters/generic.clienttest.ts
+++ b/worker/src/__tests__/chatml/adapters/generic.test.ts
@@ -1,40 +1,11 @@
-jest.mock("@langfuse/shared", () => {
- const { z } = require("zod/v4");
-
- return {
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
- BaseChatMlMessageSchema: z
- .object({
- role: z.string().optional(),
- name: z.string().optional(),
- content: z
- .union([
- z.record(z.string(), z.any()),
- z.string(),
- z.array(z.any()),
- z.any(), // Simplified - was OpenAIContentSchema
- ])
- .nullish(),
- audio: z.any().optional(),
- additional_kwargs: z.record(z.string(), z.any()).optional(),
- tools: z.array(z.any()).optional(),
- tool_calls: z.array(z.any()).optional(),
- tool_call_id: z.string().optional(),
- })
- .passthrough(),
- };
-});
-
-import { normalizeInput, normalizeOutput } from "./index";
-import { combineInputOutputMessages, cleanLegacyOutput } from "../core";
-import { genericAdapter } from "./generic";
+import { describe, it, expect } from "vitest";
+import {
+ genericAdapter,
+ normalizeInput,
+ normalizeOutput,
+ combineInputOutputMessages,
+ cleanLegacyOutput,
+} from "@langfuse/shared";
describe("Generic Adapter", () => {
it("should always detect (fallback)", () => {
diff --git a/worker/src/__tests__/chatml/adapters/generic.test.ts.new b/worker/src/__tests__/chatml/adapters/generic.test.ts.new
new file mode 100644
index 0000000000..cd39a66a95
--- /dev/null
+++ b/worker/src/__tests__/chatml/adapters/generic.test.ts.new
@@ -0,0 +1,144 @@
+import { describe, it, expect } from "vitest";
+import {
+ genericAdapter,
+ normalizeInput,
+ normalizeOutput,
+ combineInputOutputMessages,
+ cleanLegacyOutput,
+} from "@langfuse/shared";
+}
+
+describe("Generic Adapter", () => {
+ it("should always detect (fallback)", () => {
+ expect(genericAdapter.detect({})).toBe(true);
+ expect(genericAdapter.detect({ metadata: { anything: "value" } })).toBe(
+ true,
+ );
+ });
+
+ it("should handle basic ChatML format", () => {
+ const input = [
+ { role: "user", content: "Hello!" },
+ { role: "assistant", content: "Hi there!" },
+ ];
+ const output = { role: "assistant", content: "Response" };
+
+ const inResult = normalizeInput(input);
+ const outResult = normalizeOutput(output);
+ const allMessages = combineInputOutputMessages(
+ inResult,
+ outResult,
+ cleanLegacyOutput(output, output),
+ );
+
+ expect(inResult.success).toBe(true);
+ expect(outResult.success).toBe(true);
+ expect(allMessages).toHaveLength(3);
+ expect(allMessages).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ role: "user", content: "Hello!" }),
+ expect.objectContaining({ role: "assistant", content: "Hi there!" }),
+ expect.objectContaining({ role: "assistant", content: "Response" }),
+ ]),
+ );
+ });
+
+ it("should not display non-ChatML formats as chat", () => {
+ const input = {
+ new_message: {
+ parts: [{ text: "hi" }],
+ role: "user",
+ },
+ run_config: {
+ streaming_mode: "StreamingMode.NONE",
+ },
+ };
+
+ const output = {
+ content: {
+ parts: [{ text: "Hello!" }],
+ role: "model",
+ },
+ finish_reason: "STOP",
+ };
+
+ const inResult = normalizeInput(input);
+ const outResult = normalizeOutput(output);
+ const allMessages = combineInputOutputMessages(
+ inResult,
+ outResult,
+ cleanLegacyOutput(output, output),
+ );
+
+ expect(inResult.success).toBe(false);
+ expect(allMessages).toHaveLength(0);
+ });
+
+ it("should extract content from Microsoft Agent parts with content field", () => {
+ const input = [
+ {
+ role: "user",
+ parts: [
+ // space behind hello - unsure if it should be added regardless
+ { type: "text", content: "Hello " },
+ { type: "text", content: "World" },
+ ],
+ },
+ ];
+
+ const preprocessed = genericAdapter.preprocess(input, "input", {});
+ expect(Array.isArray(preprocessed)).toBe(true);
+ const messages = preprocessed as any[];
+ expect(messages[0].content).toBe("Hello World");
+ expect(messages[0].parts).toBeUndefined();
+ });
+
+ it("should not crash when parts array contains null items", () => {
+ // Bug: hasFunctionCall/hasFunctionResponse checked properties without null guards
+ const input = [
+ {
+ role: "user",
+ parts: [
+ { type: "text", content: "Hello" },
+ null, // This null item should not crash
+ { type: "text", content: "World" },
+ ],
+ },
+ ];
+
+ // Should not throw TypeError
+ expect(() => genericAdapter.preprocess(input, "input", {})).not.toThrow();
+
+ const preprocessed = genericAdapter.preprocess(input, "input", {});
+ const messages = preprocessed as any[];
+ expect(messages[0].content).toContain("Hello");
+ expect(messages[0].content).toContain("World");
+ });
+
+ it("should not crash when parts has null before function_call", () => {
+ // Test hasFunctionCall code path with null
+ const input = [
+ {
+ role: "assistant",
+ parts: [
+ null, // Null before function check
+ { function_call: { name: "test", arguments: "{}" } },
+ ],
+ },
+ ];
+
+ expect(() => genericAdapter.preprocess(input, "input", {})).not.toThrow();
+ });
+
+ it("should not crash when parts has null before tool_call", () => {
+ // Test Microsoft Agent tool_call type with null
+ const input = [
+ {
+ role: "assistant",
+ parts: [null, { type: "tool_call", id: "123", name: "test" }],
+ },
+ ];
+
+ expect(() => genericAdapter.preprocess(input, "input", {})).not.toThrow();
+ });
+});
diff --git a/web/src/utils/chatml/adapters/langgraph.clienttest.ts b/worker/src/__tests__/chatml/adapters/langgraph.test.ts
similarity index 89%
rename from web/src/utils/chatml/adapters/langgraph.clienttest.ts
rename to worker/src/__tests__/chatml/adapters/langgraph.test.ts
index 8e33dcf49a..7e61015374 100644
--- a/web/src/utils/chatml/adapters/langgraph.clienttest.ts
+++ b/worker/src/__tests__/chatml/adapters/langgraph.test.ts
@@ -1,39 +1,5 @@
-jest.mock("@langfuse/shared", () => {
- const { z } = require("zod/v4");
-
- return {
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
- BaseChatMlMessageSchema: z
- .object({
- role: z.string().optional(),
- name: z.string().optional(),
- content: z
- .union([
- z.record(z.string(), z.any()),
- z.string(),
- z.array(z.any()),
- z.any(), // Simplified - was OpenAIContentSchema
- ])
- .nullish(),
- audio: z.any().optional(),
- additional_kwargs: z.record(z.string(), z.any()).optional(),
- tools: z.array(z.any()).optional(),
- tool_calls: z.array(z.any()).optional(),
- tool_call_id: z.string().optional(),
- })
- .passthrough(),
- };
-});
-
-import { normalizeInput } from "./index";
-import { langgraphAdapter } from "./langgraph";
+import { describe, it, expect } from "vitest";
+import { langgraphAdapter, normalizeInput } from "@langfuse/shared";
describe("LangGraph Adapter", () => {
it("should detect LangGraph via various metadata patterns", () => {
diff --git a/web/src/utils/chatml/adapters/microsoft-agent.clienttest.ts b/worker/src/__tests__/chatml/adapters/microsoft-agent.test.ts
similarity index 86%
rename from web/src/utils/chatml/adapters/microsoft-agent.clienttest.ts
rename to worker/src/__tests__/chatml/adapters/microsoft-agent.test.ts
index f76c4652b2..ab6b4c9441 100644
--- a/web/src/utils/chatml/adapters/microsoft-agent.clienttest.ts
+++ b/worker/src/__tests__/chatml/adapters/microsoft-agent.test.ts
@@ -1,39 +1,31 @@
-jest.mock("@langfuse/shared", () => {
- const { z } = require("zod/v4");
-
- return {
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
- BaseChatMlMessageSchema: z
- .object({
- role: z.string().optional(),
- name: z.string().optional(),
- content: z
- .union([
- z.record(z.string(), z.any()),
- z.string(),
- z.array(z.any()),
- z.any(), // Simplified - was OpenAIContentSchema
- ])
- .nullish(),
- audio: z.any().optional(),
- additional_kwargs: z.record(z.string(), z.any()).optional(),
- tools: z.array(z.any()).optional(),
- tool_calls: z.array(z.any()).optional(),
- tool_call_id: z.string().optional(),
- })
- .passthrough(),
- };
-});
-
-import { normalizeInput, normalizeOutput } from "./index";
-import { microsoftAgentAdapter } from "./microsoft-agent";
+import { describe, it, expect } from "vitest";
+import {
+ microsoftAgentAdapter,
+ selectAdapter,
+ SimpleChatMlArraySchema,
+ type NormalizerContext,
+} from "@langfuse/shared";
+
+// Test helpers
+function normalizeInput(input: unknown, ctx: NormalizerContext = {}) {
+ const adapter = selectAdapter({
+ ...ctx,
+ metadata: ctx.metadata ?? input,
+ data: input,
+ });
+ const preprocessed = adapter.preprocess(input, "input", ctx);
+ return SimpleChatMlArraySchema.safeParse(preprocessed);
+}
+
+function normalizeOutput(output: unknown, ctx: NormalizerContext = {}) {
+ const adapter = selectAdapter({
+ ...ctx,
+ metadata: ctx.metadata ?? output,
+ data: output,
+ });
+ const preprocessed = adapter.preprocess(output, "output", ctx);
+ return SimpleChatMlArraySchema.safeParse(preprocessed);
+}
describe("Microsoft Agent Framework Adapter", () => {
describe("detection", () => {
diff --git a/web/src/utils/chatml/adapters/openai.clienttest.ts b/worker/src/__tests__/chatml/adapters/openai.test.ts
similarity index 92%
rename from web/src/utils/chatml/adapters/openai.clienttest.ts
rename to worker/src/__tests__/chatml/adapters/openai.test.ts
index 6554663c46..3c7c3fa406 100644
--- a/web/src/utils/chatml/adapters/openai.clienttest.ts
+++ b/worker/src/__tests__/chatml/adapters/openai.test.ts
@@ -1,39 +1,9 @@
-jest.mock("@langfuse/shared", () => {
- const { z } = require("zod/v4");
-
- return {
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
- BaseChatMlMessageSchema: z
- .object({
- role: z.string().optional(),
- name: z.string().optional(),
- content: z
- .union([
- z.record(z.string(), z.any()),
- z.string(),
- z.array(z.any()),
- z.any(), // Simplified - was OpenAIContentSchema
- ])
- .nullish(),
- audio: z.any().optional(),
- additional_kwargs: z.record(z.string(), z.any()).optional(),
- tools: z.array(z.any()).optional(),
- tool_calls: z.array(z.any()).optional(),
- tool_call_id: z.string().optional(),
- })
- .passthrough(),
- };
-});
-
-import { normalizeInput, normalizeOutput } from "./index";
-import { openAIAdapter } from "./openai";
+import { describe, it, expect } from "vitest";
+import {
+ openAIAdapter,
+ normalizeInput,
+ normalizeOutput,
+} from "@langfuse/shared";
describe("OpenAI Adapter", () => {
describe("detection", () => {
diff --git a/web/src/utils/chatml/adapters/pydantic-ai.clienttest.ts b/worker/src/__tests__/chatml/adapters/pydantic-ai.test.ts
similarity index 82%
rename from web/src/utils/chatml/adapters/pydantic-ai.clienttest.ts
rename to worker/src/__tests__/chatml/adapters/pydantic-ai.test.ts
index b1839172d0..38a4a6a084 100644
--- a/web/src/utils/chatml/adapters/pydantic-ai.clienttest.ts
+++ b/worker/src/__tests__/chatml/adapters/pydantic-ai.test.ts
@@ -1,38 +1,21 @@
-jest.mock("@langfuse/shared", () => {
- const { z } = require("zod/v4");
+import { describe, it, expect } from "vitest";
+import {
+ pydanticAIAdapter,
+ selectAdapter,
+ SimpleChatMlArraySchema,
+ type NormalizerContext,
+} from "@langfuse/shared";
- return {
- ChatMessageRole: {
- System: "system",
- Developer: "developer",
- User: "user",
- Assistant: "assistant",
- Tool: "tool",
- Model: "model",
- },
- BaseChatMlMessageSchema: z
- .object({
- role: z.string().optional(),
- name: z.string().optional(),
- content: z
- .union([
- z.record(z.string(), z.any()),
- z.string(),
- z.array(z.any()),
- z.any(),
- ])
- .nullish(),
- audio: z.any().optional(),
- additional_kwargs: z.record(z.string(), z.any()).optional(),
- tools: z.array(z.any()).optional(),
- tool_calls: z.array(z.any()).optional(),
- tool_call_id: z.string().optional(),
- })
- .passthrough(),
- };
-});
-
-import { normalizeInput } from "./index";
+// Test helper
+function normalizeInput(input: unknown, ctx: NormalizerContext = {}) {
+ const adapter = selectAdapter({
+ ...ctx,
+ metadata: ctx.metadata ?? input,
+ data: input,
+ });
+ const preprocessed = adapter.preprocess(input, "input", ctx);
+ return SimpleChatMlArraySchema.safeParse(preprocessed);
+}
describe("Pydantic AI Adapter", () => {
describe("detection and parsing", () => {
diff --git a/web/src/utils/chatml/integration.clienttest.ts b/worker/src/__tests__/chatml/integration.test.ts
similarity index 98%
rename from web/src/utils/chatml/integration.clienttest.ts
rename to worker/src/__tests__/chatml/integration.test.ts
index c591c2b680..2a11c7880d 100644
--- a/web/src/utils/chatml/integration.clienttest.ts
+++ b/worker/src/__tests__/chatml/integration.test.ts
@@ -1,4 +1,6 @@
-jest.mock("@langfuse/shared", () => {
+import { describe, it, expect, vi } from "vitest";
+
+vi.mock("@langfuse/shared", () => {
const { z } = require("zod/v4");
return {
@@ -32,12 +34,13 @@ jest.mock("@langfuse/shared", () => {
};
});
-import { normalizeInput, normalizeOutput } from "./adapters";
import {
+ normalizeInput,
+ normalizeOutput,
combineInputOutputMessages,
cleanLegacyOutput,
extractAdditionalInput,
-} from "./core";
+} from "@langfuse/shared/src/utils/chatml";
describe("ChatML Integration", () => {
it("should handle OpenAI multimodal format", () => {
diff --git a/worker/src/__tests__/extractToolsBackend.test.ts b/worker/src/__tests__/extractToolsBackend.test.ts
new file mode 100644
index 0000000000..805a12a15a
--- /dev/null
+++ b/worker/src/__tests__/extractToolsBackend.test.ts
@@ -0,0 +1,840 @@
+import { describe, it, expect } from "vitest";
+import {
+ extractToolsFromObservation,
+ convertDefinitionsToMap,
+ convertCallsToArrays,
+} from "@langfuse/shared/src/server";
+
+describe("extractToolsFromObservation", () => {
+ describe("Tool Definitions extraction", () => {
+ it("extracts OpenAI format tools from input", () => {
+ const input = {
+ tools: [
+ {
+ type: "function",
+ function: {
+ name: "get_weather",
+ description: "Get current weather",
+ parameters: {
+ type: "object",
+ properties: { location: { type: "string" } },
+ },
+ },
+ },
+ ],
+ };
+
+ const { toolDefinitions } = extractToolsFromObservation(input, null);
+
+ expect(toolDefinitions).toHaveLength(1);
+ expect(toolDefinitions[0]).toEqual({
+ name: "get_weather",
+ description: "Get current weather",
+ parameters: JSON.stringify({
+ type: "object",
+ properties: { location: { type: "string" } },
+ }),
+ });
+ });
+
+ it("extracts tools from messages array", () => {
+ const input = {
+ messages: [
+ {
+ role: "user",
+ content: "test",
+ tools: [
+ {
+ name: "search",
+ description: "Search database",
+ },
+ ],
+ },
+ ],
+ };
+
+ const { toolDefinitions } = extractToolsFromObservation(input, null);
+
+ expect(toolDefinitions).toHaveLength(1);
+ expect(toolDefinitions[0].name).toBe("search");
+ });
+
+ it.skip("extracts tools from OTel metadata attributes", () => {
+ // TODO: Re-enable when OTel processor maps gen_ai.tool.definitions → input.tools
+ const metadata = {
+ attributes: {
+ "gen_ai.tool.definitions": [
+ {
+ name: "calculator",
+ description: "Do math",
+ parameters: { type: "object" },
+ },
+ ],
+ },
+ };
+
+ const { toolDefinitions } = extractToolsFromObservation(
+ null,
+ null,
+ metadata,
+ );
+
+ expect(toolDefinitions).toHaveLength(1);
+ expect(toolDefinitions[0].name).toBe("calculator");
+ });
+
+ it.skip("extracts tools from OTel indexed format", () => {
+ // TODO: Re-enable when OTel processor maps llm.tools.*.tool.json_schema → input.tools
+ const metadata = {
+ attributes: {
+ "llm.tools.0.tool.json_schema": {
+ name: "tool1",
+ description: "First tool",
+ },
+ "llm.tools.1.tool.json_schema": {
+ name: "tool2",
+ description: "Second tool",
+ },
+ },
+ };
+
+ const { toolDefinitions } = extractToolsFromObservation(
+ null,
+ null,
+ metadata,
+ );
+
+ expect(toolDefinitions).toHaveLength(2);
+ expect(toolDefinitions.map((t) => t.name)).toEqual(["tool1", "tool2"]);
+ });
+
+ it("returns empty array for input without tools", () => {
+ const input = { messages: [{ role: "user", content: "hi" }] };
+
+ const { toolDefinitions } = extractToolsFromObservation(input, null);
+
+ expect(toolDefinitions).toEqual([]);
+ });
+
+ it("deduplicates tools by name", () => {
+ const input = {
+ messages: [
+ { tools: [{ name: "search" }] },
+ { tools: [{ name: "search" }] }, // duplicate
+ ],
+ };
+
+ const { toolDefinitions } = extractToolsFromObservation(input, null);
+
+ expect(toolDefinitions).toHaveLength(1);
+ });
+
+ it("extracts tools from LangGraph role:tool message content", () => {
+ const input = [
+ { role: "user", content: "Search for something" },
+ {
+ role: "tool",
+ content: {
+ type: "function",
+ function: {
+ name: "web_search",
+ description: "Search the web",
+ parameters: {
+ type: "object",
+ properties: { query: { type: "string" } },
+ },
+ },
+ },
+ },
+ ];
+
+ const { toolDefinitions } = extractToolsFromObservation(input, null);
+
+ expect(toolDefinitions).toHaveLength(1);
+ expect(toolDefinitions[0].name).toBe("web_search");
+ expect(toolDefinitions[0].description).toBe("Search the web");
+ });
+ });
+
+ describe("Tool Arguments extraction", () => {
+ it("extracts flat tool_calls from output", () => {
+ const output = {
+ tool_calls: [
+ {
+ id: "call_123",
+ name: "get_weather",
+ arguments: '{"location": "Boston"}',
+ type: "function",
+ index: 0,
+ },
+ ],
+ };
+
+ const { toolArguments } = extractToolsFromObservation(null, output);
+
+ expect(toolArguments).toHaveLength(1);
+ expect(toolArguments[0]).toEqual({
+ id: "call_123",
+ name: "get_weather",
+ arguments: '{"location": "Boston"}',
+ type: "function",
+ index: 0,
+ });
+ });
+
+ it("extracts tool_calls from OpenAI choices response", () => {
+ const output = {
+ choices: [
+ {
+ message: {
+ tool_calls: [
+ {
+ id: "call_abc",
+ type: "function",
+ function: {
+ name: "search",
+ arguments: '{"query": "test"}',
+ },
+ },
+ ],
+ },
+ },
+ ],
+ };
+
+ const { toolArguments } = extractToolsFromObservation(null, output);
+
+ expect(toolArguments).toHaveLength(1);
+ expect(toolArguments[0]).toMatchObject({
+ id: "call_abc",
+ name: "search",
+ arguments: '{"query": "test"}',
+ type: "function",
+ });
+ });
+
+ it("extracts Anthropic tool_use from content array", () => {
+ const output = {
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_123",
+ name: "get_weather",
+ input: { location: "NYC" },
+ },
+ ],
+ };
+
+ const { toolArguments } = extractToolsFromObservation(null, output);
+
+ expect(toolArguments).toHaveLength(1);
+ expect(toolArguments[0]).toEqual({
+ id: "toolu_123",
+ name: "get_weather",
+ arguments: JSON.stringify({ location: "NYC" }),
+ type: "tool_use",
+ });
+ });
+
+ it("extracts LangChain additional_kwargs tool_calls", () => {
+ const output = {
+ additional_kwargs: {
+ tool_calls: [
+ {
+ id: "call_xyz",
+ name: "calculator",
+ arguments: { operation: "add" },
+ },
+ ],
+ },
+ };
+
+ const { toolArguments } = extractToolsFromObservation(null, output);
+
+ expect(toolArguments).toHaveLength(1);
+ expect(toolArguments[0].name).toBe("calculator");
+ expect(toolArguments[0].arguments).toBe(
+ JSON.stringify({ operation: "add" }),
+ );
+ });
+
+ it("extracts from array of messages with tool_calls", () => {
+ const output = [
+ { role: "user", content: "hi" },
+ {
+ role: "assistant",
+ tool_calls: [{ id: "c1", name: "tool1", arguments: "{}" }],
+ },
+ ];
+
+ const { toolArguments } = extractToolsFromObservation(null, output);
+
+ expect(toolArguments).toHaveLength(1);
+ expect(toolArguments[0].name).toBe("tool1");
+ });
+
+ it("handles Vercel AI SDK format (toolCallId, toolName, args)", () => {
+ const output = {
+ tool_calls: [
+ {
+ toolCallId: "call_123",
+ toolName: "search",
+ args: { query: "test" },
+ },
+ ],
+ };
+
+ const { toolArguments } = extractToolsFromObservation(null, output);
+
+ expect(toolArguments).toHaveLength(1);
+ expect(toolArguments[0]).toMatchObject({
+ id: "call_123",
+ name: "search",
+ arguments: JSON.stringify({ query: "test" }),
+ });
+ });
+
+ it("preserves index field for parallel tool calls", () => {
+ const output = {
+ tool_calls: [
+ { id: "c1", name: "tool1", arguments: "{}", index: 0 },
+ { id: "c2", name: "tool2", arguments: "{}", index: 1 },
+ ],
+ };
+
+ const { toolArguments } = extractToolsFromObservation(null, output);
+
+ expect(toolArguments).toHaveLength(2);
+ expect(toolArguments[0].index).toBe(0);
+ expect(toolArguments[1].index).toBe(1);
+ });
+
+ it("returns empty array for output without tool_calls", () => {
+ const output = { role: "assistant", content: "Hello" };
+
+ const { toolArguments } = extractToolsFromObservation(null, output);
+
+ expect(toolArguments).toEqual([]);
+ });
+ });
+
+ describe("Error handling", () => {
+ it("returns empty arrays on malformed input (no throw)", () => {
+ const malformed = { tools: "not an array" };
+
+ expect(() => extractToolsFromObservation(malformed, null)).not.toThrow();
+
+ const result = extractToolsFromObservation(malformed, null);
+ expect(result.toolDefinitions).toEqual([]);
+ });
+
+ it("handles null/undefined gracefully", () => {
+ const result = extractToolsFromObservation(null, undefined);
+
+ expect(result.toolDefinitions).toEqual([]);
+ expect(result.toolArguments).toEqual([]);
+ });
+
+ it("parses JSON string input and extracts tools", () => {
+ const input = JSON.stringify([
+ { role: "user", content: "hi" },
+ {
+ role: "tool",
+ content: {
+ type: "function",
+ function: {
+ name: "search",
+ description: "Search function",
+ },
+ },
+ },
+ ]);
+
+ const { toolDefinitions } = extractToolsFromObservation(input, null);
+
+ expect(toolDefinitions).toHaveLength(1);
+ expect(toolDefinitions[0].name).toBe("search");
+ });
+
+ it("parses JSON string output and extracts tool calls", () => {
+ const output = JSON.stringify({
+ tool_calls: [{ id: "c1", name: "get_weather", args: { city: "NYC" } }],
+ });
+
+ const { toolArguments } = extractToolsFromObservation(null, output);
+
+ expect(toolArguments).toHaveLength(1);
+ expect(toolArguments[0].name).toBe("get_weather");
+ });
+
+ it("handles circular references gracefully", () => {
+ const circular: any = { tools: [] };
+ circular.tools.push(circular);
+
+ expect(() => extractToolsFromObservation(circular, null)).not.toThrow();
+ });
+
+ it("filters out invalid tool definitions (missing name)", () => {
+ const input = {
+ tools: [
+ { function: { name: "valid_tool" } },
+ { function: { description: "no name" } }, // invalid
+ ],
+ };
+
+ const { toolDefinitions } = extractToolsFromObservation(input, null);
+
+ expect(toolDefinitions).toHaveLength(1);
+ expect(toolDefinitions[0].name).toBe("valid_tool");
+ });
+
+ it("filters out invalid tool calls (missing name)", () => {
+ const output = {
+ tool_calls: [
+ { id: "c1", name: "valid_call", arguments: "{}" },
+ { id: "c2", arguments: "{}" }, // invalid - no name
+ ],
+ };
+
+ const { toolArguments } = extractToolsFromObservation(null, output);
+
+ expect(toolArguments).toHaveLength(1);
+ expect(toolArguments[0].name).toBe("valid_call");
+ });
+ });
+
+ describe("Combined extraction", () => {
+ it("extracts both definitions and arguments in single call", () => {
+ const input = {
+ tools: [{ name: "calculator", description: "Do math" }],
+ };
+ const output = {
+ tool_calls: [{ id: "c1", name: "calculator", arguments: "{}" }],
+ };
+
+ const result = extractToolsFromObservation(input, output);
+
+ expect(result.toolDefinitions).toHaveLength(1);
+ expect(result.toolArguments).toHaveLength(1);
+ expect(result.toolDefinitions[0].name).toBe("calculator");
+ expect(result.toolArguments[0].name).toBe("calculator");
+ });
+ });
+
+ describe("real world data tests", () => {
+ it("should extract LangGraph tool definitions and tool calls and parse them correctly", () => {
+ // Exact format from user's observation that wasn't being extracted
+ const input = [
+ {
+ role: "system",
+ content:
+ "You are a creative joke writer. Select and call THREE of the available tools to get joke suggestions about 'programming'.",
+ },
+ {
+ role: "user",
+ content: "Generate a joke about programming",
+ },
+ {
+ role: "tool",
+ content: {
+ type: "function",
+ function: {
+ name: "get_pun_suggestion",
+ description:
+ "Get a pun-style joke suggestion for the given topic.\n\nArgs:\n topic: The topic for the joke",
+ parameters: {
+ properties: { topic: { type: "string" } },
+ required: ["topic"],
+ type: "object",
+ },
+ },
+ },
+ },
+ {
+ role: "tool",
+ content: {
+ type: "function",
+ function: {
+ name: "get_dad_joke_suggestion",
+ description:
+ "Get a dad joke style suggestion for the given topic.\n\nArgs:\n topic: The topic for the joke",
+ parameters: {
+ properties: { topic: { type: "string" } },
+ required: ["topic"],
+ type: "object",
+ },
+ },
+ },
+ },
+ {
+ role: "tool",
+ content: {
+ type: "function",
+ function: {
+ name: "get_one_liner_suggestion",
+ description:
+ "Get a one-liner joke suggestion for the given topic.\n\nArgs:\n topic: The topic for the joke",
+ parameters: {
+ properties: { topic: { type: "string" } },
+ required: ["topic"],
+ type: "object",
+ },
+ },
+ },
+ },
+ ];
+
+ const output = {
+ role: "assistant",
+ content: "",
+ tool_calls: [
+ {
+ name: "get_pun_suggestion",
+ args: { topic: "programming" },
+ id: "call_mock_1",
+ type: "tool_call",
+ },
+ {
+ name: "get_dad_joke_suggestion",
+ args: { topic: "programming" },
+ id: "call_mock_2",
+ type: "tool_call",
+ },
+ {
+ name: "get_one_liner_suggestion",
+ args: { topic: "programming" },
+ id: "call_mock_3",
+ type: "tool_call",
+ },
+ ],
+ additional_kwargs: { refusal: null },
+ };
+
+ const result = extractToolsFromObservation(input, output);
+
+ // Should extract 3 tool definitions from role:tool messages
+ expect(result.toolDefinitions).toHaveLength(3);
+ expect(result.toolDefinitions.map((t) => t.name)).toEqual([
+ "get_pun_suggestion",
+ "get_dad_joke_suggestion",
+ "get_one_liner_suggestion",
+ ]);
+
+ // Should extract 3 tool calls from output.tool_calls
+ expect(result.toolArguments).toHaveLength(3);
+ expect(result.toolArguments.map((t) => t.name)).toEqual([
+ "get_pun_suggestion",
+ "get_dad_joke_suggestion",
+ "get_one_liner_suggestion",
+ ]);
+
+ // Verify tool call structure
+ expect(result.toolArguments[0]).toMatchObject({
+ id: "call_mock_1",
+ name: "get_pun_suggestion",
+ type: "tool_call",
+ });
+ expect(result.toolArguments[0].arguments).toBe(
+ JSON.stringify({ topic: "programming" }),
+ );
+ });
+
+ it("should extract tools from OpenAI format (tools in input.tools)", () => {
+ const input = {
+ tools: [
+ {
+ type: "function",
+ function: {
+ name: "get_weather",
+ description: "Get current weather",
+ parameters: {
+ type: "object",
+ properties: { location: { type: "string" } },
+ required: ["location"],
+ },
+ },
+ },
+ {
+ type: "function",
+ function: {
+ name: "search_web",
+ description: "Search",
+ },
+ },
+ ],
+ messages: [{ role: "user", content: "Weather in NYC?" }],
+ };
+
+ const output = {
+ model: "gpt-4",
+ choices: [
+ {
+ message: {
+ role: "assistant",
+ tool_calls: [
+ {
+ id: "call_123",
+ type: "function",
+ function: {
+ name: "get_weather",
+ arguments: '{"location":"NYC"}',
+ },
+ },
+ ],
+ },
+ },
+ ],
+ };
+
+ const result = extractToolsFromObservation(input, output);
+
+ expect(result.toolDefinitions).toHaveLength(2);
+ expect(result.toolDefinitions.map((t) => t.name)).toEqual([
+ "get_weather",
+ "search_web",
+ ]);
+ expect(result.toolArguments).toHaveLength(1);
+ expect(result.toolArguments[0].name).toBe("get_weather");
+ expect(result.toolArguments[0].id).toBe("call_123");
+ expect(result.toolArguments[0].arguments).toBe('{"location":"NYC"}');
+ });
+
+ it.skip("should extract tool definitions from OTel metadata structure i.e. pydantic-ai", () => {
+ // TODO: Re-enable when OTel processor maps metadata.attributes.model_request_parameters.function_tools → input.tools
+ const metadata = {
+ attributes: {
+ "gen_ai.operation.name": "chat",
+ "gen_ai.system": "openai",
+ "gen_ai.request.model": "gpt-4o-mini",
+ model_request_parameters: {
+ function_tools: [
+ {
+ name: "get_pun_suggestion",
+ parameters_json_schema: {
+ type: "object",
+ properties: { topic: { type: "string" } },
+ required: ["topic"],
+ },
+ description:
+ "Get a pun-style joke suggestion for the given topic.",
+ },
+ {
+ name: "get_dad_joke_suggestion",
+ parameters_json_schema: {
+ type: "object",
+ properties: { topic: { type: "string" } },
+ },
+ description:
+ "Get a dad joke style suggestion for the given topic.",
+ },
+ {
+ name: "get_one_liner_suggestion",
+ description:
+ "Get a one-liner joke suggestion for the given topic.",
+ },
+ ],
+ },
+ },
+ scope: {
+ name: "pydantic-ai",
+ version: "1.26.0",
+ },
+ };
+
+ const input = [
+ {
+ role: "system",
+ parts: [{ type: "text", content: "You are a creative joke writer." }],
+ },
+ {
+ role: "user",
+ parts: [
+ { type: "text", content: "Tell me a joke about programming." },
+ ],
+ },
+ ];
+
+ const output = {
+ role: "assistant",
+ tool_calls: [
+ {
+ id: "call_1",
+ name: "get_pun_suggestion",
+ arguments: '{"topic":"programming"}',
+ },
+ {
+ id: "call_2",
+ name: "get_dad_joke_suggestion",
+ arguments: '{"topic":"programming"}',
+ },
+ ],
+ };
+
+ // Also test with explicit framework hint
+ const result = extractToolsFromObservation(input, output, metadata);
+
+ // Should extract 3 available tools
+ expect(result.toolDefinitions).toHaveLength(3);
+ expect(result.toolDefinitions.map((t) => t.name)).toEqual([
+ "get_pun_suggestion",
+ "get_dad_joke_suggestion",
+ "get_one_liner_suggestion",
+ ]);
+
+ // Should extract 2 called tools
+ expect(result.toolArguments).toHaveLength(2);
+ expect(result.toolArguments.map((t) => t.name)).toEqual([
+ "get_pun_suggestion",
+ "get_dad_joke_suggestion",
+ ]);
+ });
+ });
+
+ describe("Transformation functions", () => {
+ describe("convertDefinitionsToMap", () => {
+ it("converts array to map format", () => {
+ const defs = [
+ { name: "get_weather", description: "Get weather", parameters: "{}" },
+ { name: "search", description: "Search" },
+ ];
+ const map = convertDefinitionsToMap(defs);
+
+ expect(Object.keys(map)).toEqual(["get_weather", "search"]);
+ expect(JSON.parse(map["get_weather"])).toEqual({
+ description: "Get weather",
+ parameters: "{}",
+ });
+ expect(JSON.parse(map["search"])).toEqual({
+ description: "Search",
+ parameters: "",
+ });
+ });
+
+ it("returns empty map for empty array", () => {
+ expect(convertDefinitionsToMap([])).toEqual({});
+ });
+
+ it("handles missing optional fields with empty strings", () => {
+ const defs = [{ name: "test_tool" }];
+ const map = convertDefinitionsToMap(defs);
+
+ expect(JSON.parse(map["test_tool"])).toEqual({
+ description: "",
+ parameters: "",
+ });
+ });
+ });
+
+ describe("convertCallsToArrays", () => {
+ it("converts calls to parallel arrays", () => {
+ const calls = [
+ {
+ id: "c1",
+ name: "get_weather",
+ arguments: '{"city":"NYC"}',
+ type: "function",
+ index: 0,
+ },
+ {
+ id: "c2",
+ name: "search",
+ arguments: '{"q":"test"}',
+ type: "function",
+ index: 1,
+ },
+ {
+ id: "c3",
+ name: "get_weather",
+ arguments: '{"city":"LA"}',
+ type: "function",
+ index: 2,
+ },
+ ];
+ const { tool_calls, tool_call_names } = convertCallsToArrays(calls);
+
+ // Names array should match the order of calls
+ expect(tool_call_names).toEqual([
+ "get_weather",
+ "search",
+ "get_weather",
+ ]);
+ expect(tool_calls).toHaveLength(3);
+
+ // Verify JSON structure (should NOT include name)
+ const call1 = JSON.parse(tool_calls[0]);
+ expect(call1).toEqual({
+ id: "c1",
+ arguments: '{"city":"NYC"}',
+ type: "function",
+ index: 0,
+ });
+ });
+
+ it("returns empty arrays for empty input", () => {
+ const result = convertCallsToArrays([]);
+ expect(result.tool_calls).toEqual([]);
+ expect(result.tool_call_names).toEqual([]);
+ });
+
+ it("handles missing optional fields with defaults", () => {
+ const calls = [{ id: "c1", name: "test_tool", arguments: "" }];
+ const { tool_calls, tool_call_names } = convertCallsToArrays(calls);
+
+ expect(tool_call_names).toEqual(["test_tool"]);
+ const call = JSON.parse(tool_calls[0]);
+ expect(call).toEqual({
+ id: "c1",
+ arguments: "",
+ type: "",
+ index: 0,
+ });
+ });
+
+ it("preserves order for multiple calls to same tool", () => {
+ const calls = [
+ {
+ id: "c1",
+ name: "tool1",
+ arguments: "{}",
+ type: "function",
+ index: 0,
+ },
+ {
+ id: "c2",
+ name: "tool1",
+ arguments: "{}",
+ type: "function",
+ index: 1,
+ },
+ {
+ id: "c3",
+ name: "tool1",
+ arguments: "{}",
+ type: "function",
+ index: 2,
+ },
+ ];
+ const { tool_calls, tool_call_names } = convertCallsToArrays(calls);
+
+ expect(tool_call_names).toEqual(["tool1", "tool1", "tool1"]);
+ expect(tool_calls).toHaveLength(3);
+ });
+
+ it("maintains parallel array correspondence", () => {
+ const calls = [
+ { id: "c1", name: "alpha", arguments: '{"a":1}' },
+ { id: "c2", name: "beta", arguments: '{"b":2}' },
+ { id: "c3", name: "alpha", arguments: '{"a":3}' },
+ ];
+ const { tool_calls, tool_call_names } = convertCallsToArrays(calls);
+
+ // Verify each index corresponds correctly
+ for (let i = 0; i < calls.length; i++) {
+ expect(tool_call_names[i]).toBe(calls[i].name);
+ const parsed = JSON.parse(tool_calls[i]);
+ expect(parsed.id).toBe(calls[i].id);
+ }
+ });
+ });
+ });
+});
diff --git a/worker/src/features/database-read-stream/observation-stream.ts b/worker/src/features/database-read-stream/observation-stream.ts
index 8dba48f66f..8a3ba7b830 100644
--- a/worker/src/features/database-read-stream/observation-stream.ts
+++ b/worker/src/features/database-read-stream/observation-stream.ts
@@ -359,6 +359,8 @@ export const getObservationStream = async (props: {
traceTags: bufferedRow.traceTags,
traceTimestamp: bufferedRow.traceTimestamp,
userId: bufferedRow.userId,
+ toolDefinitionsCount: null,
+ toolCallsCount: null,
...modelData,
scores: outputScores,
comments: observationComments,
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 7af64eff5d..2f4c434f8f 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -46,6 +46,9 @@ import {
traceException,
flattenJsonToPathArrays,
getDatasetItemById,
+ extractToolsFromObservation,
+ convertDefinitionsToMap,
+ convertCallsToArrays,
} from "@langfuse/shared/src/server";
import { tokenCountAsync } from "../../features/tokenisation/async-usage";
@@ -865,6 +868,35 @@ export class IngestionService {
clickhouseObservationRecord?.output,
);
+ // Extract tool definitions and calls from raw input/output
+ try {
+ const rawInput = reversedRawRecords.find((record) => record?.body?.input)
+ ?.body?.input;
+ const rawOutput = reversedRawRecords.find(
+ (record) => record?.body?.output,
+ )?.body?.output;
+
+ const { toolDefinitions, toolArguments } = extractToolsFromObservation(
+ rawInput,
+ rawOutput,
+ );
+
+ if (toolDefinitions.length > 0) {
+ mergedObservationRecord.tool_definitions =
+ convertDefinitionsToMap(toolDefinitions);
+ }
+
+ if (toolArguments.length > 0) {
+ const { tool_calls, tool_call_names } =
+ convertCallsToArrays(toolArguments);
+ mergedObservationRecord.tool_calls = tool_calls;
+ mergedObservationRecord.tool_call_names = tool_call_names;
+ }
+ } catch (error) {
+ logger.error("Tool extraction failed", { error, projectId, entityId });
+ // Don't fail ingestion - just skip tool data
+ }
+
const generationUsage = await this.getGenerationUsage({
projectId,
observationRecord: mergedObservationRecord,