🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(tool-calls): parse available tools and map them to input object (#13594)
Nimar1ede00d88d31
diff --git a/packages/shared/src/server/ingestion/extractToolsBackend.ts b/packages/shared/src/server/ingestion/extractToolsBackend.tsindex 3f0c868559..6678767857 100644--- a/packages/shared/src/server/ingestion/extractToolsBackend.ts+++ b/packages/shared/src/server/ingestion/extractToolsBackend.ts@@ -1,5 +1,7 @@import { z } from "zod";+type IngestionJsonValue = string | object | number | boolean | null | undefined;+/*** ClickHouse storage schema for tool definitions.*@@ -43,6 +45,14 @@ function flattenToolDefinition(tool: unknown): {description?: string;parameters?: unknown;} {+ if (typeof tool === "string") {+ try {+ tool = JSON.parse(tool);+ } catch {+ return {};+ }+ }+if (!tool || typeof tool !== "object") return {};const t = tool as Record<string, unknown>;@@ -380,6 +390,345 @@ function parseIfString(data: unknown): unknown {return data;}+function isPlainRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function parsePlainRecord(value: unknown): Record<string, unknown> | undefined {+ const parsed = parseIfString(value);+ return isPlainRecord(parsed) ? parsed : undefined;+}++const TOOL_METADATA_ATTRIBUTE_KEY_PATTERN =+ /"(?:ai\.prompt\.tools|gen_ai\.tool\.definitions|model_request_parameters|llm\.tools\.\d+\.tool\.json_schema)"\s*:/;++function parseMetadataAttributes(+ value: unknown,+): Record<string, unknown> | undefined {+ if (typeof value === "string") {+ if (!TOOL_METADATA_ATTRIBUTE_KEY_PATTERN.test(value)) {+ return undefined;+ }+ }++ return parsePlainRecord(value);+}++function toIngestionJsonValue(value: unknown): IngestionJsonValue {+ if (value == null) return value;++ const valueType = typeof value;+ return valueType === "string" ||+ valueType === "number" ||+ valueType === "boolean" ||+ valueType === "object"+ ? (value as IngestionJsonValue)+ : undefined;+}++function isToolDefinitionLike(tool: unknown): boolean {+ return Boolean(flattenToolDefinition(tool).name);+}++function isToolMetadataEntryLike(+ tool: unknown,+ options: { allowProviderToolWithoutName?: boolean } = {},+): boolean {+ const parsedTool = parseIfString(tool);+ if (!isPlainRecord(parsedTool)) return false;+ if (isToolDefinitionLike(parsedTool)) return true;++ return (+ options.allowProviderToolWithoutName === true &&+ typeof parsedTool.type === "string"+ );+}++function parseToolDefinitionArray(+ tools: unknown,+ options: {+ requireEveryItem?: boolean;+ allowProviderToolWithoutName?: boolean;+ } = {},+): unknown[] | undefined {+ const parsedTools = parseArrayIfString(tools);+ if (!parsedTools) return undefined;++ const normalizedTools = parsedTools.map(parseIfString);+ if (normalizedTools.length === 0) return [];++ const toolLikeEntries = normalizedTools.filter((tool) =>+ isToolMetadataEntryLike(tool, {+ allowProviderToolWithoutName:+ options.allowProviderToolWithoutName ?? true,+ }),+ );+ if (+ options.requireEveryItem &&+ toolLikeEntries.length !== normalizedTools.length+ ) {+ return undefined;+ }++ return toolLikeEntries.length > 0 ? toolLikeEntries : undefined;+}++type ToolDefinitionArrayOptions = Parameters<+ typeof parseToolDefinitionArray+>[1];++function dedupeToolDefinitions(tools: unknown[]): unknown[] {+ const seenToolNames = new Set<string>();+ return tools.filter((tool) => {+ const name = flattenToolDefinition(tool).name;+ if (!name) return true;+ if (seenToolNames.has(name)) return false;+ seenToolNames.add(name);+ return true;+ });+}++function collectAndRemoveToolDefinitionsFromMetadata(+ metadata: Record<string, unknown>,+): { tools: unknown[]; metadata: Record<string, unknown> } {+ let tools: unknown[] = [];+ const cleanedMetadata = { ...metadata };+ const addTools = (+ value: unknown,+ options: ToolDefinitionArrayOptions = {},+ ) => {+ const parsedTools = parseToolDefinitionArray(value, options);+ if (!parsedTools) return false;++ tools = tools.concat(parsedTools);+ return true;+ };++ const metadataTools = parseToolDefinitionArray(metadata.tools, {+ requireEveryItem: true,+ allowProviderToolWithoutName: false,+ });+ if (metadataTools && metadataTools.length > 0) {+ tools = tools.concat(metadataTools);+ delete cleanedMetadata.tools;+ }++ const attributes = parseMetadataAttributes(metadata.attributes);++ if (!attributes) {+ return { tools: dedupeToolDefinitions(tools), metadata: cleanedMetadata };+ }++ const cleanedAttributes = { ...attributes };++ if (+ addTools(attributes["ai.prompt.tools"], {+ requireEveryItem: true,+ allowProviderToolWithoutName: true,+ })+ ) {+ delete cleanedAttributes["ai.prompt.tools"];+ }++ if (+ addTools(attributes["gen_ai.tool.definitions"], {+ requireEveryItem: true,+ allowProviderToolWithoutName: false,+ })+ ) {+ delete cleanedAttributes["gen_ai.tool.definitions"];+ }++ const modelRequestParameters = parseIfString(+ attributes.model_request_parameters,+ );+ if (isPlainRecord(modelRequestParameters)) {+ const movedFunctionTools = addTools(modelRequestParameters.function_tools, {+ requireEveryItem: true,+ allowProviderToolWithoutName: false,+ });++ const cleanedModelRequestParameters = { ...modelRequestParameters };+ if (movedFunctionTools) {+ delete cleanedModelRequestParameters.function_tools;+ }++ if (Object.keys(cleanedModelRequestParameters).length > 0) {+ cleanedAttributes.model_request_parameters =+ typeof attributes.model_request_parameters === "string"+ ? JSON.stringify(cleanedModelRequestParameters)+ : cleanedModelRequestParameters;+ } else {+ delete cleanedAttributes.model_request_parameters;+ }+ }++ const indexedToolKeys = Object.keys(attributes)+ .map((key) => ({+ key,+ match: /^llm\.tools\.(\d+)\.tool\.json_schema$/.exec(key),+ }))+ .filter(+ (entry): entry is { key: string; match: RegExpExecArray } =>+ entry.match !== null,+ )+ .sort((left, right) => Number(left.match[1]) - Number(right.match[1]));++ for (const { key } of indexedToolKeys) {+ const parsedTool = parseIfString(attributes[key]);+ if (+ isToolMetadataEntryLike(parsedTool, {+ allowProviderToolWithoutName: false,+ })+ ) {+ tools.push(parsedTool);+ delete cleanedAttributes[key];+ }+ }++ if (Object.keys(cleanedAttributes).length > 0) {+ cleanedMetadata.attributes = cleanedAttributes;+ } else {+ delete cleanedMetadata.attributes;+ }++ return { tools: dedupeToolDefinitions(tools), metadata: cleanedMetadata };+}++function appendToolsToInput(+ input: unknown,+ tools: unknown[],+): {+ input: IngestionJsonValue;+ mapped: boolean;+ inputForExtraction?: unknown;+} {+ const mergeTools = (+ value: unknown,+ ): {+ input: IngestionJsonValue;+ mapped: boolean;+ inputForExtraction?: unknown;+ } => {+ if (Array.isArray(value)) {+ const mergedInput = { messages: value, tools };+ return {+ input: mergedInput,+ mapped: true,+ inputForExtraction: mergedInput,+ };+ }++ if (isPlainRecord(value)) {+ if (value.tools != null) {+ const existingTools = parseToolDefinitionArray(value.tools);++ if (!existingTools) {+ return { input: toIngestionJsonValue(input), mapped: false };+ }++ const mergedInput = {+ ...value,+ tools: dedupeToolDefinitions(existingTools.concat(tools)),+ };+ return {+ input: mergedInput,+ mapped: true,+ inputForExtraction: mergedInput,+ };+ }++ const mergedInput = { ...value, tools };+ return {+ input: mergedInput,+ mapped: true,+ inputForExtraction: mergedInput,+ };+ }++ if (value == null) {+ const mergedInput = { tools };+ return {+ input: mergedInput,+ mapped: true,+ inputForExtraction: mergedInput,+ };+ }++ if (typeof value === "string") {+ const mergedInput = { prompt: value, tools };+ return {+ input: mergedInput,+ mapped: true,+ inputForExtraction: mergedInput,+ };+ }++ return { input: toIngestionJsonValue(input), mapped: false };+ };++ if (typeof input === "string") {+ try {+ const merged = mergeTools(JSON.parse(input));+ return {+ input: merged.mapped ? merged.input : input,+ mapped: merged.mapped,+ inputForExtraction: merged.inputForExtraction,+ };+ } catch {+ const mergedInput = { prompt: input, tools };+ return {+ input: mergedInput,+ mapped: true,+ inputForExtraction: mergedInput,+ };+ }+ }++ return mergeTools(input);+}++export function normalizeToolMetadataForObservation(+ input: unknown,+ metadata: unknown,+): {+ input: IngestionJsonValue;+ metadata: IngestionJsonValue;+ inputForExtraction?: unknown;+} {+ const parsedMetadata = parseIfString(metadata);+ if (!isPlainRecord(parsedMetadata)) {+ return {+ input: toIngestionJsonValue(input),+ metadata: toIngestionJsonValue(metadata),+ };+ }++ const normalizedMetadata =+ collectAndRemoveToolDefinitionsFromMetadata(parsedMetadata);+ const { tools } = normalizedMetadata;+ if (tools.length === 0) {+ return {+ input: toIngestionJsonValue(input),+ metadata: toIngestionJsonValue(metadata),+ };+ }++ const mappedInput = appendToolsToInput(input, tools);+ if (!mappedInput.mapped) {+ return {+ input: toIngestionJsonValue(input),+ metadata: toIngestionJsonValue(metadata),+ };+ }++ return {+ input: mappedInput.input,+ metadata: normalizedMetadata.metadata,+ inputForExtraction: mappedInput.inputForExtraction,+ };+}+/*** Extract tool definitions and arguments from observation input/output.* Extracts directly from raw input/output formats.@@ -396,31 +745,88 @@ export function extractToolsFromObservation(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 };+ return extractToolsFromParsedObservation(+ parseIfString(input),+ parseIfString(output),+ );} catch (error) {console.error("Tool extraction error:", error);return { toolDefinitions: [], toolArguments: [] };}}+function extractToolsFromParsedObservation(+ parsedInput: unknown,+ parsedOutput: unknown,+): {+ toolDefinitions: ClickhouseToolDefinition[];+ toolArguments: ClickhouseToolArgument[];+} {+ const toolDefinitions: ClickhouseToolDefinition[] = [];+ const toolArguments: ClickhouseToolArgument[] = [];++ 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 };+}++export function normalizeToolsForObservation(+ input: unknown,+ output: unknown,+ metadata: unknown,+): {+ input: IngestionJsonValue;+ output: IngestionJsonValue;+ metadata: IngestionJsonValue;+ toolDefinitions: Record<string, string>;+ toolCalls: string[];+ toolCallNames: string[];+} {+ const normalizedToolInput = normalizeToolMetadataForObservation(+ input,+ metadata,+ );++ try {+ const { toolDefinitions, toolArguments } =+ extractToolsFromParsedObservation(+ normalizedToolInput.inputForExtraction ??+ parseIfString(normalizedToolInput.input),+ parseIfString(output),+ );+ const { tool_calls, tool_call_names } = convertCallsToArrays(toolArguments);++ return {+ input: normalizedToolInput.input,+ output: toIngestionJsonValue(output),+ metadata: normalizedToolInput.metadata,+ toolDefinitions: convertDefinitionsToMap(toolDefinitions),+ toolCalls: tool_calls,+ toolCallNames: tool_call_names,+ };+ } catch (error) {+ console.error("Tool extraction error:", error);+ return {+ input: normalizedToolInput.input,+ output: toIngestionJsonValue(output),+ metadata: normalizedToolInput.metadata,+ toolDefinitions: {},+ toolCalls: [],+ toolCallNames: [],+ };+ }+}+/*** Convert array of tool definitions to Map format for ClickHouse.* Key: tool name, Value: JSON string of {description, parameters}diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.tsindex a0ad4d11e3..05befda789 100644--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts@@ -18,9 +18,8 @@ import {instrumentSync,recordDistribution,UsageDetails,- extractToolsFromObservation,- convertDefinitionsToMap,- convertCallsToArrays,+ normalizeToolsForObservation,+ normalizeToolMetadataForObservation,} from "../";import { LangfuseOtelSpanAttributes } from "./attributes";@@ -301,6 +300,11 @@ export class OtelIngestionProcessor {...spanMetadata,...traceMetadata,};+ const normalizedTools = normalizeToolsForObservation(+ input,+ output,+ metadata,+ );// Extract instrumentation metadataconst serviceName = resourceAttributes?.["service.name"] as@@ -361,23 +365,18 @@ export class OtelIngestionProcessor {);}- let toolDefinitions = undefined;- let toolCalls = undefined;- let toolCallNames = undefined;-- const { toolDefinitions: rawToolDefinitions, toolArguments } =- extractToolsFromObservation(input, output);-- if (rawToolDefinitions.length > 0) {- toolDefinitions = convertDefinitionsToMap(rawToolDefinitions);- }-- if (toolArguments.length > 0) {- const { tool_calls, tool_call_names } =- convertCallsToArrays(toolArguments);- toolCalls = tool_calls;- toolCallNames = tool_call_names;- }+ const toolDefinitions =+ Object.keys(normalizedTools.toolDefinitions).length > 0+ ? normalizedTools.toolDefinitions+ : undefined;+ const toolCalls =+ normalizedTools.toolCalls.length > 0+ ? normalizedTools.toolCalls+ : undefined;+ const toolCallNames =+ normalizedTools.toolCallNames.length > 0+ ? normalizedTools.toolCallNames+ : undefined;events.push({projectId: this.projectId,@@ -471,11 +470,11 @@ export class OtelIngestionProcessor {resourceAttributes?.[LangfuseOtelSpanAttributes.RELEASE] ??null,- input,- output,+ input: normalizedTools.input,+ output: normalizedTools.output,// Metadata- metadata,+ metadata: normalizedTools.metadata,// Instrumentation metadatasource: "otel",@@ -978,6 +977,18 @@ export class OtelIngestionProcessor {source: "ingestion" as const,};+ const metadata = {+ ...resourceAttributeMetadata,+ ...spanAttributeMetadata,+ ...(isLangfuseSDKSpans ? {} : { attributes: filteredAttributes }),+ resourceAttributes,+ scope: { ...scopeSpan.scope, attributes: scopeAttributes },+ };+ const normalizedToolMetadata = normalizeToolMetadataForObservation(+ input,+ metadata,+ );+const observation = {id: this.parseId(span.spanId?.data ?? span.spanId),traceId,@@ -990,13 +1001,7 @@ export class OtelIngestionProcessor {attributes,startTimeISO,),- metadata: {- ...resourceAttributeMetadata,- ...spanAttributeMetadata,- ...(isLangfuseSDKSpans ? {} : { attributes: filteredAttributes }),- resourceAttributes,- scope: { ...scopeSpan.scope, attributes: scopeAttributes },- },+ metadata: normalizedToolMetadata.metadata,level:attributes[LangfuseOtelSpanAttributes.OBSERVATION_LEVEL] ??(span.status?.code === 2@@ -1034,7 +1039,7 @@ export class OtelIngestionProcessor {observationContext,),costDetails: this.extractCostDetails(attributes, observationContext),- input,+ input: normalizedToolMetadata.input,output,};@@ -1822,11 +1827,7 @@ export class OtelIngestionProcessor {);}if (input || output) {- return {- input: this.appendOtelToolDefinitionsToInput(input, attributes),- output,- filteredAttributes,- };+ return { input, output, filteredAttributes };}// OpenTelemetry tools (https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans)@@ -1839,77 +1840,6 @@ export class OtelIngestionProcessor {return { input: null, output: null, filteredAttributes };}- private appendOtelToolDefinitionsToInput(- input: unknown,- attributes: Record<string, unknown>,- ): unknown {- const toolDefinitions = this.extractOtelToolDefinitions(attributes);-- if (!toolDefinitions || input == null) {- return input;- }-- const mergeToolDefinitions = (value: unknown): unknown => {- if (Array.isArray(value)) {- return { messages: value, tools: toolDefinitions };- }-- if (typeof value !== "object" || value == null) {- return null;- }-- const inputObject = value as Record<string, unknown>;-- if (inputObject.tools != null) {- return inputObject;- }-- return {- ...inputObject,- tools: toolDefinitions,- };- };-- if (typeof input === "string") {- try {- const parsedInput = JSON.parse(input);- const mergedInput = mergeToolDefinitions(parsedInput);- return mergedInput == null ? input : JSON.stringify(mergedInput);- } catch {- return input;- }- }-- return mergeToolDefinitions(input) ?? input;- }-- private extractOtelToolDefinitions(- attributes: Record<string, unknown>,- ): unknown[] | null {- const parseJsonString = (value: unknown): unknown => {- if (typeof value !== "string") {- return value;- }-- try {- return JSON.parse(value);- } catch {- return value;- }- };-- const modelRequestParameters = parseJsonString(- attributes["model_request_parameters"],- ) as Record<string, unknown> | null;-- const toolDefinitions = parseJsonString(- attributes["gen_ai.tool.definitions"] ??- modelRequestParameters?.function_tools,- );-- return Array.isArray(toolDefinitions) ? toolDefinitions : null;- }-/*** Prepends gen_ai.system_instructions as a {role: "system", content} message,* consistent with how gen_ai.system.message events are mapped.@@ -2051,16 +1981,6 @@ export class OtelIngestionProcessor {]),});- // Vercel AI SDK- const tools =- "ai.prompt.tools" in attributes- ? attributes["ai.prompt.tools"]- : undefined;-- if (tools) {- langfuseMetadata["tools"] = tools;- }-return {...topLevelMetadata,...langfuseMetadata,diff --git a/packages/shared/src/utils/chatml/adapters/aisdk.ts b/packages/shared/src/utils/chatml/adapters/aisdk.tsindex 5ece7c5258..426d8a7529 100644--- a/packages/shared/src/utils/chatml/adapters/aisdk.ts+++ b/packages/shared/src/utils/chatml/adapters/aisdk.ts@@ -4,6 +4,8 @@ import {stringifyToolResultContent,parseMetadata,isRichToolResult,+ normalizeToolDefinitionsForChatMl,+ attachToolDefinitionsToMessages,} from "../helpers";import { z } from "zod";@@ -270,35 +272,6 @@ function normalizeMessage(msg: unknown): Record<string, unknown> {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", ...}]}@@ -348,12 +321,10 @@ function preprocessData(data: unknown, ctx?: NormalizerContext): unknown {if (!data) return data;// Extract tools from context metadata (observation.metadata.tools)- let toolsFromContext: unknown[] | undefined;+ let toolsFromContext: Array<Record<string, 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);- }+ toolsFromContext = normalizeToolDefinitionsForChatMl(meta.tools);}// Handle wrapped format with messages and tools@@ -363,10 +334,10 @@ function preprocessData(data: unknown, ctx?: NormalizerContext): unknown {const messagesArray = obj.messages as unknown[];if (Array.isArray(messagesArray)) {- let tools: unknown[] | undefined;+ let tools: Array<Record<string, unknown>> | undefined;if (Array.isArray(obj.tools)) {- tools = (obj.tools as unknown[]).map(flattenToolDefinition);+ tools = normalizeToolDefinitionsForChatMl(obj.tools);}const normalized = messagesArray.map(normalizeMessage);@@ -375,10 +346,7 @@ function preprocessData(data: unknown, ctx?: NormalizerContext): unknown {// Attach tools to messages if presentif (tools && tools.length > 0) {- return split.map((msg) => ({- ...(msg as Record<string, unknown>),- tools,- }));+ return attachToolDefinitionsToMessages(split, tools);}return split;@@ -425,10 +393,7 @@ function preprocessData(data: unknown, ctx?: NormalizerContext): unknown {// Attach tools from context metadata if presentif (toolsFromContext && toolsFromContext.length > 0) {- return split.map((msg) => ({- ...(msg as Record<string, unknown>),- tools: toolsFromContext,- }));+ return attachToolDefinitionsToMessages(split, toolsFromContext);}return split;@@ -458,6 +423,8 @@ export const aisdkAdapter: ProviderAdapter = {if (scope.name === "ai") return true;}+ if (meta["scope.name"] === "ai") return true;+if ("attributes" in meta && typeof meta.attributes === "object") {const attrs = meta.attributes as Record<string, unknown> | null;if (@@ -468,6 +435,22 @@ export const aisdkAdapter: ProviderAdapter = {return true;}}++ const flatOperationName = meta["attributes.operation.name"];+ if (+ typeof flatOperationName === "string" &&+ flatOperationName.startsWith("ai.")+ ) {+ return true;+ }++ const flatAiOperationId = meta["attributes.ai.operationId"];+ if (+ typeof flatAiOperationId === "string" &&+ flatAiOperationId.startsWith("ai.")+ ) {+ return true;+ }}// STRUCTURAL: Schema-based detection (for edge cases without metadata)diff --git a/packages/shared/src/utils/chatml/adapters/gemini.ts b/packages/shared/src/utils/chatml/adapters/gemini.tsindex 974908d7a3..4b55a00217 100644--- a/packages/shared/src/utils/chatml/adapters/gemini.ts+++ b/packages/shared/src/utils/chatml/adapters/gemini.ts@@ -404,7 +404,9 @@ function preprocessData(data: unknown): unknown {messages.push(...contents);- // Extract and attach tools if present+ // Extract and attach Gemini ADK config tools if present. Top-level+ // normalized input.tools are extracted separately, without changing+ // normalized ChatML for existing traces.if ("tools" in config && Array.isArray(config.tools)) {const extractedTools = extractToolDeclarations(config.tools);diff --git a/packages/shared/src/utils/chatml/adapters/langgraph.ts b/packages/shared/src/utils/chatml/adapters/langgraph.tsindex ff4f8246d2..80fcdef7c4 100644--- a/packages/shared/src/utils/chatml/adapters/langgraph.ts+++ b/packages/shared/src/utils/chatml/adapters/langgraph.ts@@ -4,6 +4,8 @@ import {stringifyToolResultContent,parseMetadata,isRichToolResult,+ attachToolDefinitionsToMessages,+ normalizeToolDefinitionsForChatMl,} from "../helpers";import { z } from "zod";@@ -225,10 +227,10 @@ function preprocessData(data: unknown): unknown {if (extractedTools.length > 0) {// Attach tools to all messages- return normalizedMessages.map((msg) => ({- ...(msg as Record<string, unknown>),- tools: extractedTools,- }));+ return attachToolDefinitionsToMessages(+ normalizedMessages,+ extractedTools,+ );}return normalizedMessages;@@ -239,15 +241,14 @@ function preprocessData(data: unknown): unknown {const obj = data as Record<string, unknown>;if (Array.isArray(obj.messages)) {const extractedTools = extractToolDefinitions(obj.messages);+ const rootTools = normalizeToolDefinitionsForChatMl(obj.tools);+ const tools = [...extractedTools, ...rootTools];const normalizedMessages = filterAndNormalizeMessages(obj.messages);- if (extractedTools.length > 0) {+ if (tools.length > 0) {return {...obj,- messages: normalizedMessages.map((msg) => ({- ...(msg as Record<string, unknown>),- tools: extractedTools,- })),+ messages: attachToolDefinitionsToMessages(normalizedMessages, tools),};}@@ -303,6 +304,9 @@ export const langgraphAdapter: ProviderAdapter = {if (scope?.name === "pydantic-ai") return false;}+ // Reject AI SDK metadata+ if (meta["scope.name"] === "ai") return false;+// Check attributes["operation.name"] for AI SDK patternif ("attributes" in meta && typeof meta.attributes === "object") {const attrs = meta.attributes as Record<string, unknown> | null;@@ -314,6 +318,22 @@ export const langgraphAdapter: ProviderAdapter = {return false;}}++ const flatOperationName = meta["attributes.operation.name"];+ if (+ typeof flatOperationName === "string" &&+ flatOperationName.startsWith("ai.")+ ) {+ return false;+ }++ const flatAiOperationId = meta["attributes.ai.operationId"];+ if (+ typeof flatAiOperationId === "string" &&+ flatAiOperationId.startsWith("ai.")+ ) {+ return false;+ }}// HINTS: LangGraph/LangChain-specific metadata markersdiff --git a/packages/shared/src/utils/chatml/adapters/microsoft-agent.ts b/packages/shared/src/utils/chatml/adapters/microsoft-agent.tsindex 2fe84a7587..7be0c37ec0 100644--- a/packages/shared/src/utils/chatml/adapters/microsoft-agent.ts+++ b/packages/shared/src/utils/chatml/adapters/microsoft-agent.ts@@ -4,6 +4,8 @@ import {getNestedProperty,stringifyToolResultContent,isRichToolResult,+ attachToolDefinitionsToMessages,+ normalizeToolDefinitionsForChatMl,} from "../helpers";import { z } from "zod";@@ -218,10 +220,7 @@ function preprocessData(data: unknown, ctx: NormalizerContext): unknown {if (toolDefinitions) {const tools = extractToolDefinitions(toolDefinitions);if (tools.length > 0) {- return normalized.map((msg) => ({- ...(msg as Record<string, unknown>),- tools,- }));+ return attachToolDefinitionsToMessages(normalized, tools);}}@@ -231,11 +230,21 @@ function preprocessData(data: unknown, ctx: NormalizerContext): unknown {// messages wrapperif (typeof data === "object" && "messages" in data) {const obj = data as Record<string, unknown>;+ const messages = Array.isArray(obj.messages)+ ? normalizeMessages(obj.messages)+ : obj.messages;+ const tools = normalizeToolDefinitionsForChatMl(obj.tools);++ if (Array.isArray(messages) && tools.length > 0) {+ return {+ ...obj,+ messages: attachToolDefinitionsToMessages(messages, tools),+ };+ }+return {...obj,- messages: Array.isArray(obj.messages)- ? normalizeMessages(obj.messages)- : obj.messages,+ messages,};}diff --git a/packages/shared/src/utils/chatml/adapters/openai.ts b/packages/shared/src/utils/chatml/adapters/openai.tsindex 2d59d3f011..22c8901f91 100644--- a/packages/shared/src/utils/chatml/adapters/openai.ts+++ b/packages/shared/src/utils/chatml/adapters/openai.ts@@ -4,6 +4,7 @@ import {stringifyToolResultContent,parseMetadata,isRichToolResult,+ getNestedProperty,} from "../helpers";import { z } from "zod";@@ -391,8 +392,23 @@ export const openAIAdapter: ProviderAdapter = {) {return false;}++ if (+ scope.name === "agent_framework" ||+ (typeof scope.name === "string" &&+ scope.name.includes("Microsoft.Extensions.AI"))+ ) {+ return false;+ }}+ const providerName = getNestedProperty(+ meta,+ "attributes",+ "gen_ai.provider.name",+ );+ if (providerName === "microsoft.agent_framework") return false;+// Pydantic aiif ("scope" in meta && typeof meta.scope === "object") {const scope = meta.scope as Record<string, unknown>;diff --git a/packages/shared/src/utils/chatml/adapters/pydantic-ai.ts b/packages/shared/src/utils/chatml/adapters/pydantic-ai.tsindex b23968a45d..da47dd49cb 100644--- a/packages/shared/src/utils/chatml/adapters/pydantic-ai.ts+++ b/packages/shared/src/utils/chatml/adapters/pydantic-ai.ts@@ -1,5 +1,11 @@import type { NormalizerContext, ProviderAdapter } from "../types";-import { removeNullFields, parseMetadata, getNestedProperty } from "../helpers";+import {+ removeNullFields,+ parseMetadata,+ getNestedProperty,+ attachToolDefinitionsToMessages,+ normalizeToolDefinitionsForChatMl,+} from "../helpers";import { z } from "zod";/**@@ -241,10 +247,7 @@ function preprocessData(data: unknown, ctx: NormalizerContext): unknown {// Extract and attach tool definitions from metadataconst tools = extractToolDefinitions(ctx.metadata);if (tools.length > 0) {- return normalized.map((msg) => ({- ...(msg as Record<string, unknown>),- tools,- }));+ return attachToolDefinitionsToMessages(normalized, tools);}return normalized;@@ -253,11 +256,21 @@ function preprocessData(data: unknown, ctx: NormalizerContext): unknown {// messages wrapperif (typeof data === "object" && "messages" in data) {const obj = data as Record<string, unknown>;+ const messages = Array.isArray(obj.messages)+ ? normalizeMessages(obj.messages)+ : obj.messages;+ const tools = normalizeToolDefinitionsForChatMl(obj.tools);++ if (Array.isArray(messages) && tools.length > 0) {+ return {+ ...obj,+ messages: attachToolDefinitionsToMessages(messages, tools),+ };+ }+return {...obj,- messages: Array.isArray(obj.messages)- ? normalizeMessages(obj.messages)- : obj.messages,+ messages,};}diff --git a/packages/shared/src/utils/chatml/helpers.ts b/packages/shared/src/utils/chatml/helpers.tsindex b6adc84a2d..2947ae9ee4 100644--- a/packages/shared/src/utils/chatml/helpers.ts+++ b/packages/shared/src/utils/chatml/helpers.ts@@ -97,3 +97,105 @@ export function getNestedProperty(}return current;}++function parseIfString(value: unknown): unknown {+ if (typeof value !== "string") return value;++ try {+ return JSON.parse(value);+ } catch {+ return value;+ }+}++function parseArrayIfString(value: unknown): unknown[] | undefined {+ if (Array.isArray(value)) return value;+ const parsed = parseIfString(value);+ return Array.isArray(parsed) ? parsed : undefined;+}++function isPlainRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++/**+ * Normalize available tool definitions from provider-specific shapes to ChatML.+ * Built-in provider tools often have no `name`, so we fall back to `id`/`type`+ * for display while backend column extraction can still ignore unnamed tools.+ */+export function normalizeToolDefinitionForChatMl(+ tool: unknown,+): Record<string, unknown> | null {+ const parsedTool = parseIfString(tool);+ if (!isPlainRecord(parsedTool)) return null;++ const nestedFunction = isPlainRecord(parsedTool.function)+ ? parsedTool.function+ : undefined;+ const source = nestedFunction ?? parsedTool;++ const rawName =+ source.name ??+ parsedTool.name ??+ parsedTool.id ??+ (parsedTool.type !== "function" ? parsedTool.type : undefined);++ if (typeof rawName !== "string" || rawName.length === 0) return null;++ const rawDescription = source.description ?? parsedTool.description;+ const rawParameters =+ source.parameters ??+ source.parameters_json_schema ??+ source.inputSchema ??+ parsedTool.parameters ??+ parsedTool.parameters_json_schema ??+ parsedTool.inputSchema;++ const normalized: Record<string, unknown> = {+ name: rawName,+ description: typeof rawDescription === "string" ? rawDescription : "",+ };++ if (isPlainRecord(rawParameters)) {+ normalized.parameters = rawParameters;+ }++ return normalized;+}++export function normalizeToolDefinitionsForChatMl(+ tools: unknown,+): Array<Record<string, unknown>> {+ const parsedTools = parseArrayIfString(tools);+ if (!parsedTools) return [];++ return parsedTools+ .map(normalizeToolDefinitionForChatMl)+ .filter((tool): tool is Record<string, unknown> => tool !== null);+}++function dedupeToolDefinitionsForChatMl(+ tools: Array<Record<string, unknown>>,+): Array<Record<string, unknown>> {+ const seenNames = new Set<string>();+ return tools.filter((tool) => {+ const name = tool.name;+ if (typeof name !== "string" || name.length === 0) return false;+ if (seenNames.has(name)) return false;+ seenNames.add(name);+ return true;+ });+}++export function attachToolDefinitionsToMessages(+ messages: unknown[],+ tools: Array<Record<string, unknown>>,+): unknown[] {+ const dedupedTools = dedupeToolDefinitionsForChatMl(tools);+ if (dedupedTools.length === 0) return messages;++ return messages.map((msg) => ({+ ...(isPlainRecord(msg) ? msg : {}),+ tools: dedupedTools,+ }));+}diff --git a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts b/web/src/__tests__/server/api/otel/otelMapping.servertest.tsindex d27f5f3893..098039a33e 100644--- a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts+++ b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts@@ -1210,6 +1210,128 @@ describe("OTel Resource Span Mapping", () => {},};+ const aiSdkWeatherToolInputSchema = {+ type: "object",+ properties: {+ location: { type: "string" },+ unit: { type: "string", enum: ["celsius", "fahrenheit"] },+ },+ required: ["location"],+ additionalProperties: false,+ };+ const aiSdkWeatherTools = [+ {+ type: "function",+ name: "get_weather",+ description: "Get current weather for a location.",+ inputSchema: aiSdkWeatherToolInputSchema,+ },+ ];++ const buildAiSdkToolResourceSpan = ({+ traceId,+ spanId,+ tools,+ }: {+ traceId: string;+ spanId: string;+ tools: unknown[];+ }) => ({+ resource: {+ attributes: [+ {+ key: "service.name",+ value: { stringValue: "otel-test-service" },+ },+ ],+ },+ scopeSpans: [+ {+ scope: {+ name: "ai",+ version: "6.0.0",+ },+ spans: [+ {+ traceId: Buffer.from(traceId, "hex"),+ spanId: Buffer.from(spanId, "hex"),+ name: "ai.generateText",+ kind: 1,+ startTimeUnixNano: { low: 0, high: 406528574, unsigned: true },+ endTimeUnixNano: {+ low: 1000000,+ high: 406528574,+ unsigned: true,+ },+ attributes: [+ {+ key: "ai.operationId",+ value: { stringValue: "ai.generateText.doGenerate" },+ },+ {+ key: "ai.model.id",+ value: { stringValue: "test-model" },+ },+ {+ key: "ai.prompt.messages",+ value: {+ stringValue: JSON.stringify([+ {+ role: "user",+ content: [+ {+ type: "text",+ text: "What is the weather in Berlin?",+ },+ ],+ },+ ]),+ },+ },+ {+ key: "ai.prompt.tools",+ value: { stringValue: JSON.stringify(tools) },+ },+ {+ key: "ai.telemetry.metadata.tools",+ value: { stringValue: JSON.stringify(tools) },+ },+ {+ key: "ai.telemetry.metadata.topic",+ value: { stringValue: "programming" },+ },+ {+ key: "ai.response.toolCalls",+ value: {+ stringValue: JSON.stringify([+ {+ type: "tool-call",+ toolCallId: "call_get_weather_1",+ toolName: "get_weather",+ input: {+ location: "Berlin",+ unit: "celsius",+ },+ },+ ]),+ },+ },+ {+ key: "custom.attribute",+ value: { stringValue: "keep-me" },+ },+ {+ key: "custom.unmapped",+ value: { stringValue: "still-metadata" },+ },+ ],+ status: {},+ },+ ],+ },+ ],+ });+it("should interpret an empty buffer as an unset parentSpanId", async () => {// https://github.com/langchain4j/langchain4j/issues/2328#issuecomment-2686129552// Empty buffers where detected as truthy, i.e. behaved like they had a parent span.@@ -4122,9 +4244,20 @@ describe("OTel Resource Span Mapping", () => {);});- it("should map gen_ai.tool.definitions to input.tools for gen_ai.input.messages", async () => {- const traceId = "abcdef1234567890abcdef1234567890";- const rootSpanId = "1234567890abcdef";+ it("should move gen_ai.tool.definitions from metadata to observation input", async () => {+ const traceId = "abcdef1234567890abcdef1234567892";+ const rootSpanId = "1234567890abcdeb";+ const tool = {+ type: "function",+ name: "calculator",+ description: "Do math",+ parameters: {+ type: "object",+ properties: {+ expression: { type: "string" },+ },+ },+ };const span = {resource: {@@ -4145,7 +4278,7 @@ describe("OTel Resource Span Mapping", () => {{traceId: Buffer.from(traceId, "hex"),spanId: Buffer.from(rootSpanId, "hex"),- name: "otel-genai-span",+ name: "otel-genai-event-span",kind: 1,startTimeUnixNano: { low: 0, high: 406528574, unsigned: true },endTimeUnixNano: {@@ -4155,30 +4288,24 @@ describe("OTel Resource Span Mapping", () => {},attributes: [{- key: "gen_ai.input.messages",- value: {- stringValue: JSON.stringify([- { role: "user", content: "What is 2 + 2?" },- ]),- },+ key: "gen_ai.tool.definitions",+ value: { stringValue: JSON.stringify([tool]) },},+ ],+ events: [{- key: "gen_ai.tool.definitions",- value: {- stringValue: JSON.stringify([- {- type: "function",- name: "calculator",- description: "Do math",- parameters: {- type: "object",- properties: {- expression: { type: "string" },- },- },- },- ]),+ name: "gen_ai.user.message",+ timeUnixNano: {+ low: 1000000,+ high: 406528574,+ unsigned: true,},+ attributes: [+ {+ key: "content",+ value: { stringValue: "What is 2 + 2?" },+ },+ ],},],status: {},@@ -4201,22 +4328,159 @@ describe("OTel Resource Span Mapping", () => {? JSON.parse(observation.body.input): observation?.body.input;- expect(parsedInput.messages).toEqual([- { role: "user", content: "What is 2 + 2?" },+ expect(parsedInput).toEqual({+ messages: [+ {+ role: "user",+ content: "What is 2 + 2?",+ },+ ],+ tools: [tool],+ });+ expect(+ observation?.body.metadata?.attributes?.["gen_ai.tool.definitions"],+ ).toBeUndefined();++ const processor = new OtelIngestionProcessor({+ projectId: "test-project",+ });+ const eventInputs = processor.processToEvent([span]);+ expect(eventInputs).toHaveLength(1);++ const parsedEventInput =+ typeof eventInputs[0].input === "string"+ ? JSON.parse(eventInputs[0].input)+ : eventInputs[0].input;++ expect(parsedEventInput).toEqual({+ messages: [+ {+ role: "user",+ content: "What is 2 + 2?",+ },+ ],+ tools: [tool],+ });+ expect(Object.keys(eventInputs[0].toolDefinitions ?? {})).toEqual([+ "calculator",]);- expect(parsedInput.tools).toEqual([- {- type: "function",- name: "calculator",- description: "Do math",- parameters: {- type: "object",- properties: {- expression: { type: "string" },- },+ expect(+ eventInputs[0].metadata.attributes?.["gen_ai.tool.definitions"],+ ).toBeUndefined();+ });++ it("should move AI SDK available tools from metadata to observation input", async () => {+ const traceId = "abcdef1234567890abcdef1234567891";+ const rootSpanId = "1234567890abcdea";+ const tools = aiSdkWeatherTools;++ const span = buildAiSdkToolResourceSpan({+ traceId,+ spanId: rootSpanId,+ tools,+ });++ const events = await convertOtelSpanToIngestionEvent(span, new Set());++ const observation = events.find(+ (e) => e.type.endsWith("-create") && e.type !== "trace-create",+ );++ expect(observation?.body.input).toBeDefined();++ const parsedInput =+ typeof observation?.body.input === "string"+ ? JSON.parse(observation.body.input)+ : observation?.body.input;++ expect(parsedInput).toEqual({+ messages: [+ {+ role: "user",+ content: [{ type: "text", text: "What is the weather in Berlin?" }],+ },+ ],+ tools,+ });++ expect(observation?.body.output).toBeDefined();+ const parsedOutput =+ typeof observation?.body.output === "string"+ ? JSON.parse(observation.body.output)+ : observation?.body.output;++ expect(parsedOutput).toEqual([+ {+ type: "tool-call",+ toolCallId: "call_get_weather_1",+ toolName: "get_weather",+ input: {+ location: "Berlin",+ unit: "celsius",},},]);++ expect(observation?.body.metadata?.tools).toBeUndefined();+ expect(+ observation?.body.metadata?.attributes?.["ai.prompt.tools"],+ ).toBeUndefined();+ expect(+ observation?.body.metadata?.attributes?.["ai.response.toolCalls"],+ ).toBeUndefined();+ expect(observation?.body.metadata?.topic).toBe("programming");+ expect(observation?.body.metadata?.attributes?.["custom.attribute"]).toBe(+ "keep-me",+ );+ expect(observation?.body.metadata?.attributes?.["custom.unmapped"]).toBe(+ "still-metadata",+ );+ });++ it("should extract AI SDK available tools after metadata normalization in processToEvent", () => {+ const tools = aiSdkWeatherTools;+ const resourceSpan = buildAiSdkToolResourceSpan({+ traceId: "abcdef1234567890abcdef1234567893",+ spanId: "1234567890abcdec",+ tools,+ });++ const processor = new OtelIngestionProcessor({+ projectId: "test-project",+ });+ const eventInputs = processor.processToEvent([resourceSpan]);++ expect(eventInputs).toHaveLength(1);+ const eventInput = eventInputs[0];+ expect(typeof eventInput.input).toBe("object");+ const parsedInput =+ typeof eventInput.input === "string"+ ? JSON.parse(eventInput.input)+ : eventInput.input;++ expect(parsedInput).toEqual({+ messages: [+ {+ role: "user",+ content: [{ type: "text", text: "What is the weather in Berlin?" }],+ },+ ],+ tools,+ });+ expect(Object.keys(eventInput.toolDefinitions ?? {})).toEqual([+ "get_weather",+ ]);+ expect(JSON.parse(eventInput.toolDefinitions.get_weather)).toEqual({+ description: "Get current weather for a location.",+ parameters: JSON.stringify(aiSdkWeatherToolInputSchema),+ });+ expect(eventInput.toolCallNames).toEqual(["get_weather"]);+ expect(eventInput.metadata.tools).toBeUndefined();+ expect(eventInput.metadata.attributes["ai.prompt.tools"]).toBeUndefined();+ expect(eventInput.metadata.topic).toBe("programming");+ expect(eventInput.metadata.attributes["custom.attribute"]).toBe(+ "keep-me",+ );});it("should filter all input/output attribute patterns from metadata.attributes while preserving custom attributes", async () => {diff --git a/web/src/utils/chatml/extractTools.ts b/web/src/utils/chatml/extractTools.tsindex 93001dd26a..ab3a663c3a 100644--- a/web/src/utils/chatml/extractTools.ts+++ b/web/src/utils/chatml/extractTools.ts@@ -1,19 +1,46 @@-import { z } from "zod";-import { OpenAIToolSchema, extractAdditionalInput } from "@langfuse/shared";+import {+ extractAdditionalInput,+ normalizeToolDefinitionsForChatMl,+} from "@langfuse/shared";import type { PlaygroundTool } from "@/src/features/playground/page/types";+const EMPTY_TOOL_PARAMETERS = {+ type: "object",+ properties: {},+} as const;++function parseIfString(value: unknown): unknown {+ if (typeof value !== "string") return value;++ try {+ return JSON.parse(value);+ } catch {+ return value;+ }+}++function asRecord(value: unknown): Record<string, unknown> | null {+ const parsed = parseIfString(value);+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)+ ? (parsed as Record<string, unknown>)+ : null;+}+/**- * Helper to map parsed OpenAI tool schemas to PlaygroundTool format.+ * Helper to map normalized tool definitions to PlaygroundTool format.* Ensures description is always a string (never null/undefined).*/-function mapToolsToPlayground(- tools: z.infer<typeof OpenAIToolSchema>[],-): PlaygroundTool[] {- return tools.map((tool) => ({+function mapToolsToPlayground(tools: unknown): PlaygroundTool[] {+ return normalizeToolDefinitionsForChatMl(tools).map((tool) => ({id: Math.random().toString(36).substring(2),- name: tool.function.name,- description: tool.function.description ?? "",- parameters: tool.function.parameters,+ name: tool.name as string,+ description: typeof tool.description === "string" ? tool.description : "",+ parameters:+ tool.parameters &&+ typeof tool.parameters === "object" &&+ !Array.isArray(tool.parameters)+ ? tool.parameters+ : EMPTY_TOOL_PARAMETERS,}));}@@ -31,31 +58,44 @@ export function extractTools(metadata?: unknown,): PlaygroundTool[] {// Check metadata for tool definitions- if (metadata && typeof metadata === "object" && metadata !== null) {- const meta = metadata as Record<string, unknown>;- if (meta.attributes && typeof meta.attributes === "object") {- const attributes = meta.attributes as Record<string, unknown>;-- // Microsoft Agent Framework: tools in "gen_ai.tool.definitions"- const toolDefs = attributes["gen_ai.tool.definitions"];- if (toolDefs && Array.isArray(toolDefs)) {- const parsedTools = z.array(OpenAIToolSchema).safeParse(toolDefs);- if (parsedTools.success) {- return mapToolsToPlayground(parsedTools.data);- }- }+ const meta = asRecord(metadata);+ if (meta) {+ const attributes = asRecord(meta.attributes);+ if (attributes) {+ // AI SDK OTel: tools in ai.prompt.tools+ const aiSdkTools = mapToolsToPlayground(attributes["ai.prompt.tools"]);+ if (aiSdkTools.length > 0) return aiSdkTools;++ // Microsoft Agent Framework / OTel: tools in gen_ai.tool.definitions+ const genAiTools = mapToolsToPlayground(+ attributes["gen_ai.tool.definitions"],+ );+ if (genAiTools.length > 0) return genAiTools;++ // pydantic-ai: tools in model_request_parameters.function_tools+ const modelRequestParameters = asRecord(+ attributes.model_request_parameters,+ );+ const pydanticTools = mapToolsToPlayground(+ modelRequestParameters?.function_tools,+ );+ if (pydanticTools.length > 0) return pydanticTools;// OpenTelemetry semantic convention: tools indexed as "llm.tools.{N}.tool.json_schema"// Example: "llm.tools.0.tool.json_schema", "llm.tools.1.tool.json_schema", ...- const toolKeys = Object.keys(attributes).filter((key) =>- /^llm\.tools\.\d+\.tool\.json_schema$/.test(key),- );+ const toolKeyPattern = /^llm\.tools\.(\d+)\.tool\.json_schema$/;+ const toolKeys = Object.keys(attributes)+ .map((key) => ({ key, match: toolKeyPattern.exec(key) }))+ .filter(+ (entry): entry is { key: string; match: RegExpExecArray } =>+ entry.match !== null,+ )+ .sort((left, right) => Number(left.match[1]) - Number(right.match[1]))+ .map(({ key }) => key);if (toolKeys.length > 0) {const toolDefs = toolKeys.map((key) => attributes[key]);- const parsedTools = z.array(OpenAIToolSchema).safeParse(toolDefs);- if (parsedTools.success) {- return mapToolsToPlayground(parsedTools.data);- }+ const tools = mapToolsToPlayground(toolDefs);+ if (tools.length > 0) return tools;}}}@@ -74,35 +114,22 @@ export function extractTools(msg.tools.length > 0,);if (firstMessageWithTools && Array.isArray(firstMessageWithTools.tools)) {- return firstMessageWithTools.tools.map((tool: any) => ({- id: Math.random().toString(36).substring(2),- name: tool.name || tool.function?.name,- description: tool.description ?? tool.function?.description ?? "",- parameters: tool.parameters || tool.function?.parameters,- }));+ return mapToolsToPlayground(firstMessageWithTools.tools);}}// LangChain format: tools in additional.tools fieldconst additionalInput = extractAdditionalInput(input);if (additionalInput?.tools && Array.isArray(additionalInput.tools)) {- return additionalInput.tools.map((tool: any) => ({- id: Math.random().toString(36).substring(2),- name: tool.name || tool.function?.name,- description: tool.description ?? tool.function?.description ?? "",- parameters: tool.parameters || tool.function?.parameters,- }));+ return mapToolsToPlayground(additionalInput.tools);}// OpenAI format: tools in input.tools fieldif (typeof input === "object" && input !== null && "tools" in input) {- const parsedTools = z- .array(OpenAIToolSchema)- .safeParse((input as Record<string, unknown>)["tools"]);-- if (parsedTools.success) {- return mapToolsToPlayground(parsedTools.data);- }+ const tools = mapToolsToPlayground(+ (input as Record<string, unknown>)["tools"],+ );+ if (tools.length > 0) return tools;}// LangChain format: tool definitions embedded in messages array@@ -119,11 +146,8 @@ export function extractTools(if (toolMessages.length > 0) {const toolDefs = toolMessages.map((msg: any) => msg.content);- const parsedTools = z.array(OpenAIToolSchema).safeParse(toolDefs);-- if (parsedTools.success) {- return mapToolsToPlayground(parsedTools.data);- }+ const tools = mapToolsToPlayground(toolDefs);+ if (tools.length > 0) return tools;}}@@ -147,11 +171,8 @@ export function extractTools(if (toolMessages.length > 0) {const toolDefs = toolMessages.map((msg: any) => msg.content);- const parsedTools = z.array(OpenAIToolSchema).safeParse(toolDefs);-- if (parsedTools.success) {- return mapToolsToPlayground(parsedTools.data);- }+ const tools = mapToolsToPlayground(toolDefs);+ if (tools.length > 0) return tools;}}diff --git a/web/src/utils/chatml/jumptoplayground.clienttest.ts b/web/src/utils/chatml/jumptoplayground.clienttest.tsindex d5e231cda4..06f5a9d6b9 100644--- a/web/src/utils/chatml/jumptoplayground.clienttest.ts+++ b/web/src/utils/chatml/jumptoplayground.clienttest.ts@@ -879,6 +879,160 @@ describe("Playground Jump Full Pipeline", () => {expect(firstMessage.tools![1].name).toBe("search_web");});+ it("should extract AI SDK flat tools and provider tools from normalized input", () => {+ const tools = extractTools({+ messages: [{ role: "user", content: "Need weather and search" }],+ tools: [+ {+ type: "function",+ name: "get_weather",+ description: "Get weather info",+ inputSchema: {+ type: "object",+ properties: { city: { type: "string" } },+ },+ },+ {+ type: "web_search_preview",+ },+ ],+ });++ expect(tools).toHaveLength(2);+ expect(tools[0]).toMatchObject({+ name: "get_weather",+ description: "Get weather info",+ parameters: {+ type: "object",+ properties: { city: { type: "string" } },+ },+ });+ expect(tools[1]).toMatchObject({+ name: "web_search_preview",+ description: "",+ });+ });++ it("should extract tools from legacy metadata, normalized input, and output", () => {+ const metadataTools = extractTools(null, {+ attributes: {+ "llm.tools.0.tool.json_schema": {+ type: "function",+ function: {+ name: "metadata_search",+ description: "Search from metadata",+ parameters: {+ type: "object",+ properties: { query: { type: "string" } },+ },+ },+ },+ },+ });++ expect(metadataTools).toHaveLength(1);+ expect(metadataTools[0]).toMatchObject({+ name: "metadata_search",+ description: "Search from metadata",+ });++ const inputTools = extractTools({+ messages: [{ role: "user", content: "Need a joke" }],+ tools: [+ {+ type: "function",+ name: "input_joke",+ description: "Get a joke from normalized input",+ inputSchema: { type: "object" },+ },+ ],+ });++ expect(inputTools).toHaveLength(1);+ expect(inputTools[0]).toMatchObject({+ name: "input_joke",+ description: "Get a joke from normalized input",+ parameters: { type: "object" },+ });++ const outputTools = extractTools({+ output: [{ role: "assistant", content: "Done" }],+ tools: [+ {+ type: "function",+ name: "output_tool",+ description: "Tool carried by output",+ inputSchema: { type: "object" },+ },+ ],+ });++ expect(outputTools).toHaveLength(1);+ expect(outputTools[0]).toMatchObject({+ name: "output_tool",+ description: "Tool carried by output",+ });+ });++ it("should preserve numeric order for indexed metadata tools", () => {+ const tools = extractTools(null, {+ attributes: {+ "llm.tools.10.tool.json_schema": {+ type: "function",+ function: {+ name: "tool_ten",+ },+ },+ "llm.tools.2.tool.json_schema": {+ type: "function",+ function: {+ name: "tool_two",+ },+ },+ "llm.tools.1.tool.json_schema": {+ type: "function",+ function: {+ name: "tool_one",+ },+ },+ },+ });++ expect(tools.map((tool) => tool.name)).toEqual([+ "tool_one",+ "tool_two",+ "tool_ten",+ ]);+ });++ it("should extract tools from stringified metadata attributes", () => {+ const metadataTools = extractTools(null, {+ attributes: JSON.stringify({+ "ai.prompt.tools": JSON.stringify([+ {+ type: "function",+ name: "metadata_joke",+ description: "Get a joke from metadata",+ inputSchema: {+ type: "object",+ properties: { topic: { type: "string" } },+ },+ },+ ]),+ }),+ });++ expect(metadataTools).toHaveLength(1);+ expect(metadataTools[0]).toMatchObject({+ name: "metadata_joke",+ description: "Get a joke from metadata",+ parameters: {+ type: "object",+ properties: { topic: { type: "string" } },+ },+ });+ });+it("should handle double-stringified messages array", () => {// ClickHouse can store messages as double-stringified:// { "messages": "[{\"role\":\"user\",\"content\":\"...\"}]" }diff --git a/worker/AGENTS.md b/worker/AGENTS.mdindex ae544da1e1..52a6499ff0 100644--- a/worker/AGENTS.md+++ b/worker/AGENTS.md@@ -1,6 +1,6 @@# Codex Guidelines for `worker`-This file covers package-local guidance for this package.+This file covers package-local guidance for the worker.Use root [AGENTS.md](../AGENTS.md) for monorepo-level rules.## Purpose@@ -20,12 +20,10 @@ Use root [AGENTS.md](../AGENTS.md) for monorepo-level rules.## High-Signal Entry Points-- Bootstrap: `src/index.ts`, `src/app.ts`- Worker registration/lifecycle: `src/queues/workerManager.ts`- Queue processors: `src/queues/*`- Feature processors: `src/features/*`- Service layer: `src/services/*`-- Background migrations: `src/backgroundMigrations/*`- Tests: `src/__tests__/*`, `src/queues/__tests__/*`## Shared Package Imports@@ -50,16 +48,6 @@ Use root [AGENTS.md](../AGENTS.md) for monorepo-level rules.(GitHub mirror:[architecture.mdx](https://github.com/langfuse/langfuse-docs/blob/4188c1ba453240c90a763a8067ef442d68839323/content/handbook/product-engineering/architecture.mdx#L4)).-## Quick Commands--- Dev: `pnpm --filter worker run dev`-- Lint: `pnpm --filter worker run lint`-- Lint fix: `pnpm --filter worker run lint:fix`-- Typecheck: `pnpm --filter worker run typecheck`-- Tests: `pnpm --filter worker run test <file-or-pattern>`-- Coverage: `pnpm --filter worker run coverage [file-or-pattern]`-- Build: `pnpm --filter worker run build`-## Queue Playbook (Add/Change Queue Processor)1. Update queue schemas/contracts in `../packages/shared/src/server/queues.ts`@@ -82,12 +70,6 @@ Use root [AGENTS.md](../AGENTS.md) for monorepo-level rules.- Prefer explicit env-flag gating in `src/app.ts` for new consumers.- Keep queue payload parsing/schema validation centralized in shared contracts.-## Operational Scripts--- Refill ingestion events: `pnpm --filter worker run refill-ingestion-events`-- Refill billing event: `pnpm --filter worker run refill-billing-event`-- Refill queue event: `pnpm --filter worker run refill-queue-event`-## Package-Specific Rules- Keep tests independent; no ordering assumptions.@@ -99,3 +81,4 @@ Use root [AGENTS.md](../AGENTS.md) for monorepo-level rules.surface any discrepancies:- https://langfuse.com/docs/api-and-data-platform/features/export-to-blob-storage- https://langfuse.com/docs/api-and-data-platform/features/blob-storage-export-fields+- be very mindful of adding additional `JSON.parse` calls in the ingestion processing pipeline. Those can cause performance issues, because JSONs might be very large. Ideally, parse each JSON subset only once.diff --git a/worker/src/__tests__/chatml/adapters/aisdk.test.ts b/worker/src/__tests__/chatml/adapters/aisdk.test.tsindex a0fe811efc..a8661347f5 100644--- a/worker/src/__tests__/chatml/adapters/aisdk.test.ts+++ b/worker/src/__tests__/chatml/adapters/aisdk.test.ts@@ -2,6 +2,7 @@ import { describe, it, expect } from "vitest";import {aisdkAdapter,normalizeInput,+ normalizeOutput,type NormalizerContext,} from "@langfuse/shared";@@ -46,6 +47,17 @@ describe("AI SDK Adapter", () => {).toBe(true);});+ it("should detect AI SDK via flat v4 event metadata", () => {+ expect(+ aisdkAdapter.detect({+ metadata: {+ "scope.name": "ai",+ "attributes.operation.name": "ai.generateText.doGenerate",+ },+ }),+ ).toBe(true);+ });+it("should detect AI SDK via framework hint", () => {expect(aisdkAdapter.detect({ framework: "aisdk" })).toBe(true);expect(aisdkAdapter.detect({ framework: "aisdk-v5" })).toBe(true);@@ -316,6 +328,31 @@ describe("AI SDK Adapter", () => {expect(result.data?.[0].tools?.[0].parameters).toBeDefined();});+ it("should attach provider tools without explicit names using their type", () => {+ const input = {+ messages: [+ {+ role: "user",+ content: [{ type: "text", text: "Search the web" }],+ },+ ],+ tools: [+ {+ type: "web_search_preview",+ },+ ],+ };++ const result = normalizeInput(input, { framework: "aisdk" });++ expect(result.success).toBe(true);+ expect(result.data?.[0].tools).toHaveLength(1);+ expect(result.data?.[0].tools?.[0]).toEqual({+ name: "web_search_preview",+ description: "",+ });+ });+it("should stringify simple tool result objects (1-2 scalar keys)", () => {const input = {messages: [@@ -558,5 +595,36 @@ describe("AI SDK Adapter", () => {expect(msg?.tool_calls?.length).toBe(1);expect(msg?.tool_calls?.[0].name).toBe("calculator");});++ it("should normalize raw tool calls with flat v4 event metadata", () => {+ const rawToolCallArray = [+ {+ toolCallId: "call_abc",+ toolName: "get_weather",+ input: { city: "NYC" },+ },+ ];++ const result = normalizeOutput(rawToolCallArray, {+ metadata: {+ "scope.name": "ai",+ "attributes.operation.name": "ai.generateText.doGenerate",+ },+ });++ expect(result.success).toBe(true);+ expect(result.data?.[0]).toMatchObject({+ role: "assistant",+ content: "",+ tool_calls: [+ {+ id: "call_abc",+ name: "get_weather",+ arguments: '{"city":"NYC"}',+ type: "function",+ },+ ],+ });+ });});});diff --git a/worker/src/__tests__/chatml/adapters/langgraph.test.ts b/worker/src/__tests__/chatml/adapters/langgraph.test.tsindex 7e61015374..8bf4267ff8 100644--- a/worker/src/__tests__/chatml/adapters/langgraph.test.ts+++ b/worker/src/__tests__/chatml/adapters/langgraph.test.ts@@ -148,6 +148,60 @@ describe("LangGraph Adapter", () => {expect(result.data?.[1].tools?.[0].name).toBe("Web-Search");});+ it("should attach root tools from normalized wrapped LangGraph input", () => {+ const input = {+ messages: [+ {+ role: "system",+ content: "You are a helpful assistant.",+ },+ {+ role: "user",+ content: "What's the weather in Tokyo?",+ },+ ],+ tools: [+ {+ type: "function",+ name: "get_weather",+ description: "Get the weather for a given location.",+ inputSchema: {+ type: "object",+ properties: {+ location: {+ type: "string",+ description: "The location to get the weather for.",+ },+ },+ required: ["location"],+ },+ },+ ],+ };++ const result = normalizeInput(input, { framework: "langgraph" });++ expect(result.success).toBe(true);+ expect(result.data).toHaveLength(2);+ expect(result.data?.[0].tools).toEqual([+ {+ name: "get_weather",+ description: "Get the weather for a given location.",+ parameters: {+ type: "object",+ properties: {+ location: {+ type: "string",+ description: "The location to get the weather for.",+ },+ },+ required: ["location"],+ },+ },+ ]);+ expect(result.data?.[1].tools?.[0].name).toBe("get_weather");+ });+it("should skip null entries in tool_calls arrays", () => {const input = [{diff --git a/worker/src/__tests__/chatml/adapters/microsoft-agent.test.ts b/worker/src/__tests__/chatml/adapters/microsoft-agent.test.tsindex ab6b4c9441..1c3e9b8246 100644--- a/worker/src/__tests__/chatml/adapters/microsoft-agent.test.ts+++ b/worker/src/__tests__/chatml/adapters/microsoft-agent.test.ts@@ -2,7 +2,8 @@ import { describe, it, expect } from "vitest";import {microsoftAgentAdapter,selectAdapter,- SimpleChatMlArraySchema,+ mapToChatMl,+ mapOutputToChatMl,type NormalizerContext,} from "@langfuse/shared";@@ -14,7 +15,7 @@ function normalizeInput(input: unknown, ctx: NormalizerContext = {}) {data: input,});const preprocessed = adapter.preprocess(input, "input", ctx);- return SimpleChatMlArraySchema.safeParse(preprocessed);+ return mapToChatMl(preprocessed);}function normalizeOutput(output: unknown, ctx: NormalizerContext = {}) {@@ -24,7 +25,7 @@ function normalizeOutput(output: unknown, ctx: NormalizerContext = {}) {data: output,});const preprocessed = adapter.preprocess(output, "output", ctx);- return SimpleChatMlArraySchema.safeParse(preprocessed);+ return mapOutputToChatMl(preprocessed);}describe("Microsoft Agent Framework Adapter", () => {@@ -192,6 +193,65 @@ describe("Microsoft Agent Framework Adapter", () => {expect(result.data?.[0].tools?.[0].name).toBe("get_weather");});+ it("should attach tools from wrapped input tools", () => {+ const input = {+ messages: [+ {+ role: "user",+ parts: [+ {+ type: "text",+ content: "What's the weather like in Portland?",+ },+ ],+ },+ ],+ tools: [+ {+ type: "function",+ function: {+ name: "get_weather",+ description: "Get the weather for a given location.",+ parameters: {+ type: "object",+ properties: {+ location: { type: "string" },+ },+ },+ },+ },+ ],+ };++ const result = normalizeInput(input, {+ metadata: {+ attributes: {+ "gen_ai.provider.name": "microsoft.agent_framework",+ },+ scope: {+ name: "agent_framework",+ },+ },+ });++ expect(result.success).toBe(true);+ expect(result.data?.[0].content).toBe(+ "What's the weather like in Portland?",+ );+ expect(result.data?.[0].tools).toEqual([+ {+ name: "get_weather",+ description: "Get the weather for a given location.",+ parameters: {+ type: "object",+ properties: {+ location: { type: "string" },+ },+ },+ },+ ]);+ });+it("should handle output with multiple parts", () => {const output = [{diff --git a/worker/src/__tests__/chatml/adapters/pydantic-ai.test.ts b/worker/src/__tests__/chatml/adapters/pydantic-ai.test.tsindex 12181ecaae..e027d473a3 100644--- a/worker/src/__tests__/chatml/adapters/pydantic-ai.test.ts+++ b/worker/src/__tests__/chatml/adapters/pydantic-ai.test.ts@@ -2,7 +2,7 @@ import { describe, it, expect } from "vitest";import {pydanticAIAdapter,selectAdapter,- SimpleChatMlArraySchema,+ mapToChatMl,type NormalizerContext,} from "@langfuse/shared";@@ -14,7 +14,7 @@ function normalizeInput(input: unknown, ctx: NormalizerContext = {}) {data: input,});const preprocessed = adapter.preprocess(input, "input", ctx);- return SimpleChatMlArraySchema.safeParse(preprocessed);+ return mapToChatMl(preprocessed);}describe("Pydantic AI Adapter", () => {@@ -199,5 +199,60 @@ describe("Pydantic AI Adapter", () => {expect(result.data?.[0].tool_calls?.[0].name).toBe("get_weather");expect(result.data?.[0].tools?.[0].name).toBe("get_weather");});++ it("should attach tools from wrapped input tools", () => {+ const input = {+ messages: [+ {+ role: "user",+ parts: [+ {+ type: "text",+ content: "Tell me a joke about programming.",+ },+ ],+ },+ ],+ tools: [+ {+ name: "get_pun_suggestion",+ description: "Get a pun-style joke suggestion",+ parameters_json_schema: {+ type: "object",+ properties: {+ topic: { type: "string" },+ },+ },+ },+ ],+ };++ const result = normalizeInput(input, {+ metadata: {+ scope: {+ name: "pydantic-ai",+ version: "1.26.0",+ },+ attributes: {},+ },+ });++ expect(result.success).toBe(true);+ expect(result.data?.[0].content).toBe(+ "Tell me a joke about programming.",+ );+ expect(result.data?.[0].tools).toEqual([+ {+ name: "get_pun_suggestion",+ description: "Get a pun-style joke suggestion",+ parameters: {+ type: "object",+ properties: {+ topic: { type: "string" },+ },+ },+ },+ ]);+ });});});diff --git a/worker/src/__tests__/extractToolsBackend.test.ts b/worker/src/__tests__/extractToolsBackend.test.tsindex 5fad4de7cd..e8e9467308 100644--- a/worker/src/__tests__/extractToolsBackend.test.ts+++ b/worker/src/__tests__/extractToolsBackend.test.ts@@ -1,11 +1,303 @@import { describe, it, expect } from "vitest";import {extractToolsFromObservation,+ normalizeToolsForObservation,convertDefinitionsToMap,convertCallsToArrays,} from "@langfuse/shared/src/server";describe("extractToolsFromObservation", () => {+ describe("Tool metadata normalization", () => {+ it("moves AI SDK tools from metadata to input and removes duplicate metadata", () => {+ const input = [+ {+ role: "user",+ content: [+ {+ type: "text",+ text: "What is the weather in Berlin?",+ },+ ],+ },+ ];+ const tools = [+ {+ type: "function",+ name: "get_weather",+ description: "Get current weather for a location.",+ inputSchema: {+ type: "object",+ properties: {+ location: { type: "string" },+ },+ required: ["location"],+ },+ },+ ];+ const metadata = {+ tools,+ attributes: {+ "ai.prompt.tools": JSON.stringify(tools),+ "custom.attribute": "keep-me",+ },+ };++ const result = normalizeToolsForObservation(input, null, metadata);++ expect(result.input).toEqual({+ messages: input,+ tools,+ });+ expect(result.metadata).toEqual({+ attributes: {+ "custom.attribute": "keep-me",+ },+ });+ });++ it("merges metadata tools with existing input tools before cleanup", () => {+ const existingTool = {+ type: "function",+ name: "search_docs",+ description: "Search docs.",+ inputSchema: { type: "object" },+ };+ const metadataTool = {+ type: "function",+ name: "get_weather",+ description: "Get weather.",+ inputSchema: { type: "object" },+ };+ const input = {+ messages: [{ role: "user", content: "Need weather and docs" }],+ tools: [existingTool],+ };+ const metadata = {+ tools: [metadataTool],+ };++ const result = normalizeToolsForObservation(input, null, metadata);++ expect(result.input).toEqual({+ messages: input.messages,+ tools: [existingTool, metadataTool],+ });+ expect(result.metadata).toEqual({});+ });++ it("moves tools from stringified metadata attributes and removes duplicate metadata", () => {+ const input = [{ role: "user", content: "Need a calculation" }];+ const tool = {+ name: "calculator",+ description: "Do math.",+ parameters: {+ type: "object",+ properties: {+ expression: { type: "string" },+ },+ },+ };+ const metadata = {+ attributes: JSON.stringify({+ "llm.tools.0.tool.json_schema": tool,+ "custom.attribute": "keep-me",+ }),+ };++ const result = normalizeToolsForObservation(input, null, metadata);++ expect(result.input).toEqual({+ messages: input,+ tools: [tool],+ });+ expect(result.metadata).toEqual({+ attributes: {+ "custom.attribute": "keep-me",+ },+ });+ });++ it("does not parse stringified metadata attributes without tool definition keys", () => {+ const input = [{ role: "user", content: "Need weather" }];+ const metadataTool = {+ type: "function",+ name: "get_weather",+ description: "Get weather.",+ };+ const attributes = JSON.stringify({+ "custom.attribute": "mentions model_request_parameters in the value",+ });++ const result = normalizeToolsForObservation(input, null, {+ tools: [metadataTool],+ attributes,+ });++ expect(result.input).toEqual({+ messages: input,+ tools: [metadataTool],+ });+ expect(result.metadata).toEqual({+ attributes,+ });+ });++ it("maps tools onto plain string input instead of dropping them", () => {+ const tool = {+ type: "function",+ name: "get_weather",+ description: "Get weather.",+ inputSchema: {+ type: "object",+ properties: {+ location: { type: "string" },+ },+ },+ };+ const metadata = {+ attributes: {+ "ai.prompt.tools": [tool],+ "custom.attribute": "keep-me",+ },+ };++ const result = normalizeToolsForObservation(+ "What is the weather in Berlin?",+ null,+ metadata,+ );++ expect(result.input).toEqual({+ prompt: "What is the weather in Berlin?",+ tools: [tool],+ });+ expect(result.metadata).toEqual({+ attributes: {+ "custom.attribute": "keep-me",+ },+ });+ });++ it("keeps normalized JSON-string input parsed after moving tools", () => {+ const input = JSON.stringify([{ role: "user", content: "Need weather" }]);+ const tool = {+ type: "function",+ name: "get_weather",+ description: "Get weather.",+ };+ const metadata = {+ attributes: {+ "ai.prompt.tools": [tool],+ },+ };++ const result = normalizeToolsForObservation(input, null, metadata);++ expect(result.input).toEqual({+ messages: [{ role: "user", content: "Need weather" }],+ tools: [tool],+ });+ });++ it("preserves user metadata.tools arrays that are not tool definitions", () => {+ const input = [{ role: "user", content: "Need weather" }];+ const tool = {+ type: "function",+ name: "get_weather",+ description: "Get weather.",+ };+ const metadata = {+ tools: ["hammer"],+ attributes: {+ "ai.prompt.tools": [tool],+ "custom.attribute": "keep-me",+ },+ };++ const result = normalizeToolsForObservation(input, null, metadata);++ expect(result.input).toEqual({+ messages: input,+ tools: [tool],+ });+ expect(result.metadata).toEqual({+ tools: ["hammer"],+ attributes: {+ "custom.attribute": "keep-me",+ },+ });+ });++ it("preserves user metadata.tools objects with generic id or type fields", () => {+ const input = [{ role: "user", content: "Need weather" }];+ const metadata = {+ tools: [{ id: "hammer" }, { type: "manual" }],+ attributes: {+ "custom.attribute": "keep-me",+ },+ };++ const result = normalizeToolsForObservation(input, null, metadata);++ expect(result.input).toEqual(input);+ expect(result.metadata).toEqual(metadata);+ expect(result.toolDefinitions).toEqual({});+ });++ it("preserves invalid OTel gen_ai.tool.definitions without tool names", () => {+ const input = [{ role: "user", content: "Need weather" }];+ const metadata = {+ attributes: {+ "gen_ai.tool.definitions": [{ type: "manual" }],+ "custom.attribute": "keep-me",+ },+ };++ const result = normalizeToolsForObservation(input, null, metadata);++ expect(result.input).toEqual(input);+ expect(result.metadata).toEqual(metadata);+ expect(result.toolDefinitions).toEqual({});+ });++ it("preserves unnamed provider tools in normalized input while extracting only named definitions", () => {+ const input = [{ role: "user", content: "Need current weather" }];+ const functionTool = {+ type: "function",+ name: "get_weather",+ description: "Get weather.",+ inputSchema: {+ type: "object",+ properties: {+ location: { type: "string" },+ },+ },+ };+ const providerTool = {+ type: "web_search_preview",+ };+ const metadata = {+ attributes: {+ "ai.prompt.tools": [functionTool, providerTool],+ "custom.attribute": "keep-me",+ },+ };++ const result = normalizeToolsForObservation(input, null, metadata);++ expect(result.input).toEqual({+ messages: input,+ tools: [functionTool, providerTool],+ });+ expect(result.metadata).toEqual({+ attributes: {+ "custom.attribute": "keep-me",+ },+ });+ expect(Object.keys(result.toolDefinitions)).toEqual(["get_weather"]);+ });+ });+describe("Tool Definitions extraction", () => {it("extracts OpenAI format tools from input", () => {const input = {@@ -59,8 +351,7 @@ describe("extractToolsFromObservation", () => {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+ it("extracts normalized tools from OTel metadata attributes", () => {const metadata = {attributes: {"gen_ai.tool.definitions": [@@ -73,18 +364,17 @@ describe("extractToolsFromObservation", () => {},};+ const normalized = normalizeToolsForObservation(null, null, metadata);const { toolDefinitions } = extractToolsFromObservation(+ normalized.input,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+ it("extracts normalized tools from OTel indexed format", () => {const metadata = {attributes: {"llm.tools.0.tool.json_schema": {@@ -98,10 +388,10 @@ describe("extractToolsFromObservation", () => {},};+ const normalized = normalizeToolsForObservation(null, null, metadata);const { toolDefinitions } = extractToolsFromObservation(+ normalized.input,null,- null,- metadata,);expect(toolDefinitions).toHaveLength(2);@@ -810,8 +1100,82 @@ describe("extractToolsFromObservation", () => {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+ it("should extract AI SDK available tools from metadata while preserving called provider tools", () => {+ const input = [+ {+ role: "user",+ content: [{ type: "text", text: "What's the weather in Berlin?" }],+ },+ ];++ const output = {+ role: "assistant",+ content: "Here's what I found.",+ tool_calls: [+ {+ type: "tool-call",+ toolCallId: "call_provider_search_1",+ toolName: "web_search",+ input: {+ query: "weather forecast in Berlin",+ },+ providerExecuted: true,+ },+ ],+ };++ const tools = [+ {+ type: "function",+ name: "get_weather",+ description: "Get current weather for a location.",+ inputSchema: {+ type: "object",+ properties: {+ location: { type: "string" },+ unit: { type: "string", enum: ["celsius", "fahrenheit"] },+ },+ required: ["location"],+ },+ },+ {+ type: "provider",+ name: "web_search",+ id: "provider.web_search",+ args: {},+ },+ ];++ const metadata = {+ tools,+ providerToolIds: ["web_search"],+ attributes: {+ "ai.prompt.tools": tools,+ },+ };++ const normalized = normalizeToolsForObservation(input, null, metadata);+ const result = extractToolsFromObservation(normalized.input, output);++ expect(result.toolDefinitions.map((t) => t.name)).toEqual([+ "get_weather",+ "web_search",+ ]);+ expect(result.toolDefinitions[0].parameters).toBe(+ JSON.stringify(tools[0].inputSchema),+ );+ expect(result.toolArguments).toHaveLength(1);+ expect(result.toolArguments[0]).toMatchObject({+ id: "call_provider_search_1",+ name: "web_search",+ arguments: JSON.stringify({+ query: "weather forecast in Berlin",+ }),+ type: "tool-call",+ });+ });++ it("should extract normalized tool definitions from OTel metadata structure i.e. pydantic-ai", () => {const metadata = {attributes: {"gen_ai.operation.name": "chat",@@ -881,8 +1245,8 @@ describe("extractToolsFromObservation", () => {],};- // Also test with explicit framework hint- const result = extractToolsFromObservation(input, output, metadata);+ const normalized = normalizeToolsForObservation(input, null, metadata);+ const result = extractToolsFromObservation(normalized.input, output);// Should extract 3 available toolsexpect(result.toolDefinitions).toHaveLength(3);diff --git a/worker/src/queues/__tests__/otelToObservationForEval.test.ts b/worker/src/queues/__tests__/otelToObservationForEval.test.tsindex c7e540d8a8..cf577b555e 100644--- a/worker/src/queues/__tests__/otelToObservationForEval.test.ts+++ b/worker/src/queues/__tests__/otelToObservationForEval.test.ts@@ -741,6 +741,137 @@ describe("OTEL to ObservationForEval Schema Validation", () => {}),});});++ it("should create ClickHouse-valid event records for event-based OTel spans with available tools", async () => {+ const tool = {+ type: "function",+ name: "calculator",+ description: "Do math",+ parameters: {+ type: "object",+ properties: {+ expression: { type: "string" },+ },+ required: ["expression"],+ },+ };+ const resourceSpan = {+ resource: {+ attributes: [+ { key: "service.name", value: { stringValue: "agent-service" } },+ ],+ },+ scopeSpans: [+ {+ scope: { name: "agent_framework", version: "1.0.0" },+ spans: [+ {+ traceId: createBufferId("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),+ spanId: createBufferId("bbbbbbbbbbbbbbbb"),+ name: "agent-event-span",+ kind: 1,+ startTimeUnixNano: createNanoTimestamp(+ BigInt(1714488530686000000),+ ),+ endTimeUnixNano: createNanoTimestamp(+ BigInt(1714488530687000000),+ ),+ attributes: [+ {+ key: "gen_ai.tool.definitions",+ value: { stringValue: JSON.stringify([tool]) },+ },+ ],+ events: [+ {+ name: "gen_ai.user.message",+ timeUnixNano: createNanoTimestamp(+ BigInt(1714488530686000000),+ ),+ attributes: [+ {+ key: "content",+ value: { stringValue: "What is 2 + 2?" },+ },+ ],+ },+ {+ name: "gen_ai.choice",+ timeUnixNano: createNanoTimestamp(+ BigInt(1714488530687000000),+ ),+ attributes: [+ {+ key: "tool_calls",+ value: {+ stringValue: JSON.stringify([+ {+ id: "call_1",+ name: "calculator",+ arguments: JSON.stringify({+ expression: "2 + 2",+ }),+ },+ ]),+ },+ },+ ],+ },+ ],+ status: {},+ },+ ],+ },+ ],+ };++ const processor = new OtelIngestionProcessor({+ projectId: "test-project",+ });+ const eventInputs = processor.processToEvent([resourceSpan]);++ expect(eventInputs).toHaveLength(1);+ expect(typeof eventInputs[0].input).toBe("object");+ expect(+ eventInputs[0].metadata.attributes?.["gen_ai.tool.definitions"],+ ).toBeUndefined();+ expect(eventInputs[0].toolDefinitions).toHaveProperty("calculator");+ expect(eventInputs[0].toolCallNames).toEqual(["calculator"]);++ const eventRecord = await ingestionService.createEventRecord(+ eventInputs[0],+ "test/otel/tools.json",+ );++ expect(typeof eventRecord.input).toBe("string");+ expect(JSON.parse(eventRecord.input)).toEqual({+ messages: [{ role: "user", content: "What is 2 + 2?" }],+ tools: [tool],+ });+ expect(eventRecord.metadata_names).not.toContain(+ "attributes.gen_ai.tool.definitions",+ );+ expect(eventRecord.tool_definitions).toHaveProperty("calculator");+ expect(JSON.parse(eventRecord.tool_definitions.calculator)).toEqual({+ description: "Do math",+ parameters: JSON.stringify(tool.parameters),+ });+ expect(eventRecord.tool_call_names).toEqual(["calculator"]);+ expect(eventRecord.tool_calls).toHaveLength(1);+ expect(JSON.parse(eventRecord.tool_calls[0])).toEqual({+ id: "call_1",+ arguments: JSON.stringify({ expression: "2 + 2" }),+ type: "",+ index: 0,+ });++ const observation = convertEventRecordToObservationForEval(eventRecord);+ const result = observationForEvalSchema.safeParse(observation);+ expect(result.success).toBe(true);+ expect(observation.tool_definitions).toEqual(+ eventRecord.tool_definitions,+ );+ });});describe("Schema field coverage", () => {diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 7c5daee140..507dccf54b 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -6,6 +6,7 @@ import {ObservationLevel,PrismaClient,Prompt,+ type JsonNested,} from "@langfuse/shared";import {ClickhouseClientType,@@ -46,9 +47,7 @@ import {traceException,flattenJsonToPathArrays,getDatasetItemById,- extractToolsFromObservation,- convertDefinitionsToMap,- convertCallsToArrays,+ normalizeToolsForObservation,hasNoEvalConfigsCache,} from "@langfuse/shared/src/server";@@ -217,6 +216,12 @@ export class IngestionService {`Creating event record for project ${eventData.projectId} and span ${eventData.spanId}`,);+ // processToEvent can keep normalized input/output as objects so tool data+ // can be extracted before write time. EventRecordInsertType stores both+ // fields as strings, so stringify at this schema boundary.+ const input = this.stringify(eventData.input);+ const output = this.stringify(eventData.output);+// Perform lookups for prompt and model/usage enrichmentconst [prompt, generationUsage] = await Promise.all([// Lookup prompt by name and version@@ -242,8 +247,8 @@ export class IngestionService {provided_model_name: eventData.modelName,provided_usage_details: eventData.providedUsageDetails ?? {},provided_cost_details: eventData.providedCostDetails ?? {},- input: eventData.input,- output: eventData.output,+ input,+ output,},}): null,@@ -328,8 +333,8 @@ export class IngestionService {tool_call_names: eventData.toolCallNames ?? [],// I/O- input: eventData.input,- output: eventData.output,+ input,+ output,// Metadatametadata_names: metadataNames,@@ -800,42 +805,38 @@ export class IngestionService {// Search for the first non-null input and output in the observation events and set them on the merged result.// Fallback to the ClickHouse input/output if none are found within the events list.const reversedRawRecords = timeSortedEvents.slice().reverse();- mergedObservationRecord.input = this.stringify(+ const rawInput =reversedRawRecords.find((record) => record?.body?.input)?.body?.input ??- clickhouseObservationRecord?.input,- );- mergedObservationRecord.output = this.stringify(+ clickhouseObservationRecord?.input;+ const rawOutput =reversedRawRecords.find((record) => record?.body?.output)?.body?.output ??- clickhouseObservationRecord?.output,+ clickhouseObservationRecord?.output;+ const normalizedTools = normalizeToolsForObservation(+ rawInput,+ rawOutput,+ mergedObservationRecord.metadata,);- // 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);- }+ mergedObservationRecord.input = this.stringify(normalizedTools.input);+ mergedObservationRecord.output = this.stringify(normalizedTools.output);+ const normalizedMetadata = normalizedTools.metadata ?? {};+ mergedObservationRecord.metadata =+ normalizedMetadata &&+ typeof normalizedMetadata === "object" &&+ !Array.isArray(normalizedMetadata)+ ? convertRecordValuesToString(+ normalizedMetadata as Record<string, unknown>,+ )+ : convertJsonSchemaToRecord(normalizedMetadata as JsonNested);++ if (Object.keys(normalizedTools.toolDefinitions).length > 0) {+ mergedObservationRecord.tool_definitions =+ normalizedTools.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+ if (normalizedTools.toolCalls.length > 0) {+ mergedObservationRecord.tool_calls = normalizedTools.toolCalls;+ mergedObservationRecord.tool_call_names = normalizedTools.toolCallNames;}const generationUsage = await this.getGenerationUsage({diff --git a/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts b/worker/src/services/IngestionService/tests/IngestionService.unit.test.tsindex 6efdefe89a..93aa753538 100644--- a/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts+++ b/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts@@ -1,6 +1,10 @@import { expect, describe, it, vi } from "vitest";import { IngestionService } from "../../IngestionService";-import { convertDateToClickhouseDateTime } from "@langfuse/shared/src/server";+import {+ convertDateToClickhouseDateTime,+ type ObservationEvent,+} from "@langfuse/shared/src/server";+import { TableName } from "../../ClickhouseWriter";describe("IngestionService unit tests", () => {it("correctly sorts events in ascending order by timestamp", async () => {@@ -25,4 +29,64 @@ describe("IngestionService unit tests", () => {expect(clickhouseDateTime).toEqual("2024-10-12 12:13:14.123");});++ it("keeps observation metadata values stringified after moving tool definitions to input", async () => {+ const addToQueue = vi.fn();+ const ingestionService = new IngestionService(+ {} as any,+ {} as any,+ { addToQueue } as any,+ {} as any,+ );+ const tool = {+ type: "function",+ name: "get_weather",+ description: "Get weather.",+ };+ const timestamp = "2024-10-12T12:13:14.123Z";+ const observationEventList: ObservationEvent[] = [+ {+ id: "event-id",+ timestamp,+ type: "generation-create",+ body: {+ id: "observation-id",+ traceId: "trace-id",+ startTime: timestamp,+ input: [{ role: "user", content: "Need weather" }],+ metadata: {+ attributes: {+ "ai.prompt.tools": [tool],+ "custom.attribute": "keep-me",+ },+ },+ environment: "default",+ },+ },+ ];++ vi.spyOn(ingestionService as any, "getClickhouseRecord").mockResolvedValue(+ null,+ );+ vi.spyOn(ingestionService as any, "getPrompt").mockResolvedValue(null);+ vi.spyOn(ingestionService as any, "getGenerationUsage").mockResolvedValue(+ {},+ );++ await (ingestionService as any).processObservationEventList({+ projectId: "project-id",+ entityId: "observation-id",+ createdAtTimestamp: new Date(timestamp),+ observationEventList,+ writeToStagingTables: false,+ });++ const observationRecord = addToQueue.mock.calls.find(+ ([table]) => table === TableName.Observations,+ )?.[1];++ expect(observationRecord?.metadata).toEqual({+ attributes: JSON.stringify({ "custom.attribute": "keep-me" }),+ });+ });});