Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,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()
Expand Down Expand Up @@ -389,7 +389,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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,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 () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
},
},
]);
Expand Down
6 changes: 4 additions & 2 deletions packages/server-utils/src/ai/anthropic-ai/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
resolveGenAiCallRecording,
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';
Expand Down Expand Up @@ -54,8 +55,9 @@ export function extractRequestAttributes(

if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {
const params = args[0] as Record<string, unknown>;
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';
Expand Down
71 changes: 71 additions & 0 deletions packages/server-utils/src/ai/core/tool-definitions.ts
Original file line number Diff line number Diff line change
@@ -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) : [];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Chained map and filter loops

Low Severity

The SDK performance convention asks to avoid chaining .map and .filter over the same array; a classic for loop is the expected replacement. getToolDefinitionsAttribute walks tools twice this way. I flagged this because it is called out in the PR review rules.

Fix in Cursor Fix in Web

Triggered by project rule: PR Review Guidelines for Cursor Bot

Reviewed by Cursor Bugbot for commit 3b37818. Configure here.

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<string, unknown>): 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;
}
12 changes: 9 additions & 3 deletions packages/server-utils/src/ai/google-genai/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
getClient,
handleCallbackErrors,
hasSpanStreamingEnabled,
isObjectLike,
startSpan,
startSpanManual,
stringify,
Expand Down Expand Up @@ -39,6 +40,7 @@ import {
getTokenUsageAttributes,
resolveGenAiCallRecording,
} from '../core/utils';
import { getToolDefinitionsAttribute } from '../core/tool-definitions';
import { GOOGLE_GENAI_METHOD_REGISTRY, GOOGLE_GENAI_SYSTEM_NAME } from './constants';
import { addDecisionResponseAttributes, getDecisionInputMessages } from './decisions';
import { instrumentStream } from './streaming';
Expand Down Expand Up @@ -132,10 +134,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;
}
}
}

Expand Down
12 changes: 2 additions & 10 deletions packages/server-utils/src/ai/langchain/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
import { GEN_AI_REQUEST_STREAM_ATTRIBUTE, GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE } from '../core/gen-ai-attributes';
import { extractSystemInstructions, getTokenUsageAttributes } from '../core/utils';
import type { GenAiOptions } from '../core/utils';
import { getToolDefinitionsAttribute } from '../core/tool-definitions';
import { LANGCHAIN_ORIGIN, ROLE_MAP } from './constants';
import type { LangChainLLMResult, LangChainMessage, LangChainSerialized } from './types';

Expand Down Expand Up @@ -562,16 +563,7 @@ export function extractToolDefinitions(extraParams?: Record<string, unknown>): s
const tools =
(extraParams?.invocation_params as Record<string, unknown>)?.tools ??
(extraParams?.options as Record<string, unknown>)?.tools;
if (!Array.isArray(tools) || tools.length === 0) return undefined;
const toolDefs = tools.map((tool: Record<string, unknown>) => {
const fn = tool.function as Record<string, unknown> | 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
Expand Down
9 changes: 6 additions & 3 deletions packages/server-utils/src/ai/langgraph/agent-span.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
import { GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';
import { extractSystemInstructions, resolveGenAiCallRecording } from '../core/utils';
import type { GenAiOptions } from '../core/utils';
import { getToolDefinitionsAttribute } from '../core/tool-definitions';
import type { BaseChatModel, LangChainMessage } from '../langchain/types';
import {
_INTERNAL_mergeLangChainCallbackHandler,
Expand Down Expand Up @@ -121,9 +122,11 @@ export function prepareAgentSpan(

const { recordInputs } = recording;

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.
Expand Down
3 changes: 2 additions & 1 deletion packages/server-utils/src/ai/mastra/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -184,7 +185,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.
Expand Down
13 changes: 2 additions & 11 deletions packages/server-utils/src/ai/mistral/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,13 @@ import {
resolveGenAiCallRecording,
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 { MistralCallInfo, MistralOptions } from './types';
import { addResponseAttributes, extractRequestParameters, getMistralRequestSignal, getSpanName } from './utils';

/**
* Serialize tool definitions from request parameters, if present.
*/
function extractToolDefinitions(params: Record<string, unknown>): string | undefined {
if (!Array.isArray(params.tools) || params.tools.length === 0) {
return undefined;
}
return stringify(params.tools);
}

/**
* Extract request attributes from method arguments.
*
Expand Down Expand Up @@ -63,7 +54,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;
}
Expand Down
16 changes: 3 additions & 13 deletions packages/server-utils/src/ai/openai/index.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -23,6 +22,7 @@ import {
wrapPromiseWithMethods,
} from '../core/utils';
import { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';
import { getToolDefinitionsAttribute } from '../core/tool-definitions';
import { OPENAI_METHOD_REGISTRY } from './constants';
import { instrumentStream } from './streaming';
import type { ChatCompletionChunk, OpenAiCallInfo, OpenAiOptions, OpenAIStream, ResponseStreamingEvent } from './types';
Expand All @@ -39,17 +39,7 @@ function extractAvailableTools(params: Record<string, unknown>): string | undefi
? [{ type: 'web_search_options', ...(params.web_search_options as Record<string, unknown>) }]
: [];

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]);
}

/**
Expand Down
5 changes: 3 additions & 2 deletions packages/server-utils/src/ai/pi-ai/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
} from '@sentry/conventions/attributes';
import { GEN_AI_CHAT } from '@sentry/conventions/op';
import { recordTimeToFirstChunk } from '../core/time-to-first-chunk';
import { getToolDefinitionsAttribute } from '../core/tool-definitions';
import { PI_AI_ORIGIN } from './constants';
import type { PiAiContext } from './messages';
import {
Expand Down Expand Up @@ -112,11 +113,11 @@ function getServerAttributes(model: PiModel): Record<string, string | number | u

function getRequestContentAttributes(context: PiAiContext): Record<string, string | undefined> {
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,
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';

/**
Expand Down Expand Up @@ -142,8 +143,9 @@ export function getConverseInputAttributes(input: Record<string, unknown>): 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;
}
}

Expand All @@ -156,8 +158,9 @@ export function getConverseInputAttributes(input: Record<string, unknown>): Reco
*/
export function getClaudeInputAttributes(body: Record<string, unknown>): Record<string, unknown> {
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;
}
Expand Down
Loading
Loading