From e37c8ef0dec05f5edbc7c4dff0de580e861e3290 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:40:20 +0000 Subject: [PATCH] feat(server-utils): Send gen_ai.tool.definitions in the documented format Co-Authored-By: Alexander Webb --- .../suites/tracing/google-genai/test.ts | 2 +- .../suites/aws-serverless/bedrock/test.ts | 2 +- .../suites/tracing/anthropic/test.ts | 4 +- .../suites/tracing/google-genai/test.ts | 2 +- .../tracing/openai/openai-tool-calls/test.ts | 18 ++--- .../server-utils/src/ai/anthropic-ai/index.ts | 6 +- .../src/ai/core/tool-definitions.ts | 71 ++++++++++++++++++ .../server-utils/src/ai/google-genai/index.ts | 12 ++- .../server-utils/src/ai/langchain/utils.ts | 12 +-- .../src/ai/langgraph/agent-span.ts | 9 ++- packages/server-utils/src/ai/mastra/utils.ts | 3 +- packages/server-utils/src/ai/mistral/index.ts | 13 +--- packages/server-utils/src/ai/openai/index.ts | 16 +--- packages/server-utils/src/ai/pi-ai/chat.ts | 5 +- .../services/bedrock-runtime-content.ts | 11 ++- .../vercel-ai/vercel-ai-dc-subscriber.ts | 3 +- .../test/ai/lib/tracing/google-genai.test.ts | 4 +- .../ai/lib/utils/tool-definitions.test.ts | 75 +++++++++++++++++++ .../test/integrations/aws-sdk-bedrock.test.ts | 13 +++- 19 files changed, 212 insertions(+), 69 deletions(-) create mode 100644 packages/server-utils/src/ai/core/tool-definitions.ts create mode 100644 packages/server-utils/test/ai/lib/utils/tool-definitions.test.ts diff --git a/dev-packages/cloudflare-integration-tests/suites/tracing/google-genai/test.ts b/dev-packages/cloudflare-integration-tests/suites/tracing/google-genai/test.ts index 27fc478b4667..360745050994 100644 --- a/dev-packages/cloudflare-integration-tests/suites/tracing/google-genai/test.ts +++ b/dev-packages/cloudflare-integration-tests/suites/tracing/google-genai/test.ts @@ -72,7 +72,7 @@ it('traces Google GenAI chat, generateContent, and embedContent calls', async ({ [GEN_AI_REQUEST_PRESENCE_PENALTY]: { value: 0.3, type: 'double' }, [GEN_AI_TOOL_DEFINITIONS]: { value: - '[{"name":"controlLight","parametersJsonSchema":{"type":"object","properties":{"brightness":{"type":"number"},"colorTemperature":{"type":"string"}},"required":["brightness","colorTemperature"]}}]', + '[{"type":"function","name":"controlLight","parameters":{"type":"object","properties":{"brightness":{"type":"number"},"colorTemperature":{"type":"string"}},"required":["brightness","colorTemperature"]}}]', type: 'string', }, // collect LLM input and outputs (default true) diff --git a/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/test.ts b/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/test.ts index d021a54859b3..ccfe2be19ee8 100644 --- a/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/test.ts +++ b/dev-packages/node-integration-tests/suites/aws-serverless/bedrock/test.ts @@ -71,7 +71,7 @@ function assertBedrockContent(container: SerializedStreamedSpanContainer): void JSON.stringify([{ role: 'user', parts: [{ type: 'text', content: 'Hello' }] }]), ); expect(converseSpan!.attributes[GEN_AI_TOOL_DEFINITIONS].value).toBe( - JSON.stringify([{ name: 'get_weather', inputSchema: { json: { type: 'object' } } }]), + JSON.stringify([{ type: 'function', name: 'get_weather', parameters: { type: 'object' } }]), ); expect(converseSpan!.attributes[GEN_AI_OUTPUT_MESSAGES].value).toBe(OUTPUT_MESSAGES); diff --git a/dev-packages/node-integration-tests/suites/tracing/anthropic/test.ts b/dev-packages/node-integration-tests/suites/tracing/anthropic/test.ts index 54dd27321cd1..5baf9fe25b6c 100644 --- a/dev-packages/node-integration-tests/suites/tracing/anthropic/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/anthropic/test.ts @@ -359,7 +359,7 @@ describe('Anthropic integration', () => { createEsmAndCjsTests(__dirname, 'scenario-tools.mjs', 'instrument-with-pii.mjs', (createRunner, test) => { test('non-streaming sets available tools and tool calls with PII', async () => { const EXPECTED_TOOLS_JSON = - '[{"name":"weather","description":"Get the weather by city","input_schema":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}]'; + '[{"type":"function","name":"weather","description":"Get the weather by city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}]'; const EXPECTED_TOOL_CALLS_JSON = '[{"type":"tool_use","id":"tool_weather_1","name":"weather","input":{"city":"Paris"}}]'; await createRunner() @@ -387,7 +387,7 @@ describe('Anthropic integration', () => { createEsmAndCjsTests(__dirname, 'scenario-stream-tools.mjs', 'instrument-with-pii.mjs', (createRunner, test) => { test('streaming sets available tools and tool calls with PII', async () => { const EXPECTED_TOOLS_JSON = - '[{"name":"weather","description":"Get weather","input_schema":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}]'; + '[{"type":"function","name":"weather","description":"Get weather","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}]'; const EXPECTED_TOOL_CALLS_JSON = '[{"type":"tool_use","id":"tool_weather_2","name":"weather","input":{"city":"Paris"}}]'; await createRunner() diff --git a/dev-packages/node-integration-tests/suites/tracing/google-genai/test.ts b/dev-packages/node-integration-tests/suites/tracing/google-genai/test.ts index afc273ab86c5..68be6ccd90aa 100644 --- a/dev-packages/node-integration-tests/suites/tracing/google-genai/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/google-genai/test.ts @@ -184,7 +184,7 @@ describe('Google GenAI integration', () => { }); const EXPECTED_AVAILABLE_TOOLS_JSON = - '[{"name":"controlLight","parametersJsonSchema":{"type":"object","properties":{"brightness":{"type":"number"},"colorTemperature":{"type":"string"}},"required":["brightness","colorTemperature"]}}]'; + '[{"type":"function","name":"controlLight","parameters":{"type":"object","properties":{"brightness":{"type":"number"},"colorTemperature":{"type":"string"}},"required":["brightness","colorTemperature"]}}]'; createEsmAndCjsTests(__dirname, 'scenario-tools.mjs', 'instrument-with-options.mjs', (createRunner, test) => { test('creates google genai related spans with tool calls', async () => { diff --git a/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/test.ts b/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/test.ts index cf5e050605da..d64d2774a958 100644 --- a/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/openai/openai-tool-calls/test.ts @@ -28,17 +28,15 @@ describe('OpenAI Tool Calls integration', () => { const WEATHER_TOOL_DEFINITION = JSON.stringify([ { type: 'function', - function: { - name: 'get_weather', - description: 'Get the current weather in a given location', - parameters: { - type: 'object', - properties: { - latitude: { type: 'number', description: 'The latitude of the location' }, - longitude: { type: 'number', description: 'The longitude of the location' }, - }, - required: ['latitude', 'longitude'], + name: 'get_weather', + description: 'Get the current weather in a given location', + parameters: { + type: 'object', + properties: { + latitude: { type: 'number', description: 'The latitude of the location' }, + longitude: { type: 'number', description: 'The longitude of the location' }, }, + required: ['latitude', 'longitude'], }, }, ]); diff --git a/packages/server-utils/src/ai/anthropic-ai/index.ts b/packages/server-utils/src/ai/anthropic-ai/index.ts index 4d987af2a474..8ec3fcfabf35 100644 --- a/packages/server-utils/src/ai/anthropic-ai/index.ts +++ b/packages/server-utils/src/ai/anthropic-ai/index.ts @@ -27,6 +27,7 @@ import { resolveAIRecordingOptions, wrapPromiseWithMethods, } from '../core/utils'; +import { getToolDefinitionsAttribute } from '../core/tool-definitions'; import { ANTHROPIC_AI_ORIGIN, ANTHROPIC_METHOD_REGISTRY } from './constants'; import { instrumentAsyncIterableStream, instrumentMessageStream } from './streaming'; import { instrumentSessionToolRunner, instrumentToolRunner, instrumentToolRunnerFactory } from './tool-runner'; @@ -59,8 +60,9 @@ export function extractRequestAttributes( if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) { const params = args[0] as Record; - if (recordInputs && params.tools && Array.isArray(params.tools)) { - attributes[GEN_AI_TOOL_DEFINITIONS] = JSON.stringify(params.tools); + const toolDefinitions = recordInputs ? getToolDefinitionsAttribute(params.tools) : undefined; + if (toolDefinitions) { + attributes[GEN_AI_TOOL_DEFINITIONS] = toolDefinitions; } attributes[GEN_AI_REQUEST_MODEL] = params.model ?? 'unknown'; diff --git a/packages/server-utils/src/ai/core/tool-definitions.ts b/packages/server-utils/src/ai/core/tool-definitions.ts new file mode 100644 index 000000000000..ef25876d5d79 --- /dev/null +++ b/packages/server-utils/src/ai/core/tool-definitions.ts @@ -0,0 +1,71 @@ +import { debug, isObjectLike } from '@sentry/core'; +import { DEBUG_BUILD } from '../../debug-build'; + +/** A `gen_ai.tool.definitions` entry in the shape documented by the Sentry conventions. */ +interface GenAiToolDefinition { + type: string; + name: string; + description?: string; + parameters?: unknown; +} + +/** + * Serializes provider tool definitions as the `{ type, name, description, parameters }` entries of + * `gen_ai.tool.definitions`, or returns `undefined` if there are none. + * + * Function tools come in several shapes: OpenAI Chat Completions and Mistral nest them under + * `function`, Anthropic puts the schema in `input_schema`, Bedrock in `inputSchema.json`, Vercel AI + * in `inputSchema`, Google in `parameters` or `parametersJsonSchema`. A bare string is a tool name. + * Tools that a provider runs itself (such as OpenAI's `web_search`) have no schema and are kept as they are. + */ +export function getToolDefinitionsAttribute(tools: unknown): string | undefined { + const definitions = Array.isArray(tools) ? tools.map(toGenAiToolDefinition).filter(tool => tool !== undefined) : []; + if (!definitions.length) { + return undefined; + } + try { + return JSON.stringify(definitions); + } catch (error) { + DEBUG_BUILD && debug.error('Failed to serialize tool definitions:', error); + return undefined; + } +} + +function toGenAiToolDefinition(tool: unknown): unknown { + if (typeof tool === 'string') { + return { type: 'function', name: tool }; + } + if (!isObjectLike(tool)) { + return undefined; + } + // Anthropic marks its function tools as `custom`, to tell them apart from its server tools. + const isFunctionTool = + tool.type === undefined || tool.type === 'function' || (tool.type === 'custom' && 'input_schema' in tool); + if (!isFunctionTool) { + return tool; + } + const fn = isObjectLike(tool.function) ? tool.function : tool; + if (typeof fn.name !== 'string') { + return undefined; + } + const definition: GenAiToolDefinition = { type: 'function', name: fn.name }; + if (typeof fn.description === 'string') { + definition.description = fn.description; + } + const parameters = getToolParameters(fn); + if (parameters !== undefined) { + definition.parameters = parameters; + } + return definition; +} + +function getToolParameters(fn: Record): unknown { + const inputSchema = + isObjectLike(fn.inputSchema) && isObjectLike(fn.inputSchema.json) ? fn.inputSchema.json : fn.inputSchema; + const schema = fn.parameters ?? fn.input_schema ?? inputSchema ?? fn.parametersJsonSchema ?? fn.schema; + // A Zod schema serializes to its internals, not to a JSON schema. + if (!isObjectLike(schema) || '_def' in schema || '_zod' in schema) { + return undefined; + } + return schema; +} diff --git a/packages/server-utils/src/ai/google-genai/index.ts b/packages/server-utils/src/ai/google-genai/index.ts index d80559565ba4..01d6343b30c0 100644 --- a/packages/server-utils/src/ai/google-genai/index.ts +++ b/packages/server-utils/src/ai/google-genai/index.ts @@ -4,6 +4,7 @@ import { getClient, handleCallbackErrors, hasSpanStreamingEnabled, + isObjectLike, startSpan, startSpanManual, stringify, @@ -37,6 +38,7 @@ import { getTokenUsageAttributes, resolveAIRecordingOptions, } from '../core/utils'; +import { getToolDefinitionsAttribute } from '../core/tool-definitions'; import { GOOGLE_GENAI_METHOD_REGISTRY, GOOGLE_GENAI_SYSTEM_NAME } from './constants'; import { instrumentStream } from './streaming'; import type { Candidate, ContentPart, GoogleGenAIOptions, GoogleGenAIResponse } from './types'; @@ -129,10 +131,14 @@ export function extractRequestAttributes( // Extract available tools from config if (recordInputs && 'tools' in config && Array.isArray(config.tools)) { - const functionDeclarations = config.tools.flatMap( - (tool: { functionDeclarations: unknown[] }) => tool.functionDeclarations, + // Only function declarations are tool definitions; the other entries (such as `googleSearch`) toggle built-in tools. + const functionDeclarations = config.tools.flatMap((tool: unknown) => + isObjectLike(tool) && Array.isArray(tool.functionDeclarations) ? tool.functionDeclarations : [], ); - attributes[GEN_AI_TOOL_DEFINITIONS] = JSON.stringify(functionDeclarations); + const toolDefinitions = getToolDefinitionsAttribute(functionDeclarations); + if (toolDefinitions) { + attributes[GEN_AI_TOOL_DEFINITIONS] = toolDefinitions; + } } } } else { diff --git a/packages/server-utils/src/ai/langchain/utils.ts b/packages/server-utils/src/ai/langchain/utils.ts index 405340e71c56..43cb0136f88c 100644 --- a/packages/server-utils/src/ai/langchain/utils.ts +++ b/packages/server-utils/src/ai/langchain/utils.ts @@ -26,6 +26,7 @@ import { } from '@sentry/conventions/attributes'; import { GEN_AI_REQUEST_STREAM_ATTRIBUTE, GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE } from '../core/gen-ai-attributes'; import { extractSystemInstructions, getTokenUsageAttributes } from '../core/utils'; +import { getToolDefinitionsAttribute } from '../core/tool-definitions'; import { LANGCHAIN_ORIGIN, ROLE_MAP } from './constants'; import type { LangChainLLMResult, LangChainMessage, LangChainSerialized } from './types'; @@ -552,16 +553,7 @@ export function extractToolDefinitions(extraParams?: Record): s const tools = (extraParams?.invocation_params as Record)?.tools ?? (extraParams?.options as Record)?.tools; - if (!Array.isArray(tools) || tools.length === 0) return undefined; - const toolDefs = tools.map((tool: Record) => { - const fn = tool.function as Record | undefined; - return { - type: 'function', - name: tool.name ?? fn?.name ?? '', - description: tool.description ?? fn?.description, - }; - }); - return JSON.stringify(toolDefs); + return getToolDefinitionsAttribute(tools); } // A run started without config inherits the parent run's config, which LangChain keeps in a global diff --git a/packages/server-utils/src/ai/langgraph/agent-span.ts b/packages/server-utils/src/ai/langgraph/agent-span.ts index acae26fda9cf..765ced17fdbb 100644 --- a/packages/server-utils/src/ai/langgraph/agent-span.ts +++ b/packages/server-utils/src/ai/langgraph/agent-span.ts @@ -13,6 +13,7 @@ import { } from '@sentry/conventions/attributes'; import { GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op'; import { extractSystemInstructions } from '../core/utils'; +import { getToolDefinitionsAttribute } from '../core/tool-definitions'; import type { BaseChatModel, LangChainMessage } from '../langchain/types'; import { _INTERNAL_mergeLangChainCallbackHandler, @@ -110,9 +111,11 @@ export function prepareAgentSpan( const recordInputs = options.recordInputs; - const tools = recordInputs ? extractToolsFromCompiledGraph(graphInstance) : null; - if (tools) { - span.setAttribute(GEN_AI_TOOL_DEFINITIONS, JSON.stringify(tools)); + const toolDefinitions = recordInputs + ? getToolDefinitionsAttribute(extractToolsFromCompiledGraph(graphInstance)) + : undefined; + if (toolDefinitions) { + span.setAttribute(GEN_AI_TOOL_DEFINITIONS, toolDefinitions); } // Custom state annotations have no `messages` array, the whole state is recorded instead. diff --git a/packages/server-utils/src/ai/mastra/utils.ts b/packages/server-utils/src/ai/mastra/utils.ts index 3f6d32ed8424..9a5513bce2d5 100644 --- a/packages/server-utils/src/ai/mastra/utils.ts +++ b/packages/server-utils/src/ai/mastra/utils.ts @@ -36,6 +36,7 @@ import { GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS, } from '@sentry/conventions/attributes'; +import { getToolDefinitionsAttribute } from '../core/tool-definitions'; import { AGENT_SPAN_TYPES, MODEL_SPAN_TYPES, SPAN_TYPE_OPS, TOOL_SPAN_TYPES } from './constants'; import type { MastraExportedSpan, MastraSpanType, MastraUsageStats } from './types'; @@ -185,7 +186,7 @@ function addAgentAttributes( attributes[GEN_AI_AGENT_NAME] = name; attributes[GEN_AI_PIPELINE_NAME] = name; - attributes[GEN_AI_TOOL_DEFINITIONS] = serialize(attrs.availableTools); + attributes[GEN_AI_TOOL_DEFINITIONS] = getToolDefinitionsAttribute(attrs.availableTools); if (options.recordInputs) { // `prompt` is Mastra's legacy alias for the system prompt. diff --git a/packages/server-utils/src/ai/mistral/index.ts b/packages/server-utils/src/ai/mistral/index.ts index 4f6ba7b25f7e..72cadb3a7022 100644 --- a/packages/server-utils/src/ai/mistral/index.ts +++ b/packages/server-utils/src/ai/mistral/index.ts @@ -18,22 +18,13 @@ import { resolveAIRecordingOptions, wrapPromiseWithMethods, } from '../core/utils'; +import { getToolDefinitionsAttribute } from '../core/tool-definitions'; import { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../core/gen-ai-attributes'; import { MISTRAL_METHOD_REGISTRY, MISTRAL_ORIGIN, MISTRAL_PROVIDER_NAME } from './constants'; import { instrumentEventStream } from './streaming'; import type { MistralOptions } from './types'; import { addResponseAttributes, extractRequestParameters, getSpanName } from './utils'; -/** - * Serialize tool definitions from request parameters, if present. - */ -function extractToolDefinitions(params: Record): string | undefined { - if (!Array.isArray(params.tools) || params.tools.length === 0) { - return undefined; - } - return stringify(params.tools); -} - /** * Extract request attributes from method arguments. * @@ -61,7 +52,7 @@ export function extractRequestAttributes( attributes[GEN_AI_AGENT_NAME] = params.agentId; } - const tools = recordInputs ? extractToolDefinitions(params) : undefined; + const tools = recordInputs ? getToolDefinitionsAttribute(params.tools) : undefined; if (tools) { attributes[GEN_AI_TOOL_DEFINITIONS] = tools; } diff --git a/packages/server-utils/src/ai/openai/index.ts b/packages/server-utils/src/ai/openai/index.ts index 06d34be7b412..87429475a83e 100644 --- a/packages/server-utils/src/ai/openai/index.ts +++ b/packages/server-utils/src/ai/openai/index.ts @@ -1,6 +1,5 @@ /* eslint-disable typescript-eslint/no-deprecated */ -import { DEBUG_BUILD } from '../../debug-build'; -import { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual, debug, stringify } from '@sentry/core'; +import { getClient, hasSpanStreamingEnabled, startSpan, startSpanManual, stringify } from '@sentry/core'; import type { Span, SpanAttributeValue } from '@sentry/core'; import { GEN_AI_EMBEDDINGS_INPUT, @@ -22,6 +21,7 @@ import { resolveAIRecordingOptions, wrapPromiseWithMethods, } from '../core/utils'; +import { getToolDefinitionsAttribute } from '../core/tool-definitions'; import { OPENAI_METHOD_REGISTRY } from './constants'; import { instrumentStream } from './streaming'; import type { ChatCompletionChunk, OpenAiOptions, OpenAIStream, ResponseStreamingEvent } from './types'; @@ -38,17 +38,7 @@ function extractAvailableTools(params: Record): string | undefi ? [{ type: 'web_search_options', ...(params.web_search_options as Record) }] : []; - const availableTools = [...tools, ...webSearchOptions]; - if (availableTools.length === 0) { - return undefined; - } - - try { - return JSON.stringify(availableTools); - } catch (error) { - DEBUG_BUILD && debug.error('Failed to serialize OpenAI tools:', error); - return undefined; - } + return getToolDefinitionsAttribute([...tools, ...webSearchOptions]); } /** diff --git a/packages/server-utils/src/ai/pi-ai/chat.ts b/packages/server-utils/src/ai/pi-ai/chat.ts index c7f8b10dc511..c190bf9cc914 100644 --- a/packages/server-utils/src/ai/pi-ai/chat.ts +++ b/packages/server-utils/src/ai/pi-ai/chat.ts @@ -28,6 +28,7 @@ import { SERVER_PORT, } from '@sentry/conventions/attributes'; import { GEN_AI_CHAT } from '@sentry/conventions/op'; +import { getToolDefinitionsAttribute } from '../core/tool-definitions'; import { PI_AI_ORIGIN } from './constants'; import type { PiAiContext } from './messages'; import { @@ -111,10 +112,10 @@ function getServerAttributes(model: PiModel): Record { const messages = piAiMessagesToGenAiMessages(context.messages); - const tools = piAiToolDefinitions(context); + const tools = getToolDefinitionsAttribute(piAiToolDefinitions(context)); return { [GEN_AI_SYSTEM_INSTRUCTIONS]: piAiSystemInstructions(context), [GEN_AI_INPUT_MESSAGES]: messages.length ? stringify(messages) : undefined, - [GEN_AI_TOOL_DEFINITIONS]: tools.length ? stringify(tools) : undefined, + [GEN_AI_TOOL_DEFINITIONS]: tools, }; } diff --git a/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime-content.ts b/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime-content.ts index 0446cb377c6c..e3d697de554f 100644 --- a/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime-content.ts +++ b/packages/server-utils/src/integrations/aws-sdk/services/bedrock-runtime-content.ts @@ -7,6 +7,7 @@ import { GEN_AI_TOOL_DEFINITIONS, } from '@sentry/conventions/attributes'; import { getMessagesAttributes, messagesFromParams } from '../../../ai/anthropic-ai/utils'; +import { getToolDefinitionsAttribute } from '../../../ai/core/tool-definitions'; import type { GenAiMessagePart } from '../../../ai/types'; /** @@ -142,8 +143,9 @@ export function getConverseInputAttributes(input: Record): Reco const toolSpecs = toolConfig.tools .map(tool => (isObjectLike(tool) ? tool.toolSpec : undefined)) .filter(isObjectLike); - if (toolSpecs.length) { - attributes[GEN_AI_TOOL_DEFINITIONS] = JSON.stringify(toolSpecs); + const toolDefinitions = getToolDefinitionsAttribute(toolSpecs); + if (toolDefinitions) { + attributes[GEN_AI_TOOL_DEFINITIONS] = toolDefinitions; } } @@ -156,8 +158,9 @@ export function getConverseInputAttributes(input: Record): Reco */ export function getClaudeInputAttributes(body: Record): Record { const attributes = getMessagesAttributes(messagesFromParams(body)); - if (Array.isArray(body.tools)) { - attributes[GEN_AI_TOOL_DEFINITIONS] = JSON.stringify(body.tools); + const toolDefinitions = getToolDefinitionsAttribute(body.tools); + if (toolDefinitions) { + attributes[GEN_AI_TOOL_DEFINITIONS] = toolDefinitions; } return attributes; } diff --git a/packages/server-utils/src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts b/packages/server-utils/src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts index d19111cb39be..0b0c386ed4f3 100644 --- a/packages/server-utils/src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts +++ b/packages/server-utils/src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts @@ -56,6 +56,7 @@ import type { TracingChannel } from 'node:diagnostics_channel'; import { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../../ai/core/gen-ai-attributes'; import { isEveGenAiRecordingDefault } from './gen-ai-recording-mode'; import { getEvaluationOutputMessages, type GenAiOptions } from '../../ai/core/utils'; +import { getToolDefinitionsAttribute } from '../../ai/core/tool-definitions'; import { getProviderMetadataAttributes, LAST_STEP_ONLY_USAGE_KEYS } from '../../ai/vercel-ai'; import { WORKERS_AI_INTEGRATION_NAME } from '../../ai/workers-ai/constants'; import { bindTracingChannelToSpan } from '../../tracing-channel'; @@ -628,7 +629,7 @@ function buildModelCallSpan( ...baseAttributes, [VERCEL_AI_OPERATION_ID_ATTRIBUTE]: operationId, ...(recordInputs ? buildInputMessageAttributes(event) : {}), - ...(recordInputs && Array.isArray(event.tools) ? { [GEN_AI_TOOL_DEFINITIONS]: stringify(event.tools) } : {}), + ...(recordInputs ? { [GEN_AI_TOOL_DEFINITIONS]: getToolDefinitionsAttribute(event.tools) } : {}), }); } diff --git a/packages/server-utils/test/ai/lib/tracing/google-genai.test.ts b/packages/server-utils/test/ai/lib/tracing/google-genai.test.ts index 1001a10ea766..82dd32f0fe36 100644 --- a/packages/server-utils/test/ai/lib/tracing/google-genai.test.ts +++ b/packages/server-utils/test/ai/lib/tracing/google-genai.test.ts @@ -184,7 +184,7 @@ describe('instrumentGoogleGenAIClient chat config propagation', () => { expect(data[GEN_AI_REQUEST_MAX_TOKENS]).toBe(150); expect(data[GEN_AI_REQUEST_FREQUENCY_PENALTY]).toBe(0.5); expect(data[GEN_AI_REQUEST_PRESENCE_PENALTY]).toBe(0.3); - expect(data[GEN_AI_TOOL_DEFINITIONS]).toBe('[{"name":"getWeather"}]'); + expect(data[GEN_AI_TOOL_DEFINITIONS]).toBe('[{"type":"function","name":"getWeather"}]'); expect(data[GEN_AI_SYSTEM_INSTRUCTIONS]).toBe('[{"type":"text","content":"You are a friendly robot."}]'); // The chat message stays as the only input message; the system instruction is split out above. expect(data[GEN_AI_INPUT_MESSAGES]).toBe('[{"role":"user","parts":[{"type":"text","content":"Tell me a joke"}]}]'); @@ -210,7 +210,7 @@ describe('instrumentGoogleGenAIClient chat config propagation', () => { expect(data[GEN_AI_REQUEST_MAX_TOKENS]).toBe(150); expect(data[GEN_AI_REQUEST_FREQUENCY_PENALTY]).toBe(0.5); expect(data[GEN_AI_REQUEST_PRESENCE_PENALTY]).toBe(0.3); - expect(data[GEN_AI_TOOL_DEFINITIONS]).toBe('[{"name":"getWeather"}]'); + expect(data[GEN_AI_TOOL_DEFINITIONS]).toBe('[{"type":"function","name":"getWeather"}]'); expect(data[GEN_AI_SYSTEM_INSTRUCTIONS]).toBe('[{"type":"text","content":"You are a friendly robot."}]'); }); diff --git a/packages/server-utils/test/ai/lib/utils/tool-definitions.test.ts b/packages/server-utils/test/ai/lib/utils/tool-definitions.test.ts new file mode 100644 index 000000000000..a28a503601c6 --- /dev/null +++ b/packages/server-utils/test/ai/lib/utils/tool-definitions.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from 'vitest'; +import { getToolDefinitionsAttribute } from '../../../../src/ai/core/tool-definitions'; + +const SCHEMA = { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] }; +const WEATHER_TOOL = { + type: 'function', + name: 'get_weather', + description: 'Get the weather for a city', + parameters: SCHEMA, +}; + +function parse(tools: unknown): unknown { + const attribute = getToolDefinitionsAttribute(tools); + return attribute === undefined ? undefined : JSON.parse(attribute); +} + +describe('getToolDefinitionsAttribute', () => { + it.each([ + [ + 'OpenAI Chat Completions / Mistral', + { + type: 'function', + function: { name: 'get_weather', description: 'Get the weather for a city', parameters: SCHEMA, strict: true }, + }, + ], + ['OpenAI Responses', { ...WEATHER_TOOL, strict: true }], + [ + 'Anthropic', + { + name: 'get_weather', + description: 'Get the weather for a city', + input_schema: SCHEMA, + cache_control: { type: 'ephemeral' }, + }, + ], + [ + 'Anthropic custom', + { type: 'custom', name: 'get_weather', description: 'Get the weather for a city', input_schema: SCHEMA }, + ], + [ + 'Bedrock Converse', + { name: 'get_weather', description: 'Get the weather for a city', inputSchema: { json: SCHEMA } }, + ], + [ + 'Vercel AI', + { type: 'function', name: 'get_weather', description: 'Get the weather for a city', inputSchema: SCHEMA }, + ], + ['Google GenAI', { name: 'get_weather', description: 'Get the weather for a city', parametersJsonSchema: SCHEMA }], + ['LangGraph', { name: 'get_weather', description: 'Get the weather for a city', schema: SCHEMA }], + ])('converts %s function tools', (_provider, tool) => { + expect(parse([tool])).toEqual([WEATHER_TOOL]); + }); + + it('converts tool names', () => { + expect(parse(['get_weather'])).toEqual([{ type: 'function', name: 'get_weather' }]); + }); + + it('omits Zod schemas', () => { + const zodSchema = { _def: { typeName: 'ZodObject' } }; + expect(parse([{ name: 'get_weather', schema: zodSchema }])).toEqual([{ type: 'function', name: 'get_weather' }]); + }); + + it('keeps provider-executed tools as they are', () => { + const webSearch = { type: 'web_search_preview', search_context_size: 'low' }; + expect(parse([webSearch, WEATHER_TOOL])).toEqual([webSearch, WEATHER_TOOL]); + }); + + it('drops entries without a name', () => { + expect(parse([{ description: 'nameless' }, null, WEATHER_TOOL])).toEqual([WEATHER_TOOL]); + }); + + it.each([[undefined], [[]], [{}], [[null]]])('returns undefined for %j', tools => { + expect(getToolDefinitionsAttribute(tools)).toBeUndefined(); + }); +}); diff --git a/packages/server-utils/test/integrations/aws-sdk-bedrock.test.ts b/packages/server-utils/test/integrations/aws-sdk-bedrock.test.ts index a5ef64146989..efad5e16374c 100644 --- a/packages/server-utils/test/integrations/aws-sdk-bedrock.test.ts +++ b/packages/server-utils/test/integrations/aws-sdk-bedrock.test.ts @@ -180,7 +180,14 @@ describe('BedrockRuntimeServiceExtension input recording', () => { ], }, ]), - [GEN_AI_TOOL_DEFINITIONS]: JSON.stringify([WEATHER_TOOL_SPEC]), + [GEN_AI_TOOL_DEFINITIONS]: JSON.stringify([ + { + type: 'function', + name: 'get_weather', + description: 'Get the weather for a city', + parameters: { type: 'object', properties: { city: { type: 'string' } } }, + }, + ]), }); }); @@ -197,7 +204,9 @@ describe('BedrockRuntimeServiceExtension input recording', () => { [GEN_AI_REQUEST_MODEL]: CLAUDE_MODEL_ID, [GEN_AI_SYSTEM_INSTRUCTIONS]: JSON.stringify([{ type: 'text', content: 'You are a weather bot.' }]), [GEN_AI_INPUT_MESSAGES]: JSON.stringify(messages), - [GEN_AI_TOOL_DEFINITIONS]: JSON.stringify(tools), + [GEN_AI_TOOL_DEFINITIONS]: JSON.stringify([ + { type: 'function', name: 'get_weather', parameters: { type: 'object' } }, + ]), }); });