From e1c2b678c2506fa8a61b558c10d358680610e780 Mon Sep 17 00:00:00 2001 From: Aikins Laryea Date: Thu, 26 Nov 2026 14:39:30 +0000 Subject: [PATCH] feat(sdk): record tool descriptions and schemas as captured input Model spans list the tools offered to the model in gen_ai.tool.definitions, now with each tool's description and input JSON Schema when input capture is on. Each tool's type and name stay recorded whatever the capture flags. The Anthropic, OpenAI, OpenRouter, Bedrock Converse, Google GenAI, and AI SDK integrations (TypeScript and Python where both exist), LangChain, and the Python LiteLLM integration record the list. Google GenAI previously recorded descriptions and schemas whatever the capture flags; they now need input capture too. The core SDKs apply one rule to the attribute, so older integrations and values set by hand follow it: with input capture off only types and names stay, and with a mask the definitions go through it. The value can be JSON text or an array of one JSON text per tool. A list longer than the attribute limit keeps only types and names, so that it stays JSON. --- README.md | 2 +- docs/sdk-conformance.md | 17 +++- packages/ai/README.md | 9 +- packages/ai/src/integration_v6.ts | 69 +++++++++++++ packages/ai/src/integration_v7.ts | 55 +++++++++++ packages/ai/src/shared.ts | 28 ++++++ packages/ai/tests/integration.test.ts | 22 ++++- packages/ai/tests/integration_v7.test.ts | 51 ++++++++++ packages/anthropic/README.md | 2 +- packages/anthropic/src/index.ts | 38 +++++-- packages/anthropic/tests/anthropic.test.ts | 11 ++- packages/bedrock/src/converse.ts | 51 +++++++++- packages/bedrock/tests/bedrock.test.ts | 20 ++++ packages/google-genai/README.md | 2 +- packages/google-genai/src/index.ts | 26 ++++- .../google-genai/tests/google-genai.test.ts | 9 ++ packages/langchain/README.md | 2 +- packages/langchain/src/generation.ts | 98 ++++++++++++++++--- packages/langchain/tests/handler.test.ts | 8 +- packages/openai/README.md | 2 +- packages/openai/src/index.ts | 71 ++++++++++++-- packages/openai/tests/openai.test.ts | 94 ++++++++++++++++++ packages/openrouter/README.md | 2 + packages/openrouter/src/index.ts | 61 +++++++++++- packages/openrouter/tests/openrouter.test.ts | 70 +++++++++++++ packages/sdk/README.md | 11 ++- packages/sdk/src/attrs.ts | 87 ++++++++++++++++ packages/sdk/tests/capture.test.ts | 82 ++++++++++++++++ sdks/python-anthropic/README.md | 2 +- .../src/telemetry_dev_anthropic/__init__.py | 40 ++++++-- sdks/python-anthropic/tests/test_anthropic.py | 18 +++- .../src/telemetry_dev_bedrock/_registry.py | 52 +++++++++- sdks/python-bedrock/tests/test_bedrock.py | 20 ++++ sdks/python-google-genai/README.md | 2 +- .../telemetry_dev_google_genai/__init__.py | 14 ++- .../src/telemetry_dev_litellm/__init__.py | 52 +++++++++- sdks/python-litellm/tests/test_litellm.py | 29 ++++++ sdks/python-openai/README.md | 2 +- .../src/telemetry_dev_openai/__init__.py | 55 ++++++++++- sdks/python-openai/tests/test_openai.py | 81 +++++++++++++++ sdks/python-openrouter/README.md | 4 + .../src/telemetry_dev_openrouter/__init__.py | 57 ++++++++++- .../tests/test_openrouter.py | 31 ++++++ sdks/python/README.md | 11 ++- sdks/python/src/telemetry_dev/_semconv.py | 1 + sdks/python/src/telemetry_dev/_spans.py | 82 +++++++++++++++- sdks/python/tests/test_masking.py | 80 +++++++++++++++ 47 files changed, 1551 insertions(+), 82 deletions(-) diff --git a/README.md b/README.md index e91445f0..def8c711 100644 --- a/README.md +++ b/README.md @@ -119,7 +119,7 @@ capture setting of its own and records chat messages, tool payloads, and error m Disabling output capture omits message content; response IDs and models, finish reasons, usage, timing, and errors may still be recorded when providers supply them. For streamed OpenAI chat, usage requires provider support or the documented stream-usage option in the OpenAI integration. -Capture flags do not gate stop sequences, tool descriptions and definitions (`gen_ai.tool.description`, `gen_ai.tool.definitions`), or caller-supplied metadata or raw attributes; redact those separately when needed. +Model spans list the tools offered to the model in `gen_ai.tool.definitions`. Each tool's type and name are always recorded; its description and input schema are prompt content, so they need input capture on and pass through the mask. Capture flags do not gate stop sequences, a tool span's description (`gen_ai.tool.description`), or caller-supplied metadata or other raw attributes; redact those separately when needed. The core SDKs record exception messages and stack traces only when both input and output capture are on, and pass them through the mask. Streamed output is kept within fixed size limits that each provider package's README lists, and [Privacy](https://telemetry.dev/docs/platform/privacy) describes what is sent and how to redact it. diff --git a/docs/sdk-conformance.md b/docs/sdk-conformance.md index df761350..ff91254b 100644 --- a/docs/sdk-conformance.md +++ b/docs/sdk-conformance.md @@ -106,10 +106,19 @@ Counters sum advisor entries in the last 1,000 iterations; longer lists also set Streaming replaces cumulative usage snapshots rather than adding them. Absent counters stay absent; zero counters remain zero. Advisor tokens do not change executor usage or its model. -Anthropic integrations record each request tool's type and name in `gen_ai.tool.definitions` as a -JSON array of `{type, name}`, with `type` `function` for custom tools and the tool's own type for -server tools. They record it regardless of capture flags and `mask`; descriptions and input -schemas stay in the captured input. +Model spans list the tools offered to the model in `gen_ai.tool.definitions`, a JSON array of +`{type, name, description, parameters}`: `type` is `function` for a tool the app defines and the +provider's own type for a built-in tool, and `parameters` is the JSON Schema of the tool's input. +The Anthropic, OpenAI, OpenRouter, LiteLLM, Bedrock Converse, Google GenAI, LangChain, and AI SDK +integrations record it. Each tool's `type` and `name` are recorded regardless of capture flags. +`description` and `parameters` are prompt content: they are recorded only with input capture on, +and pass through `mask`. The core SDKs apply the same rule to a raw `gen_ai.tool.definitions` +attribute, given as JSON text or as an array of one JSON text per tool: with input capture off +they keep only `type` and `name`, and they also keep only those when the whole list, masked or +not, is longer than the attribute length limit (0 included, as for other content), so that the +value stays JSON. The names follow the limit of raw attributes, where 0 sets no limit; when they +do not fit, the attribute is left out. A value that is not +such a list is kept as it is with input capture on and no mask, and dropped otherwise. Shared constants: env vars `TELEMETRY_DEV_API_KEY` / `TELEMETRY_DEV_BASE_URL` (default `https://api.telemetry.dev`, for telemetry export and `getPrompt` / `get_prompt`; earlier releases diff --git a/packages/ai/README.md b/packages/ai/README.md index 64dadd5f..71147caf 100644 --- a/packages/ai/README.md +++ b/packages/ai/README.md @@ -149,7 +149,10 @@ a call without one is its own trace. AI SDK records inputs and outputs by default. Each step's `chat` span records the step's instructions (the call's `instructions`, or a `prepareStep` override; `system` on `ai@6`) as -`gen_ai.system_instructions`, next to its input messages. Inputs also include tool arguments and +`gen_ai.system_instructions`, next to its input messages, and the tools offered to the model in +`gen_ai.tool.definitions`: each tool's type and name, and its description and input JSON Schema +(as `parameters`). On `ai@6`, a schema is recorded when it is a `jsonSchema()` schema or a schema +that converts itself to JSON Schema, such as zod 4. Inputs also include tool arguments and results, including provider tools, which can contain shell commands, code, search data, or MCP payloads. To suppress payload capture: @@ -161,8 +164,8 @@ telemetry: { } ``` -These flags omit prompt, instructions, response, tool-argument, tool-result, and detailed error -payloads. Tool +These flags omit prompt, instructions, tool description and schema, response, tool-argument, +tool-result, and detailed error payloads. Tool identity, status, error type, token usage, and other non-payload metadata are still recorded. On text generation steps, model warning messages are reduced to a generic "Model warning" unless both input and output recording are enabled; a warning that supplies a string `type` still records it diff --git a/packages/ai/src/integration_v6.ts b/packages/ai/src/integration_v6.ts index 81a5b912..692deb6c 100644 --- a/packages/ai/src/integration_v6.ts +++ b/packages/ai/src/integration_v6.ts @@ -29,6 +29,8 @@ import { SEVERITY_WARN, type TelemetryDevEvent, type JsonValue, + type ToolDefinition, + toolDefinitionsAttr, unknownErrorMessage, } from "./shared.ts"; @@ -63,6 +65,68 @@ interface V6StepStartEvent { // The step's system prompt: the call's, or a prepareStep override. system?: JsonValue; messages?: JsonValue; + // The call's ToolSet, by tool name, and the names that the step offers when it limits them. + tools?: Record; + activeTools?: string[]; +} + +interface V6Tool { + type?: string; + id?: string; + description?: string; + inputSchema?: unknown; +} + +/** + * The tools a step offers. ai@6 hands telemetry the tools as the app defined them, so a schema + * is recorded when it is readable as JSON Schema without running the app's code: a `jsonSchema()` + * schema, or a Standard Schema that converts itself, such as zod 4. + */ +function v6ToolDefinitions(event: V6StepStartEvent): ToolDefinition[] { + return Object.entries(event.tools ?? {}).flatMap(([name, tool]) => { + if (!tool || (event.activeTools && !event.activeTools.includes(name))) return []; + + if (tool.type === "provider") { + return [{ type: typeof tool.id === "string" ? tool.id : "provider", name }]; + } + + return [ + { + type: "function", + name, + description: typeof tool.description === "string" ? tool.description : undefined, + parameters: readableJsonSchema(tool.inputSchema), + }, + ]; + }); +} + +function readableJsonSchema(schema: unknown): unknown { + if (typeof schema !== "object" || schema === null) return undefined; + + try { + if (Symbol.for("vercel.ai.schema") in schema && "jsonSchema" in schema) { + return settled(schema.jsonSchema); + } + const standard = ( + schema as { + "~standard"?: { jsonSchema?: { input?: (options: { target: string }) => unknown } }; + } + )["~standard"]; + + return settled(standard?.jsonSchema?.input?.({ target: "draft-07" })); + } catch { + return undefined; + } +} + +/** A schema the tool already holds. `jsonSchema()` can hold a promise, which JSON writes as `{}`. */ +function settled(schema: unknown): unknown { + return typeof schema === "object" && + schema !== null && + typeof (schema as { then?: unknown }).then !== "function" + ? schema + : undefined; } interface V6StepFinishEvent { @@ -284,6 +348,11 @@ function createV6Hooks(config: ResolvedConfig, emitter: GenerationEmitter) { rootCtx, ); + // ai@6 telemetry always records inputs, so the descriptions and schemas follow the mask. + const definitions = toolDefinitionsAttr(config, v6ToolDefinitions(e), true); + + if (definitions !== undefined) span.setAttribute("gen_ai.tool.definitions", definitions); + steps.set(e.stepNumber, { span, ctx: trace.setSpan(rootCtx, span), diff --git a/packages/ai/src/integration_v7.ts b/packages/ai/src/integration_v7.ts index f178cdcf..152f26dd 100644 --- a/packages/ai/src/integration_v7.ts +++ b/packages/ai/src/integration_v7.ts @@ -29,6 +29,8 @@ import { SEVERITY_WARN, type TelemetryDevEvent, type JsonValue, + type ToolDefinition, + toolDefinitionsAttr, } from "./shared.ts"; type TelemetryDevHook = (event: TelemetryDevEvent) => void | PromiseLike; @@ -42,6 +44,7 @@ type TelemetryDevHook = (event: TelemetryDevEvent) => void | PromiseLike; export interface TelemetryDevIntegration { onStart?: TelemetryDevHook; onStepStart?: TelemetryDevHook; + onLanguageModelCallStart?: TelemetryDevHook; onLanguageModelCallEnd?: TelemetryDevHook; onStepEnd?: TelemetryDevHook; onToolExecutionStart?: TelemetryDevHook; @@ -155,6 +158,13 @@ interface V7StepStartEvent { runtimeContext?: Record; } +// LanguageModelCallStartEvent: `tools` are the step's prepared tools (LanguageModelV4 function +// tools with a JSON Schema `inputSchema`, and provider tools with an `id`). +interface V7LanguageModelCallStartEvent { + callId: string; + tools?: ReadonlyArray>; +} + interface V7Performance { stepTimeMs?: number; responseTimeMs?: number; @@ -326,6 +336,30 @@ const callIdOf = (event: TelemetryDevEvent): string | undefined => type OpKind = "text" | "object" | "embed" | "rerank" | "evaluate"; +/** A provider tool takes its provider's id, such as `anthropic.web_search_20250305`, as type. */ +function preparedToolDefinitions( + tools: ReadonlyArray> | undefined, +): ToolDefinition[] { + return (tools ?? []).flatMap((tool) => { + const name = tool.name; + + if (typeof name !== "string") return []; + + if (tool.type === "provider") { + return [{ type: typeof tool.id === "string" ? tool.id : "provider", name }]; + } + + return [ + { + type: "function", + name, + description: typeof tool.description === "string" ? tool.description : undefined, + parameters: tool.inputSchema, + }, + ]; + }); +} + const opKindOf = (operationId: string): OpKind => { switch (operationId) { case "ai.generateObject": @@ -1235,6 +1269,27 @@ function createV7Hooks( } }, + onLanguageModelCallStart(event) { + try { + const state = stateOf(event); + + if (!state || state.currentStepNumber === null) return; + const e = event as V7LanguageModelCallStartEvent; + const step = state.steps.get(state.currentStepNumber); + const definitions = toolDefinitionsAttr( + config, + preparedToolDefinitions(e.tools), + state.recordInputs, + ); + + if (step?.open && definitions !== undefined) { + step.span.setAttribute("gen_ai.tool.definitions", definitions); + } + } catch (err) { + reportTelemetryError(onError, err); + } + }, + onLanguageModelCallEnd(event) { try { const state = stateOf(event); diff --git a/packages/ai/src/shared.ts b/packages/ai/src/shared.ts index 3d5d6fb8..6745bf99 100644 --- a/packages/ai/src/shared.ts +++ b/packages/ai/src/shared.ts @@ -58,6 +58,34 @@ export function contentAttr( return jsonAttr(masked); } +/** One tool a model call was offered, as `gen_ai.tool.definitions` lists it. */ +export interface ToolDefinition { + type: string; + name: string; + description?: string; + /** The JSON Schema of the tool's input. */ + parameters?: unknown; +} + +/** + * The `gen_ai.tool.definitions` of a model call. Each tool's type and name are recorded whatever + * `recordInputs` says, as tool spans record their tool's name. Descriptions and schemas are + * prompt content: they need `recordInputs` and go through the mask, and a mask that drops or + * fails on them leaves the names. + */ +export function toolDefinitionsAttr( + config: Pick, + tools: ToolDefinition[], + recordInputs: boolean, +): string | undefined { + if (tools.length === 0) return undefined; + const names = () => JSON.stringify(tools.map(({ type, name }) => ({ type, name }))); + + if (!recordInputs) return names(); + + return contentAttr(config, "gen_ai.tool.definitions", tools) ?? names(); +} + /** * What a failed wrapper call records as its span's `error.type`, status message, and exception. * `errorType` follows errorTypeOf and is also the exception's type. Without a mask the message is diff --git a/packages/ai/tests/integration.test.ts b/packages/ai/tests/integration.test.ts index f764d51a..dc9d5bdc 100644 --- a/packages/ai/tests/integration.test.ts +++ b/packages/ai/tests/integration.test.ts @@ -10,7 +10,7 @@ import { TraceIdRatioBasedSampler, } from "@opentelemetry/sdk-trace-base"; import { sessionSpanContext } from "@telemetry-dev/otel"; -import { generateText, tool } from "ai-v6"; +import { generateText, jsonSchema, tool } from "ai-v6"; import { MockLanguageModelV3 } from "ai-v6/test"; import { expect, test, vi } from "vitest"; import { z } from "zod"; @@ -1072,9 +1072,15 @@ test("a real ai@6 generateText run with a tool call records the root, both steps prompt: "find otel", tools: { lookup: tool({ + description: "Search the docs", inputSchema: z.object({ q: z.string() }), execute: async ({ q }) => ({ hits: [q] }), }), + // A schema that the tool holds as a promise. + later: tool({ + inputSchema: jsonSchema<{ id: string }>(async () => ({ type: "object" })), + execute: async () => ({}), + }), }, stopWhen: () => calls >= 2, experimental_telemetry: { @@ -1114,6 +1120,20 @@ test("a real ai@6 generateText run with a tool call records the root, both steps expect(step.parentSpanContext?.spanId).toBe(spanId(root)); expect(step.attributes["gen_ai.system_instructions"]).toBe("look things up"); expect(step.attributes["gen_ai.usage.input_tokens"]).toBe(4); + // zod 4 converts itself to JSON Schema, so the schema of the offered tool is recorded. + expect(JSON.parse(String(step.attributes["gen_ai.tool.definitions"]))).toEqual([ + { + type: "function", + name: "lookup", + description: "Search the docs", + parameters: expect.objectContaining({ + type: "object", + properties: { q: { type: "string" } }, + required: ["q"], + }), + }, + { type: "function", name: "later" }, + ]); } expect(steps.map((s) => s.attributes["gen_ai.response.finish_reasons"])).toEqual([ diff --git a/packages/ai/tests/integration_v7.test.ts b/packages/ai/tests/integration_v7.test.ts index ce385e39..d7e03378 100644 --- a/packages/ai/tests/integration_v7.test.ts +++ b/packages/ai/tests/integration_v7.test.ts @@ -342,6 +342,57 @@ test("ai@7 step-end fan-out records each step once", async () => { expect(metrics.filter((m) => m.metric === "duration")).toHaveLength(1); }); +test.each([true, false])( + "ai@7 model calls record the offered tools, with descriptions and schemas when recordInputs=%s", + async (recordInputs) => { + const { generateText, jsonSchema, tool } = await import("ai"); + const { MockLanguageModelV4 } = await import("ai/test"); + const { spanBatches, overrides } = makeCapture(); + const integ = telemetryDev(baseOptions, overrides); + const schema = { + type: "object" as const, + properties: { order: { type: "string" as const } }, + required: ["order"], + additionalProperties: false, + }; + + await generateText({ + model: new MockLanguageModelV4({ + doGenerate: { + content: [{ type: "text", text: "done" }], + finishReason: { unified: "stop", raw: "stop" }, + usage: { + inputTokens: { total: 4, noCache: 4, cacheRead: undefined, cacheWrite: undefined }, + outputTokens: { total: 2, text: 2, reasoning: undefined }, + }, + warnings: [], + }, + }), + prompt: "refund order 42", + tools: { + issue_refund: tool({ + description: "Refund an order paid by card", + inputSchema: jsonSchema<{ order: string }>(schema), + }), + }, + telemetry: { integrations: [integ], recordInputs }, + }); + + const [step] = byOperation(spanBatches[0]!, "chat").filter((s) => s.kind === SpanKind.CLIENT); + const definitions = JSON.parse(String(step!.attributes["gen_ai.tool.definitions"])); + expect(definitions).toEqual([ + recordInputs + ? { + type: "function", + name: "issue_refund", + description: "Refund an order paid by card", + parameters: schema, + } + : { type: "function", name: "issue_refund" }, + ]); + }, +); + test("no apiKey is a complete no-op (transport never invoked)", async () => { vi.stubEnv("TELEMETRY_DEV_API_KEY", undefined); diff --git a/packages/anthropic/README.md b/packages/anthropic/README.md index f90ca248..862870d6 100644 --- a/packages/anthropic/README.md +++ b/packages/anthropic/README.md @@ -73,7 +73,7 @@ output is omitted because the mask cannot inspect the complete value. When outpu disabled, response IDs and models, finish reasons, usage, timing, and errors may still be recorded. Capture flags do not gate stop sequences or caller-supplied metadata or raw attributes; redact those separately when needed. Exception messages and stack traces are recorded only when both -`captureInput` and `captureOutput` are on, and pass through `mask`. Request tools and `tool_choice` are part of the captured input, so `captureInput: false` removes them. Each tool's type and name are still recorded in `gen_ai.tool.definitions`, and `mask` does not apply to them; descriptions and input schemas are not. +`captureInput` and `captureOutput` are on, and pass through `mask`. Request tools and `tool_choice` are part of the captured input, so `captureInput: false` removes them. Each tool's type and name are still recorded in `gen_ai.tool.definitions`. With `captureInput` on, that attribute also holds each custom tool's description and input schema (as `parameters`), and passes through `mask`; with it off, it holds only the types and names. ## Native Claude SDK spans diff --git a/packages/anthropic/src/index.ts b/packages/anthropic/src/index.ts index 01707505..86361309 100644 --- a/packages/anthropic/src/index.ts +++ b/packages/anthropic/src/index.ts @@ -1,5 +1,6 @@ import { boundedCaptureDetails, + captureEnabled, startSpan, type SpanFields, type SpanHandle, @@ -126,11 +127,14 @@ function stopSequences(value: T): string[] | undefined { } /** - * The type and name of each request tool as `gen_ai.tool.definitions`. Names are recorded - * regardless of capture flags, as on tool spans; descriptions and schemas stay in the input. + * Each request tool as `gen_ai.tool.definitions`: its type and name, and with input capture on + * a custom tool's description and input schema as `parameters`. Names are recorded regardless of + * capture flags, as on tool spans. The core SDK also strips the description and schema with + * capture off; this check keeps them out with a core older than that rule. */ function toolDefinitions(tools: T): Record | undefined { if (!Array.isArray(tools)) return undefined; + const content = captureEnabled("input"); const definitions = tools.flatMap((tool) => { const record = asRecord(tool); @@ -139,12 +143,22 @@ function toolDefinitions(tools: T): Record | undefined { if (name === undefined) return []; const type = readString(record?.type); - return [{ type: type === undefined || type === "custom" ? "function" : type, name }]; + if (type !== undefined && type !== "custom") return [{ type, name }]; + + if (!content) return [{ type: "function", name }]; + + // JSON.stringify leaves out the fields a tool does not set. + return [ + { + type: "function", + name, + description: readString(record?.description), + parameters: record?.input_schema, + }, + ]; }); - return definitions.length > 0 - ? { "gen_ai.tool.definitions": JSON.stringify(definitions) } - : undefined; + return definitions.length > 0 ? { "gen_ai.tool.definitions": toolsJson(definitions) } : undefined; } // Cores older than promptAttributesFor record a prompt only inside withPrompt. A namespace read @@ -1487,3 +1501,15 @@ export function uninstrumentAnthropic(): void { restorePatches = []; installed = false; } + +/** + * The definitions as JSON, or only their types and names when a schema cannot be serialized, + * such as one holding a BigInt or a cycle: the wrapper maps the request outside any catch. + */ +function toolsJson(definitions: Array<{ type: string; name?: string }>): string { + try { + return JSON.stringify(definitions); + } catch { + return JSON.stringify(definitions.map(({ type, name }) => ({ type, name }))); + } +} diff --git a/packages/anthropic/tests/anthropic.test.ts b/packages/anthropic/tests/anthropic.test.ts index 20d30379..b1de1661 100644 --- a/packages/anthropic/tests/anthropic.test.ts +++ b/packages/anthropic/tests/anthropic.test.ts @@ -557,10 +557,15 @@ test("messages.create preserves request tools and tool-use blocks in output", as }); const span = await exportedSpan(spans); - // The dashboard lists these names as the tools offered; schemas stay in the captured input. + // With input capture on, a custom tool's description and schema say what the tool accepts. expect(jsonAttr(span, "gen_ai.tool.definitions")).toEqual([ - { type: "function", name: "get_weather" }, - { type: "function", name: "issue_refund" }, + { + type: "function", + name: "get_weather", + description: "Get weather", + parameters: tool.input_schema, + }, + { type: "function", name: "issue_refund", parameters: { type: "object" } }, { type: "web_search_20250305", name: "web_search" }, ]); expect(jsonAttr(span, "gen_ai.output.messages")).toEqual([ diff --git a/packages/bedrock/src/converse.ts b/packages/bedrock/src/converse.ts index 61177158..a241d4c3 100644 --- a/packages/bedrock/src/converse.ts +++ b/packages/bedrock/src/converse.ts @@ -1,4 +1,4 @@ -import type { SpanFields } from "@telemetry-dev/sdk"; +import { captureEnabled, type SpanFields } from "@telemetry-dev/sdk"; import { arrayValue, @@ -29,13 +29,14 @@ export interface NormalizedMessage { export function converseRequestFields(input: JsonRecord): SpanFields { const inference = isRecord(input.inferenceConfig) ? input.inferenceConfig : {}; const guardrail = isRecord(input.guardrailConfig) ? input.guardrailConfig : undefined; + const attributes = { ...toolDefinitions(input.toolConfig), ...promptAttributes(input.messages) }; return omitUndefined({ provider: PROVIDER, model: stringValue(input.modelId), input: normalizeMessages(input.messages), systemInstructions: normalizeSystem(input.system), - attributes: promptAttributes(input.messages), + attributes: Object.keys(attributes).length > 0 ? attributes : undefined, temperature: numberValue(inference.temperature), topP: numberValue(inference.topP), maxTokens: numberValue(inference.maxTokens), @@ -49,6 +50,40 @@ export function converseRequestFields(input: JsonRecord): SpanFields { }); } +/** + * The tools of `toolConfig` as `gen_ai.tool.definitions`: each tool's name, and with input + * capture on its description and the JSON Schema of its input. A system tool is listed as + * `system_tool`. The core SDK also strips descriptions and schemas with capture off; this check + * keeps them out with a core older than that rule. + */ +function toolDefinitions(toolConfig: JsonValue | undefined): SpanFields["attributes"] { + const tools = isRecord(toolConfig) ? toolConfig.tools : undefined; + + if (!Array.isArray(tools)) return undefined; + const content = captureEnabled("input"); + + const definitions = tools.flatMap((tool) => { + if (!isRecord(tool)) return []; + const system = isRecord(tool.systemTool) ? stringValue(tool.systemTool.name) : undefined; + + if (system !== undefined) return [{ type: "system_tool", name: system }]; + const spec = isRecord(tool.toolSpec) ? tool.toolSpec : undefined; + const name = stringValue(spec?.name); + + if (name === undefined) return []; + + if (!content) return [{ type: "function", name }]; + const schema = isRecord(spec?.inputSchema) ? spec.inputSchema.json : undefined; + + // JSON.stringify leaves out the fields a tool does not set. + return [ + { type: "function", name, description: stringValue(spec?.description), parameters: schema }, + ]; + }); + + return definitions.length > 0 ? { "gen_ai.tool.definitions": toolsJson(definitions) } : undefined; +} + export function converseResponseFields(output: T): SpanFields { const result: JsonRecord = isRecord(output) ? output : {}; const usage = usageFromConverse(result.usage); @@ -464,3 +499,15 @@ function blockToPart(block: StreamBlock) { citations: block.citations && block.citations.length > 0 ? block.citations : undefined, }); } + +/** + * The definitions as JSON, or only their types and names when a schema cannot be serialized, + * such as one holding a BigInt or a cycle: the wrapper maps the request outside any catch. + */ +function toolsJson(definitions: Array<{ type: string; name?: string }>): string { + try { + return JSON.stringify(definitions); + } catch { + return JSON.stringify(definitions.map(({ type, name }) => ({ type, name }))); + } +} diff --git a/packages/bedrock/tests/bedrock.test.ts b/packages/bedrock/tests/bedrock.test.ts index 614b2816..b72a0a44 100644 --- a/packages/bedrock/tests/bedrock.test.ts +++ b/packages/bedrock/tests/bedrock.test.ts @@ -147,10 +147,30 @@ test("Converse normalizes tool calls, tool results, and reasoning", async () => ], }, ], + toolConfig: { + tools: [ + { + toolSpec: { + name: "weather", + description: "Weather for a city", + inputSchema: { json: { type: "object", properties: { city: { type: "string" } } } }, + }, + }, + { cachePoint: { type: "default" } }, + ], + }, }), ); const span = spans.getFinishedSpans()[0]!; + expect(jsonAttr(span, "gen_ai.tool.definitions")).toEqual([ + { + type: "function", + name: "weather", + description: "Weather for a city", + parameters: { type: "object", properties: { city: { type: "string" } } }, + }, + ]); expect(jsonAttr(span, "gen_ai.input.messages")[1].parts[0]).toEqual({ type: "tool_call_response", id: "tool-1", diff --git a/packages/google-genai/README.md b/packages/google-genai/README.md index 78c8c0aa..ce31e156 100644 --- a/packages/google-genai/README.md +++ b/packages/google-genai/README.md @@ -83,7 +83,7 @@ Block, safety, grounding, and URL-context metadata are raw attributes, which the Unary `generateContent` input, system instructions, output, and AFC history, the `generateContentStream` request, and image and video request content are bounded to 16 MiB each. A value over the bound sets `telemetry.dev.capture.truncated`. Without a mask, the bounded part is kept. With a mask configured, that value is omitted because the mask cannot inspect the complete value. Request input and system instructions are omitted before the span starts, so a custom `sampler` sees the bounded values when no mask is configured. Unary output is omitted only when candidate content was cut; cut grounding, URL-context, or safety metadata sets the attribute but keeps complete content. Streaming AFC history built on a cut request is omitted the same way unless the SDK reports a complete history. -Tool definitions (`gen_ai.tool.definitions`, including tool descriptions and parameter schemas) are request attributes, not captured content: `captureInput`, the mask, and `maxAttributeLength: 0` do not remove them. Like other raw attributes, they are cut at `maxAttributeLength` without a marker, and are sent whole when `maxAttributeLength` is 0 or is not set. +Tool definitions (`gen_ai.tool.definitions`) always hold each tool's type and name. Tool descriptions and parameter schemas are prompt content: they are recorded only with `captureInput` on, and pass through the mask. When the whole list is longer than `maxAttributeLength`, 0 included, it keeps only each tool's type and name, so that it stays JSON, and it is left out when those do not fit either (0 sets no limit for them). ## Streaming diff --git a/packages/google-genai/src/index.ts b/packages/google-genai/src/index.ts index bf548c6e..4c33524a 100644 --- a/packages/google-genai/src/index.ts +++ b/packages/google-genai/src/index.ts @@ -211,10 +211,16 @@ function outputTypeFromConfig(config: UnknownRecord | undefined): string | undef return undefined; } +/** + * The request tools as `gen_ai.tool.definitions`. Descriptions and schemas are prompt content + * and need input capture on. The core SDK also strips them with capture off; this check keeps + * them out with a core older than that rule. + */ function mapToolDefinitions(tools: unknown): unknown[] | undefined { const toolArray = asArray(tools); if (!toolArray) return undefined; + const content = captureEnabled("input"); const definitions: unknown[] = []; for (const tool of toolArray) { @@ -235,9 +241,14 @@ function mapToolDefinitions(tools: unknown): unknown[] | undefined { if (!fn) continue; const definition = { type: "function", name: fn.name }; - if (fn.description !== undefined) Object.assign(definition, { description: fn.description }); + if (content && fn.description !== undefined) { + Object.assign(definition, { description: fn.description }); + } - if (fn.parameters !== undefined) Object.assign(definition, { parameters: fn.parameters }); + // A declaration gives its schema as `parameters` or as plain JSON Schema. + const parameters = fn.parameters ?? fn.parametersJsonSchema; + + if (content && parameters !== undefined) Object.assign(definition, { parameters }); definitions.push(definition); } @@ -256,7 +267,16 @@ function requestAttributesFromConfig(config: UnknownRecord | undefined) { const toolDefs = mapToolDefinitions(config.tools); if (toolDefs) { - const serialized = jsonStringify(toolDefs); + // A schema that cannot be serialized leaves the types and names. + const serialized = + jsonStringify(toolDefs) ?? + jsonStringify( + toolDefs.map((tool) => { + const { type, name } = tool as { type?: unknown; name?: unknown }; + + return { type, name }; + }), + ); if (serialized !== undefined) attributes["gen_ai.tool.definitions"] = serialized; } diff --git a/packages/google-genai/tests/google-genai.test.ts b/packages/google-genai/tests/google-genai.test.ts index fc2b568a..1e327b16 100644 --- a/packages/google-genai/tests/google-genai.test.ts +++ b/packages/google-genai/tests/google-genai.test.ts @@ -502,6 +502,10 @@ test("function tools map definitions, toolConfig, and functionCall output", asyn description: "Get weather", parameters: { type: Type.OBJECT, properties: { city: { type: Type.STRING } } }, }, + { + name: "get_time", + parametersJsonSchema: { type: "object", properties: { zone: { type: "string" } } }, + }, ], }, ], @@ -516,6 +520,11 @@ test("function tools map definitions, toolConfig, and functionCall output", asyn description: "Get weather", parameters: { type: Type.OBJECT, properties: { city: { type: Type.STRING } } }, }, + { + type: "function", + name: "get_time", + parameters: { type: "object", properties: { zone: { type: "string" } } }, + }, ]); expect(jsonAttr(span, "google_genai.request.tool_config")).toEqual({ functionCallingConfig: { mode: FunctionCallingConfigMode.ANY }, diff --git a/packages/langchain/README.md b/packages/langchain/README.md index 6e52fe89..3944e943 100644 --- a/packages/langchain/README.md +++ b/packages/langchain/README.md @@ -59,7 +59,7 @@ A graph span records the input of the graph. If the state of the graph has a `me Model spans record the request model, the provider (from `ls_provider`), temperature, maximum tokens, top-p, stop sequences, the input and output messages, the response model, response id, finish reason, and token usage from `usage_metadata`. Input token counts include cache reads and cache writes. telemetry.dev calculates the cost from the token usage. -Model spans also record the type and name of each tool bound to the model in `gen_ai.tool.definitions`. This attribute does not include the descriptions or schemas of the tools, and the capture options do not change it. +Model spans also record each tool bound to the model in `gen_ai.tool.definitions`: its type and name, and with `captureInput` on its description and input schema (as `parameters`), which pass through the mask. Streamed model calls also record the time to the first chunk and the time between chunks. diff --git a/packages/langchain/src/generation.ts b/packages/langchain/src/generation.ts index c9509df6..6ac3462b 100644 --- a/packages/langchain/src/generation.ts +++ b/packages/langchain/src/generation.ts @@ -6,7 +6,12 @@ import { } from "@langchain/core/messages"; import type { UsageMetadata } from "@langchain/core/messages"; import type { LLMResult } from "@langchain/core/outputs"; -import type { GenerationFields, SpanFields, TokenUsage } from "@telemetry-dev/sdk"; +import { + captureEnabled, + type GenerationFields, + type SpanFields, + type TokenUsage, +} from "@telemetry-dev/sdk"; import { plain, plainMessage } from "./plain.ts"; @@ -37,7 +42,7 @@ export function generationRequest( const tools = toolDefinitions(params?.["tools"]); return { - attributes: tools.length > 0 ? { "gen_ai.tool.definitions": JSON.stringify(tools) } : undefined, + attributes: tools.length > 0 ? { "gen_ai.tool.definitions": toolsJson(tools) } : undefined, model: string(metadata?.["ls_model_name"]) ?? string(params?.["model"]) ?? @@ -103,36 +108,85 @@ export function toolOutput(output: unknown): unknown { return plain(output); } +interface ToolDefinition { + type: string; + name?: string; + description?: string; + parameters?: unknown; +} + /** - * The type and name of each tool in the request, in the provider's format: OpenAI - * `{type, function: {name}}`, Anthropic `{name}` or a server tool `{type, name}`, Gemini - * `{functionDeclarations: [{name}]}`, and Bedrock `{toolSpec: {name}}`. Descriptions and schemas - * stay out, so that the tool list does not depend on content capture. + * The tools of a model run in the formats of the providers LangChain calls: OpenAI + * (`function`), Anthropic (`input_schema`), Bedrock (`toolSpec`), and Gemini + * (`functionDeclarations`). Descriptions and schemas are prompt content and need input capture + * on. The core SDK also strips them with capture off; this check keeps them out with a core + * older than that rule. */ -function toolDefinitions(tools: unknown): Array<{ type: string; name: string }> { +function toolDefinitions(tools: unknown): ToolDefinition[] { if (!Array.isArray(tools)) return []; + const content = captureEnabled("input"); + const definition = ( + type: string, + name: string, + description: unknown, + parameters: unknown, + ): ToolDefinition => + content ? { type, name, description: string(description), parameters } : { type, name }; return tools.flatMap((item: unknown) => { const tool = record(item); const declarations = tool?.["functionDeclarations"]; if (Array.isArray(declarations)) { - return declarations.flatMap((declaration: unknown) => { - const name = string(record(declaration)?.["name"]); + return declarations.flatMap((item: unknown) => { + const declaration = record(item); + const name = string(declaration?.["name"]); - return name ? [{ type: "function", name }] : []; + return name + ? [ + definition( + "function", + name, + declaration?.["description"], + declaration?.["parameters"], + ), + ] + : []; }); } - const name = - string(record(tool?.["function"])?.["name"]) ?? - string(record(tool?.["toolSpec"])?.["name"]) ?? - string(tool?.["name"]); + const fn = record(tool?.["function"]); + const spec = record(tool?.["toolSpec"]); + const name = string(fn?.["name"]) ?? string(spec?.["name"]) ?? string(tool?.["name"]); - if (!name) return []; const type = string(tool?.["type"]); - return [{ type: type === undefined || type === "custom" ? "function" : type, name }]; + // A built-in tool without a name, such as OpenAI's `{type: "web_search"}`, by its type. + if (!name) return type && type !== "function" && type !== "custom" ? [{ type }] : []; + + // A built-in tool; a Responses-format function tool also has its fields at the top. + if ( + fn === undefined && + spec === undefined && + type !== undefined && + type !== "custom" && + type !== "function" + ) { + return [{ type, name }]; + } + const source = fn ?? spec ?? tool; + + return [ + definition( + "function", + name, + source?.["description"], + fn?.["parameters"] ?? + record(spec?.["inputSchema"])?.["json"] ?? + tool?.["input_schema"] ?? + tool?.["parameters"], + ), + ]; }); } @@ -190,3 +244,15 @@ function strings(value: unknown): string[] | undefined { ? value : undefined; } + +/** + * The definitions as JSON, or only their types and names when a schema cannot be serialized, + * such as one holding a BigInt or a cycle: the wrapper maps the request outside any catch. + */ +function toolsJson(definitions: Array<{ type: string; name?: string }>): string { + try { + return JSON.stringify(definitions); + } catch { + return JSON.stringify(definitions.map(({ type, name }) => ({ type, name }))); + } +} diff --git a/packages/langchain/tests/handler.test.ts b/packages/langchain/tests/handler.test.ts index 15c8a6ce..99d07a79 100644 --- a/packages/langchain/tests/handler.test.ts +++ b/packages/langchain/tests/handler.test.ts @@ -259,6 +259,8 @@ test("records the offered tools and each tool call of a reply once", async () => { type: "function", function: { name: "add", description: "Add.", parameters: {} } }, { name: "multiply", description: "Multiply.", input_schema: {} }, { type: "web_search_20250305", name: "web_search" }, + { type: "web_search" }, + { type: "function", name: "modulo", description: "Modulo.", parameters: {} }, { functionDeclarations: [{ name: "divide" }, { name: "subtract" }] }, ]; @@ -269,9 +271,11 @@ test("records the offered tools and each tool call of a reply once", async () => const chat = byName(await finished(spans), "chat gemini-test"); expect(JSON.parse(String(chat.attributes["gen_ai.tool.definitions"]))).toEqual([ - { type: "function", name: "add" }, - { type: "function", name: "multiply" }, + { type: "function", name: "add", description: "Add.", parameters: {} }, + { type: "function", name: "multiply", description: "Multiply.", parameters: {} }, { type: "web_search_20250305", name: "web_search" }, + { type: "web_search" }, + { type: "function", name: "modulo", description: "Modulo.", parameters: {} }, { type: "function", name: "divide" }, { type: "function", name: "subtract" }, ]); diff --git a/packages/openai/README.md b/packages/openai/README.md index 34265d88..61d3fbd9 100644 --- a/packages/openai/README.md +++ b/packages/openai/README.md @@ -92,7 +92,7 @@ Chat completion streams are traced. Requests are sent unchanged by default, so t Streamed chat output and Realtime output are kept up to 16 MiB, and all streams in flight share the `batch.maxStreamBytes` bound of the core (64 MiB by default); each streamed finish reason is cut to its first 128 characters, without setting `telemetry.dev.capture.truncated`, and the finish reasons of a stream have their own budget, which fits at least 1,000 of them; the configured `maxAttributeLength` does not shrink these retention bounds; the core applies it to the exported attribute after the mask runs, with its `...[truncated]` marker, without setting `telemetry.dev.capture.truncated`. A chat stream inspects at most 1,000 choices and 1,000 tool calls in each chunk, and Realtime output keeps output and content indexes below 1,000; past these caps the rest is not kept and `telemetry.dev.capture.truncated` is set. When present, `gen_ai.output.messages` contains bounded partial output. If output and/or finish-reason capture is incomplete, including when a choice ends without `finish_reason`, `telemetry.dev.capture.truncated` is `true`. With a mask configured, incomplete output is omitted because the mask cannot inspect the complete value. When output capture is disabled or omitted, response IDs and models, finish reasons, usage, timing, and errors may still be recorded. -Capture flags do not gate stop sequences or caller-supplied metadata or raw attributes; redact those separately when needed. Exception messages and stack traces are recorded only when both `captureInput` and `captureOutput` are on, and pass through `mask`. +Capture flags do not gate stop sequences or caller-supplied metadata or raw attributes; redact those separately when needed. Exception messages and stack traces are recorded only when both `captureInput` and `captureOutput` are on, and pass through `mask`. Model spans list the request's tools in `gen_ai.tool.definitions`: each tool's type and name, and with `captureInput` on the description and parameters (a custom tool's input format) of each function and custom tool, which pass through `mask`. ```ts const openai = wrapOpenAI(new OpenAI(), { injectStreamUsage: true }); diff --git a/packages/openai/src/index.ts b/packages/openai/src/index.ts index e8c328cb..8f2e7a20 100644 --- a/packages/openai/src/index.ts +++ b/packages/openai/src/index.ts @@ -164,6 +164,49 @@ function stopSequences(value: T): string[] | undefined { return strings.length > 0 ? strings : undefined; } +/** + * The request tools as `gen_ai.tool.definitions`: each tool's type and name, and with input + * capture on a function or custom tool's description and its parameters (custom tools: their + * input format). Chat Completions nests a tool under `function` or `custom`; Responses puts it at + * the top. A built-in tool without a name, such as `web_search`, is listed by its type. The core + * SDK also strips descriptions and schemas with capture off; this check keeps them out with a + * core older than that rule. + */ +function toolDefinitions(tools: T): Record | undefined { + const list = asArray(tools); + + if (!list) return undefined; + const content = captureEnabled("input"); + + const definitions = list.flatMap((item) => { + const tool = asRecord(item); + const type = readString(tool?.type); + + if (tool === undefined || type === undefined) return []; + const spec = asRecord(type === "custom" ? tool.custom : tool.function) ?? tool; + const name = readString(spec.name); + + if (type !== "function" && type !== "custom") + return [name === undefined ? { type } : { type, name }]; + + if (name === undefined) return []; + + if (!content) return [{ type, name }]; + + // JSON.stringify leaves out the fields a tool does not set. + return [ + { + type, + name, + description: readString(spec.description), + parameters: type === "custom" ? spec.format : spec.parameters, + }, + ]; + }); + + return definitions.length > 0 ? { "gen_ai.tool.definitions": toolsJson(definitions) } : undefined; +} + function chatRequest(body: JsonRecord): RequestMapping { const model = readString(body.model); const capture = captureEnabled("input") ? sanitizeResponsesCapture(body.messages) : undefined; @@ -182,9 +225,11 @@ function chatRequest(body: JsonRecord): RequestMapping { seed: readNumber(body.seed), frequencyPenalty: readNumber(body.frequency_penalty), presencePenalty: readNumber(body.presence_penalty), - attributes: capture?.truncated - ? { ...prompt, "telemetry.dev.capture.truncated": true } - : prompt, + attributes: { + ...toolDefinitions(body.tools), + ...prompt, + ...(capture?.truncated ? { "telemetry.dev.capture.truncated": true } : undefined), + }, }, }; } @@ -269,9 +314,11 @@ function responsesRequest(body: JsonRecord): RequestMapping { temperature: readNumber(body.temperature), topP: readNumber(body.top_p), maxTokens: readNumber(body.max_output_tokens), - attributes: capture?.truncated - ? { ...prompt, "telemetry.dev.capture.truncated": true } - : prompt, + attributes: { + ...toolDefinitions(body.tools), + ...prompt, + ...(capture?.truncated ? { "telemetry.dev.capture.truncated": true } : undefined), + }, }, }; } @@ -3701,3 +3748,15 @@ export function uninstrumentOpenAI(): void { restorePatches = []; installed = false; } + +/** + * The definitions as JSON, or only their types and names when a schema cannot be serialized, + * such as one holding a BigInt or a cycle: the wrapper maps the request outside any catch. + */ +function toolsJson(definitions: Array<{ type: string; name?: string }>): string { + try { + return JSON.stringify(definitions); + } catch { + return JSON.stringify(definitions.map(({ type, name }) => ({ type, name }))); + } +} diff --git a/packages/openai/tests/openai.test.ts b/packages/openai/tests/openai.test.ts index e949ccaa..327a1204 100644 --- a/packages/openai/tests/openai.test.ts +++ b/packages/openai/tests/openai.test.ts @@ -664,6 +664,100 @@ test("chat completions preserve tool-call messages in output", async () => { expect(span.attributes["gen_ai.response.finish_reasons"]).toEqual(["tool_calls"]); }); +test.each([ + { api: "chat", captureInput: true }, + { api: "chat", captureInput: false }, + { api: "responses", captureInput: true }, + { api: "responses", captureInput: false }, +] as const)( + "$api records the offered tools, with descriptions and schemas when captureInput=$captureInput", + async ({ api, captureInput }) => { + const spans = setupSpans(undefined, { captureInput }); + const parameters = { type: "object", properties: { order: { type: "string" } } }; + // Each API spells a custom tool's grammar its own way. + const grammar = { syntax: "regex", definition: "\\d+" } as const; + const format = + api === "responses" ? { type: "grammar", ...grammar } : { type: "grammar", grammar }; + const fake = createFakeFetch( + jsonResponse( + api === "responses" + ? { + id: "resp_tools", + object: "response", + status: "completed", + model: "gpt-4.1", + output: [], + usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 }, + } + : { + id: "chatcmpl_tools", + object: "chat.completion", + created: 1, + model: "gpt-4o", + choices: [ + { index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }, + ], + usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }, + }, + ), + ); + const client = clientWith(fake.fetch); + + if (api === "responses") { + await client.responses.create({ + model: "gpt-4.1", + input: "Refund order 42", + tools: [ + { + type: "function", + name: "issue_refund", + description: "Refund", + parameters, + strict: true, + }, + { + type: "custom", + name: "order_id", + description: "An order id", + format: { type: "grammar", ...grammar }, + }, + { type: "web_search" }, + ], + }); + } else { + await client.chat.completions.create({ + model: "gpt-4o", + messages: [{ role: "user", content: "Refund order 42" }], + tools: [ + { + type: "function", + function: { name: "issue_refund", description: "Refund", parameters }, + }, + { + type: "custom", + custom: { + name: "order_id", + description: "An order id", + format: { type: "grammar", grammar }, + }, + }, + ], + }); + } + + const span = await exportedSpan(spans); + expect(jsonAttr(span, "gen_ai.tool.definitions")).toEqual([ + captureInput + ? { type: "function", name: "issue_refund", description: "Refund", parameters } + : { type: "function", name: "issue_refund" }, + captureInput + ? { type: "custom", name: "order_id", description: "An order id", parameters: format } + : { type: "custom", name: "order_id" }, + ...(api === "responses" ? [{ type: "web_search" }] : []), + ]); + }, +); + test("chat completions capture every returned choice with its finish reason", async () => { const spans = setupSpans(); diff --git a/packages/openrouter/README.md b/packages/openrouter/README.md index dfb171cd..9cd8d0ce 100644 --- a/packages/openrouter/README.md +++ b/packages/openrouter/README.md @@ -90,6 +90,8 @@ Responses spans capture: - response model, response ID, output items, status-derived finish reason, and response errors - input, output, total, cached-input, and reasoning-output token counts +Chat and Responses spans also list the request's tools in `gen_ai.tool.definitions`: each tool's type and name, and with `captureInput` on the description and parameters of each function and custom tool (a custom tool's input format), which pass through `mask`. + Embedding spans capture: - request model and input diff --git a/packages/openrouter/src/index.ts b/packages/openrouter/src/index.ts index f5c1d819..e4f38960 100644 --- a/packages/openrouter/src/index.ts +++ b/packages/openrouter/src/index.ts @@ -1,4 +1,5 @@ import { + captureEnabled, MAX_RECORD_BYTES, startSpan, type SpanFields, @@ -402,6 +403,50 @@ function promptAttributes(messages: unknown): SpanFields["attributes"] { return typeof read === "function" ? read(messages) : undefined; } +/** + * The request tools, in the OpenAI format, as `gen_ai.tool.definitions`: each tool's type and + * name, and with input capture on a function or custom tool's description and its parameters + * (custom tools: their input format). Chat nests a tool under `function` or `custom`; Responses + * puts it at the top. A built-in tool without a name is listed by its type. The core SDK also + * strips descriptions and schemas with capture off; this check keeps them out with a core older + * than that rule. + */ +function toolDefinitions(tools: T): Record | undefined { + const list = asArray(tools); + + if (!list) return undefined; + const content = captureEnabled("input"); + + const definitions = list.flatMap((item) => { + const tool = asRecord(item); + const type = readString(tool?.type); + + if (tool === undefined || type === undefined) return []; + const spec = asRecord(type === "custom" ? tool.custom : tool.function) ?? tool; + const name = readString(spec.name); + + if (type !== "function" && type !== "custom") { + return [name === undefined ? { type } : { type, name }]; + } + + if (name === undefined) return []; + + if (!content) return [{ type, name }]; + + // JSON.stringify leaves out the fields a tool does not set. + return [ + { + type, + name, + description: readString(spec.description), + parameters: type === "custom" ? spec.format : spec.parameters, + }, + ]; + }); + + return definitions.length > 0 ? { "gen_ai.tool.definitions": toolsJson(definitions) } : undefined; +} + function chatRequest(request: JsonRecord): RequestMapping { const body = asRecord(request.chatRequest) ?? {}; const model = readString(body.model); @@ -421,7 +466,7 @@ function chatRequest(request: JsonRecord): RequestMapping { seed: readNumber(body.seed), frequencyPenalty: readNumber(body.frequencyPenalty), presencePenalty: readNumber(body.presencePenalty), - attributes: promptAttributes(body.messages), + attributes: { ...toolDefinitions(body.tools), ...promptAttributes(body.messages) }, }, }; } @@ -491,7 +536,7 @@ function responsesRequest(request: JsonRecord): RequestMapping { maxTokens: readNumber(body.maxOutputTokens), frequencyPenalty: readNumber(body.frequencyPenalty), presencePenalty: readNumber(body.presencePenalty), - attributes: promptAttributes(body.input), + attributes: { ...toolDefinitions(body.tools), ...promptAttributes(body.input) }, }, }; } @@ -1833,3 +1878,15 @@ export function uninstrumentOpenRouter(): void { restorePatches = []; installed = false; } + +/** + * The definitions as JSON, or only their types and names when a schema cannot be serialized, + * such as one holding a BigInt or a cycle: the wrapper maps the request outside any catch. + */ +function toolsJson(definitions: Array<{ type: string; name?: string }>): string { + try { + return JSON.stringify(definitions); + } catch { + return JSON.stringify(definitions.map(({ type, name }) => ({ type, name }))); + } +} diff --git a/packages/openrouter/tests/openrouter.test.ts b/packages/openrouter/tests/openrouter.test.ts index 6b43d623..59dd0304 100644 --- a/packages/openrouter/tests/openrouter.test.ts +++ b/packages/openrouter/tests/openrouter.test.ts @@ -2865,3 +2865,73 @@ test("wrapped clients fail open when telemetry is not initialized", async () => expect(fake.requests).toHaveLength(1); expect(response).toMatchObject({ id: "no_telemetry" }); }); + +test.each([ + { api: "chat", captureInput: true }, + { api: "chat", captureInput: false }, + { api: "responses", captureInput: true }, + { api: "responses", captureInput: false }, +] as const)( + "$api records the offered tools, with descriptions and schemas when captureInput=$captureInput", + async ({ api, captureInput }) => { + const spans = new InMemorySpanExporter(); + init( + { + apiKey: "td_live_test", + serviceName: "openrouter-tests", + environment: "test", + exportMode: "immediate", + logLevel: "silent", + captureInput, + fetch: async () => new Response(null, { status: 200 }), + }, + { spanExporter: spans }, + ); + const parameters = { type: "object", properties: { order: { type: "string" } } }; + const format = { type: "grammar", syntax: "regex", definition: "\\d+" } as const; + const fake = createFakeFetcher( + jsonResponse(api === "chat" ? chatBody("chat_tools") : responsesBody("resp_tools")), + ); + const client = clientWith(fake.fetcher); + + if (api === "chat") { + await client.chat.send({ + chatRequest: { + model: "openai/gpt-4o", + messages: [{ role: "user", content: "Refund order 42" }], + tools: [ + { + type: "function", + function: { name: "issue_refund", description: "Refund", parameters }, + }, + ], + }, + }); + } else { + await client.responses.send({ + responsesRequest: { + model: "openai/gpt-4o", + input: "Refund order 42", + tools: [ + { type: "function", name: "issue_refund", description: "Refund", parameters }, + { type: "custom", name: "order_id", description: "An order id", format }, + ], + }, + }); + } + + const span = await exportedSpan(spans); + expect(jsonAttr(span, "gen_ai.tool.definitions")).toEqual([ + captureInput + ? { type: "function", name: "issue_refund", description: "Refund", parameters } + : { type: "function", name: "issue_refund" }, + ...(api === "responses" + ? [ + captureInput + ? { type: "custom", name: "order_id", description: "An order id", parameters: format } + : { type: "custom", name: "order_id" }, + ] + : []), + ]); + }, +); diff --git a/packages/sdk/README.md b/packages/sdk/README.md index d06f4f2f..ad17e0b6 100644 --- a/packages/sdk/README.md +++ b/packages/sdk/README.md @@ -115,9 +115,14 @@ attributes, or events written directly through raw OpenTelemetry APIs. `captureInput: false` and `captureOutput: false` omit captured content. Provider integrations may still record non-content metadata such as response IDs and models, finish reasons, usage, timing, -and error types. Capture flags do not gate stop sequences, tool descriptions and definitions -(`gen_ai.tool.description`, `gen_ai.tool.definitions`), caller-supplied metadata or raw attributes; -redact those separately when needed. +and error types. Capture flags do not gate stop sequences, a tool span's description +(`gen_ai.tool.description`), or caller-supplied metadata or raw attributes; redact those separately +when needed. The one exception is `gen_ai.tool.definitions`, the tools offered to a model: with +input capture off it keeps only each tool's type and name, and with it on it passes through the +mask. Tool descriptions and input schemas are prompt content. Like other content, a list longer +than `maxAttributeLength`, 0 included, keeps only the types and names, so that it stays JSON. The +names follow the limit of raw attributes, where 0 sets no limit, and are left out when they do +not fit. `mask` receives input and output content, system instructions, log messages, log attributes other than numbers and booleans, and content that integrations pass to diff --git a/packages/sdk/src/attrs.ts b/packages/sdk/src/attrs.ts index 8c4af184..7705f528 100644 --- a/packages/sdk/src/attrs.ts +++ b/packages/sdk/src/attrs.ts @@ -182,7 +182,94 @@ export function fieldsToAttributes( // The variables are input, also when the app passes them from promptAttributesFor(). if (!cfg.captureInput) delete attrs["td.prompt.variables"]; + + const tools = attrs[TOOL_DEFINITIONS_KEY]; + + if (tools !== undefined) { + const definitions = toolDefinitionsAttribute(tools, cfg); + + if (definitions === undefined) delete attrs[TOOL_DEFINITIONS_KEY]; + else attrs[TOOL_DEFINITIONS_KEY] = definitions; + } } return attrs; } + +const TOOL_DEFINITIONS_KEY = "gen_ai.tool.definitions"; + +/** + * The `gen_ai.tool.definitions` that a span keeps. Tool descriptions and schemas are prompt + * content: with input capture off only each tool's type and name stay, and with a mask the + * definitions go through it as input does. Like other content, a list longer than + * `maxAttributeLength`, 0 included, keeps only the names, since a cut list is not JSON and + * readers would lose every tool. The names follow the limit of raw attributes, where 0 sets no + * limit; names that do not fit leave the attribute out. The list is + * JSON text, or an array of one JSON text per tool; any other value is dropped with capture off + * or a mask. + */ +function toolDefinitionsAttribute( + value: AttributeValue, + cfg: FieldCaptureConfig, +): AttributeValue | undefined { + const definitions = toolList(value); + + if (definitions === undefined) return cfg.captureInput && !cfg.mask ? value : undefined; + + if (cfg.captureInput) { + const full = cfg.mask + ? prepareCaptureValue(TOOL_DEFINITIONS_KEY, definitions, { + ...cfg, + maxAttributeLength: Number.POSITIVE_INFINITY, + }) + : typeof value === "string" + ? value + : jsonAttr(definitions); + + if (full !== undefined && full.length <= cfg.maxAttributeLength) return full; + } + + const names = definitions.flatMap((definition: unknown) => { + if (typeof definition !== "object" || definition === null) return []; + // OpenAI's Chat Completions form nests the name under `function`. + const { + type, + name, + function: fn, + } = definition as { + type?: unknown; + name?: unknown; + function?: { name?: unknown } | null; + }; + const nested = typeof fn === "object" && fn !== null ? fn.name : undefined; + const named = typeof name === "string" ? name : nested; + const kept = omitUndefined({ + type: typeof type === "string" ? type : undefined, + name: typeof named === "string" ? named : undefined, + }); + + return Object.keys(kept).length > 0 ? [kept] : []; + }); + const json = JSON.stringify(names); + const rawLimit = cfg.maxAttributeLength || Number.POSITIVE_INFINITY; + + return names.length > 0 && json.length <= rawLimit ? json : undefined; +} + +function toolList(value: AttributeValue): unknown[] | undefined { + try { + if (typeof value === "string") { + const parsed: unknown = JSON.parse(value); + + return Array.isArray(parsed) ? parsed : undefined; + } + + if (Array.isArray(value) && value.every((item) => typeof item === "string")) { + return value.map((item) => JSON.parse(item as string) as unknown); + } + } catch { + // Not JSON: no names to keep. + } + + return undefined; +} diff --git a/packages/sdk/tests/capture.test.ts b/packages/sdk/tests/capture.test.ts index ff7ef7b1..02e1b167 100644 --- a/packages/sdk/tests/capture.test.ts +++ b/packages/sdk/tests/capture.test.ts @@ -516,6 +516,88 @@ describe("capture integration", () => { ).toBeUndefined(); }); + test("keeps tool descriptions and schemas only as captured input", async () => { + const definitions = JSON.stringify([ + { + type: "function", + name: "issue_refund", + description: "Refund SECRET orders", + parameters: { type: "object", properties: { order: { type: "string" } } }, + }, + { type: "web_search_20250305", name: "web_search", max_uses: 3 }, + { type: "googleSearch" }, + { description: "a tool without a name or type" }, + ]); + const attributes = { "gen_ai.tool.definitions": definitions }; + const off = setup({ captureInput: false }); + startSpan("off", { attributes }).end(); + startSpan("on", { attributes, captureInput: true }).end(); + startSpan("not-a-list", { + attributes: { "gen_ai.tool.definitions": '{"name":"SECRET"}' }, + }).end(); + // One JSON text per tool, as an attribute array. + startSpan("texts", { + attributes: { + "gen_ai.tool.definitions": [ + '{"type":"function","name":"issue_refund","description":"SECRET"}', + ], + }, + }).end(); + startSpan("nested", { + attributes: { + "gen_ai.tool.definitions": + '[{"type":"function","function":{"name":"lookup","description":"SECRET"}}]', + }, + }).end(); + await flush(); + const byName = (name: string) => + off.spans.getFinishedSpans().find((span) => span.name === name)!.attributes; + const names = + '[{"type":"function","name":"issue_refund"},' + + '{"type":"web_search_20250305","name":"web_search"},{"type":"googleSearch"}]'; + + expect(byName("off")["gen_ai.tool.definitions"]).toBe(names); + expect(byName("on")["gen_ai.tool.definitions"]).toBe(definitions); + expect(byName("not-a-list")["gen_ai.tool.definitions"]).toBeUndefined(); + expect(byName("texts")["gen_ai.tool.definitions"]).toBe( + '[{"type":"function","name":"issue_refund"}]', + ); + expect(byName("nested")["gen_ai.tool.definitions"]).toBe( + '[{"type":"function","name":"lookup"}]', + ); + await shutdown(); + + // A list that the attribute limit would cut keeps its names, which still parse. + const limited = setup({ maxAttributeLength: names.length + 1 }); + startSpan("long", { attributes }).end(); + await flush(); + expect(limited.spans.getFinishedSpans()[0]!.attributes["gen_ai.tool.definitions"]).toBe(names); + await shutdown(); + + // A limit of 0 drops content, but not the names, which it does not limit. + const zero = setup({ maxAttributeLength: 0 }); + startSpan("zero", { attributes }).end(); + await flush(); + expect(zero.spans.getFinishedSpans()[0]!.attributes["gen_ai.tool.definitions"]).toBe(names); + await shutdown(); + + // Names that do not fit a limit above 0 leave the attribute out. + const tiny = setup({ maxAttributeLength: 5 }); + startSpan("tiny", { attributes }).end(); + await flush(); + expect(tiny.spans.getFinishedSpans()[0]!.attributes["gen_ai.tool.definitions"]).toBeUndefined(); + await shutdown(); + + const masked = setup({ + mask: (value) => JSON.parse(JSON.stringify(value).replaceAll("SECRET", "[masked]")), + }); + startSpan("masked", { attributes }).end(); + await flush(); + const value = String(masked.spans.getFinishedSpans()[0]!.attributes["gen_ai.tool.definitions"]); + expect(value).toContain("Refund [masked] orders"); + expect(value).not.toContain("SECRET"); + }); + test("applies the attribute limit to metadata", async () => { const { spans } = setup({ maxAttributeLength: 50 }); startSpan("meta", { metadata: { blob: "z".repeat(200) } }).end(); diff --git a/sdks/python-anthropic/README.md b/sdks/python-anthropic/README.md index d63c3e5d..2660ac08 100644 --- a/sdks/python-anthropic/README.md +++ b/sdks/python-anthropic/README.md @@ -80,7 +80,7 @@ capture is disabled, response IDs and models, finish reasons, usage, timing, and be recorded. Capture flags do not gate stop sequences or caller-supplied metadata or raw attributes; redact those separately when needed. Exception messages and stack traces are recorded only when both -`capture_input` and `capture_output` are on, and pass through `mask`. Request tools and `tool_choice` are part of the captured input, so `capture_input=False` removes them. Each tool's type and name are still recorded in `gen_ai.tool.definitions`, and `mask` does not apply to them; descriptions and input schemas are not. +`capture_input` and `capture_output` are on, and pass through `mask`. Request tools and `tool_choice` are part of the captured input, so `capture_input=False` removes them. Each tool's type and name are still recorded in `gen_ai.tool.definitions`. With `capture_input` on, that attribute also holds each custom tool's description and input schema (as `parameters`), and passes through `mask`; with it off, it holds only the types and names. `messages.stream()` starts the span when the context manager is entered, because that is when the Anthropic SDK opens the HTTP stream. diff --git a/sdks/python-anthropic/src/telemetry_dev_anthropic/__init__.py b/sdks/python-anthropic/src/telemetry_dev_anthropic/__init__.py index 5bb2f962..5c633eaa 100644 --- a/sdks/python-anthropic/src/telemetry_dev_anthropic/__init__.py +++ b/sdks/python-anthropic/src/telemetry_dev_anthropic/__init__.py @@ -246,20 +246,33 @@ def _tool_definitions(value: Any) -> Any: def _offered_tools(tools: Any) -> dict[str, str] | None: - # Names are recorded regardless of capture flags, as on tool spans; descriptions and schemas - # stay in the input. - definitions: list[dict[str, str]] = [] + """Each request tool as ``gen_ai.tool.definitions``: its type and name, and with input capture + on a custom tool's description and input schema as ``parameters``. Names are recorded + regardless of capture flags, as on tool spans. The core SDK also strips the description and + schema with capture off; this check keeps them out with a core older than that rule.""" + client = telemetry_dev.get_client() + content = client is not None and client.capture_input + definitions: list[dict[str, Any]] = [] for tool in _sequence_items(tools): if not isinstance(tool, Mapping): continue fields = cast(Mapping[str, Any], tool) name = _string(fields.get("name")) kind = _string(fields.get("type")) - if name is not None: - definitions.append( - {"type": "function" if kind in (None, "custom") else kind, "name": name} - ) - return {"gen_ai.tool.definitions": json_dumps(definitions)} if definitions else None + if name is None: + continue + if kind not in (None, "custom"): + definitions.append({"type": kind, "name": name}) + continue + definition: dict[str, Any] = {"type": "function", "name": name} + if content: + description = _string(fields.get("description")) + if description is not None: + definition["description"] = description + if "input_schema" in fields: + definition["parameters"] = _native(fields["input_schema"]) + definitions.append(definition) + return {"gen_ai.tool.definitions": _tools_json(definitions)} if definitions else None def _add_prompt(fields: Mapping[str, Any], messages: object) -> dict[str, Any]: @@ -1958,3 +1971,14 @@ def uninstrument_anthropic() -> None: __all__ = ["__version__", "instrument_anthropic", "uninstrument_anthropic", "wrap_anthropic"] + + +def _tools_json(definitions: list[dict[str, Any]]) -> str: + """The definitions as JSON, or only their types and names when a schema cannot be + serialized, such as one holding a cycle: the wrapper maps the request outside any catch.""" + try: + return json_dumps(definitions) + except (TypeError, ValueError): + return json_dumps( + [{key: tool[key] for key in ("type", "name") if key in tool} for tool in definitions] + ) diff --git a/sdks/python-anthropic/tests/test_anthropic.py b/sdks/python-anthropic/tests/test_anthropic.py index 22aaa908..56fcc9e1 100644 --- a/sdks/python-anthropic/tests/test_anthropic.py +++ b/sdks/python-anthropic/tests/test_anthropic.py @@ -751,10 +751,15 @@ def handler(request: httpx.Request) -> httpx.Response: ) a = attrs(only_span(memory)) - # The dashboard lists these names as the tools offered; schemas stay in the captured input. + # With input capture on, a custom tool's description and schema say what the tool accepts. assert json.loads(str(a["gen_ai.tool.definitions"])) == [ - {"type": "function", "name": "get_weather"}, - {"type": "function", "name": "issue_refund"}, + { + "type": "function", + "name": "get_weather", + "description": "Get weather", + "parameters": tool["input_schema"], + }, + {"type": "function", "name": "issue_refund", "parameters": {"type": "object"}}, {"type": "web_search_20250305", "name": "web_search"}, ] assert json.loads(str(a["gen_ai.output.messages"])) == [ @@ -816,7 +821,12 @@ def get_weather(city: str) -> str: assert captured["tools"] == requests[0]["tools"] assert captured["tools"][0]["name"] == "get_weather" assert json.loads(str(a["gen_ai.tool.definitions"])) == [ - {"type": "function", "name": "get_weather"} + { + "type": "function", + "name": "get_weather", + "description": captured["tools"][0]["description"], + "parameters": captured["tools"][0]["input_schema"], + } ] diff --git a/sdks/python-bedrock/src/telemetry_dev_bedrock/_registry.py b/sdks/python-bedrock/src/telemetry_dev_bedrock/_registry.py index fa240d17..4c71b4cc 100644 --- a/sdks/python-bedrock/src/telemetry_dev_bedrock/_registry.py +++ b/sdks/python-bedrock/src/telemetry_dev_bedrock/_registry.py @@ -5,6 +5,7 @@ from typing import Any, Literal, cast import telemetry_dev +from telemetry_dev._serialize import json_dumps from ._fields import ( PROVIDER, @@ -44,6 +45,40 @@ def _model(params: dict[str, Any]) -> str | None: return params.get("modelId") if isinstance(params.get("modelId"), str) else None +def _tool_definitions(tool_config: Any) -> dict[str, str]: + """The tools of ``toolConfig`` as ``gen_ai.tool.definitions``: each tool's name, and with + input capture on its description and the JSON Schema of its input. A system tool is listed + as ``system_tool``. The core SDK also strips descriptions and schemas with capture off; this + check keeps them out with a core older than that rule.""" + tools = tool_config.get("tools") if isinstance(tool_config, dict) else None + if not isinstance(tools, list): + return {} + client = telemetry_dev.get_client() + content = client is not None and client.capture_input + definitions: list[dict[str, Any]] = [] + for tool in cast("list[Any]", tools): + if not isinstance(tool, dict): + continue + fields = cast("dict[str, Any]", tool) + system = fields.get("systemTool") + if isinstance(system, dict) and isinstance(system.get("name"), str): + definitions.append({"type": "system_tool", "name": system["name"]}) + continue + spec = fields.get("toolSpec") + if not isinstance(spec, dict) or not isinstance(spec.get("name"), str): + continue + spec = cast("dict[str, Any]", spec) + definition: dict[str, Any] = {"type": "function", "name": spec["name"]} + if content: + if isinstance(spec.get("description"), str): + definition["description"] = spec["description"] + schema = spec.get("inputSchema") + if isinstance(schema, dict) and "json" in schema: + definition["parameters"] = schema["json"] + definitions.append(definition) + return {"gen_ai.tool.definitions": _tools_json(definitions)} if definitions else {} + + def _converse_request(params: dict[str, Any]) -> dict[str, Any]: inference = ( params.get("inferenceConfig") if isinstance(params.get("inferenceConfig"), dict) else {} @@ -57,7 +92,11 @@ def _converse_request(params: dict[str, Any]) -> dict[str, Any]: "model": _model(params), "input": normalize_messages(params.get("messages")), "system_instructions": normalize_content_list(params.get("system")) or None, - "attributes": prompt_attributes(params.get("messages")) or None, + "attributes": { + **_tool_definitions(params.get("toolConfig")), + **prompt_attributes(params.get("messages")), + } + or None, "temperature": inference.get("temperature"), "top_p": inference.get("topP"), "max_tokens": inference.get("maxTokens"), @@ -530,3 +569,14 @@ def lookup_operation(service_name: str, operation_name: str) -> OperationSpec | if service is None: return None return service.get(operation_name) + + +def _tools_json(definitions: list[dict[str, Any]]) -> str: + """The definitions as JSON, or only their types and names when a schema cannot be + serialized, such as one holding a cycle: the wrapper maps the request outside any catch.""" + try: + return json_dumps(definitions) + except (TypeError, ValueError): + return json_dumps( + [{key: tool[key] for key in ("type", "name") if key in tool} for tool in definitions] + ) diff --git a/sdks/python-bedrock/tests/test_bedrock.py b/sdks/python-bedrock/tests/test_bedrock.py index 77a34667..88a9398b 100644 --- a/sdks/python-bedrock/tests/test_bedrock.py +++ b/sdks/python-bedrock/tests/test_bedrock.py @@ -226,6 +226,18 @@ def test_converse_happy_path(memory: SimpleNamespace, monkeypatch: pytest.Monkey ], "system": [{"text": "be terse"}], "inferenceConfig": {"temperature": 0.1, "topP": 0.9, "maxTokens": 10}, + "toolConfig": { + "tools": [ + { + "toolSpec": { + "name": "weather", + "description": "Weather for a city", + "inputSchema": {"json": {"type": "object"}}, + } + }, + {"cachePoint": {"type": "default"}}, + ] + }, } request_snapshot = copy.deepcopy(request) calls = _stub_api_call( @@ -271,6 +283,14 @@ def test_converse_happy_path(memory: SimpleNamespace, monkeypatch: pytest.Monkey assert span.attributes["gen_ai.usage.total_tokens"] == 3 + 1 + 2 + 4 assert span.attributes["gen_ai.usage.cache_creation.input_tokens"] == 2 assert span.attributes["td.metadata.server_latency_ms"] == "12" + assert _json_attr(span, "gen_ai.tool.definitions") == [ + { + "type": "function", + "name": "weather", + "description": "Weather for a city", + "parameters": {"type": "object"}, + } + ] assert _json_attr(span, "gen_ai.input.messages") == [ { "role": "user", diff --git a/sdks/python-google-genai/README.md b/sdks/python-google-genai/README.md index eaa30579..e38c3b07 100644 --- a/sdks/python-google-genai/README.md +++ b/sdks/python-google-genai/README.md @@ -97,7 +97,7 @@ The integration maps native Gemini request/response shapes directly. It never mu Block, safety, grounding, and URL-context metadata are raw attributes, which the core's `capture_output` check and mask never see. The block reason message is free text. Grounding metadata repeats the answer text segment by segment and can carry retrieved document text, source titles and URIs, and search queries; URL-context metadata lists the retrieved URLs. This metadata is recorded whole only when output is captured and no mask is configured. Otherwise `google_genai.response.block_reason_message` is omitted and the other attributes keep only their structure: the block reason; each safety rating's category, probability, severity, their scores, `blocked`, and overwritten threshold, with enum fields kept only when they look like an enum value (such as `HARM_CATEGORY_HARASSMENT`); each grounding chunk's source type (such as `{"web": {}}`), segment offsets, chunk indices, confidence scores, and the dynamic retrieval score; and each URL's retrieval status. -Tool definitions (`gen_ai.tool.definitions`, including tool descriptions and parameter schemas) are request attributes, not captured content: `capture_input`, the mask, and `max_attribute_length=0` do not remove them. Like other raw attributes, they are cut at `max_attribute_length` without a marker, and are sent whole when `max_attribute_length` is 0 or `None` (the default). With `telemetry-dev` 0.3.2 or earlier, they are cut at 65,536 characters by default and when `max_attribute_length` is 0; those versions do not accept `None`. +Tool definitions (`gen_ai.tool.definitions`) always hold each tool's type and name. Tool descriptions and parameter schemas are prompt content: they are recorded only with `capture_input` on, and pass through the mask. When the whole list is longer than `max_attribute_length`, 0 included, it keeps only each tool's type and name, so that it stays JSON, and it is left out when those do not fit either (0 sets no limit for them). With `telemetry-dev` 0.3.2 or earlier, the attribute is cut at 65,536 characters by default and when `max_attribute_length` is 0. ## Streaming diff --git a/sdks/python-google-genai/src/telemetry_dev_google_genai/__init__.py b/sdks/python-google-genai/src/telemetry_dev_google_genai/__init__.py index ae2634fb..5c1cfcc1 100644 --- a/sdks/python-google-genai/src/telemetry_dev_google_genai/__init__.py +++ b/sdks/python-google-genai/src/telemetry_dev_google_genai/__init__.py @@ -312,9 +312,14 @@ def _output_type(config: Any) -> str | None: def _tool_definitions(tools: Any) -> str | None: + """The request tools as ``gen_ai.tool.definitions``. Descriptions and schemas are prompt + content and need input capture on. The core SDK also strips them with capture off; this + check keeps them out with a core older than that rule.""" items = _sequence_items(tools) if not items: return None + client = telemetry_dev.get_client() + content = client is not None and client.capture_input definitions: list[Any] = [] for tool in items: if callable(tool): @@ -337,6 +342,10 @@ def _tool_definitions(tools: Any) -> str | None: if not isinstance(decl_native, Mapping): continue entry: dict[str, Any] = {"type": "function", "name": decl_native.get("name")} + if not content: + if entry["name"]: + definitions.append(entry) + continue if decl_native.get("description") is not None: entry["description"] = decl_native.get("description") parameters = decl_native.get("parameters") @@ -355,7 +364,10 @@ def _tool_definitions(tools: Any) -> str | None: definitions.append({"type": type_name}) if not definitions: return None - return _json_attr(definitions) + # A schema that cannot be serialized leaves the types and names. + return _json_attr(definitions) or _json_attr( + [{key: tool[key] for key in ("type", "name") if key in tool} for tool in definitions] + ) def _request_attributes(config: Any) -> dict[str, Any]: diff --git a/sdks/python-litellm/src/telemetry_dev_litellm/__init__.py b/sdks/python-litellm/src/telemetry_dev_litellm/__init__.py index 208be8b9..412b0786 100644 --- a/sdks/python-litellm/src/telemetry_dev_litellm/__init__.py +++ b/sdks/python-litellm/src/telemetry_dev_litellm/__init__.py @@ -16,6 +16,7 @@ import litellm import telemetry_dev from opentelemetry import trace +from telemetry_dev._serialize import json_dumps __version__ = "0.2.7" @@ -505,6 +506,39 @@ def _prompt_attributes(messages: object) -> dict[str, Any]: return cast("dict[str, Any]", read(messages)) if callable(read) else {} +def _tool_definitions(tools: Any) -> dict[str, str] | None: + """The request tools, in the OpenAI format, as ``gen_ai.tool.definitions``: each tool's type + and name, and with input capture on a function or custom tool's description and its + parameters (custom tools: their input format). Chat Completions nests a tool under + ``function`` or ``custom``; Responses puts it at the top. A built-in tool without a name is + listed by its type. The core SDK also strips descriptions and schemas with capture off; this + check keeps them out with a core older than that rule.""" + client = telemetry_dev.get_client() + content = client is not None and client.capture_input + definitions: list[dict[str, Any]] = [] + for tool in _sequence_items(tools): + kind = _string(_field(tool, "type")) + if kind is None: + continue + spec = _field(tool, "custom" if kind == "custom" else "function") or tool + name = _string(_field(spec, "name")) + if kind not in ("function", "custom"): + definitions.append({"type": kind} if name is None else {"type": kind, "name": name}) + continue + if name is None: + continue + definition: dict[str, Any] = {"type": kind, "name": name} + if content: + description = _string(_field(spec, "description")) + if description is not None: + definition["description"] = description + parameters = _field(spec, "format" if kind == "custom" else "parameters") + if parameters is not None: + definition["parameters"] = parameters + definitions.append(definition) + return {"gen_ai.tool.definitions": _tools_json(definitions)} if definitions else None + + def _completion_request( args: tuple[Any, ...], kwargs: Mapping[str, Any] ) -> tuple[str, dict[str, Any]]: @@ -528,7 +562,11 @@ def _completion_request( "presence_penalty": _number(kwargs.get("presence_penalty")), "output_type": _output_type(kwargs.get("response_format")), "metadata": _request_metadata(kwargs), - "attributes": _prompt_attributes(_arg(args, kwargs, "messages", 1)) or None, + "attributes": { + **(_tool_definitions(kwargs.get("tools")) or {}), + **_prompt_attributes(_arg(args, kwargs, "messages", 1)), + } + or None, }, ) @@ -598,6 +636,7 @@ def _responses_request( input_value, input_budget = _bounded_responses_native(_arg(args, kwargs, "input", 0)) attributes: dict[str, Any] = { "gen_ai.operation.name": "chat", + **(_tool_definitions(kwargs.get("tools")) or {}), **_prompt_attributes(_arg(args, kwargs, "input", 0)), } if input_budget is not None and input_budget.truncated: @@ -2356,3 +2395,14 @@ def wrap_router(router: _T) -> _T: "uninstrument_litellm", "wrap_router", ] + + +def _tools_json(definitions: list[dict[str, Any]]) -> str: + """The definitions as JSON, or only their types and names when a schema cannot be + serialized, such as one holding a cycle: the wrapper maps the request outside any catch.""" + try: + return json_dumps(definitions) + except (TypeError, ValueError): + return json_dumps( + [{key: tool[key] for key in ("type", "name") if key in tool} for tool in definitions] + ) diff --git a/sdks/python-litellm/tests/test_litellm.py b/sdks/python-litellm/tests/test_litellm.py index 4945cc0b..b38b4741 100644 --- a/sdks/python-litellm/tests/test_litellm.py +++ b/sdks/python-litellm/tests/test_litellm.py @@ -4323,3 +4323,32 @@ def hold() -> None: pytest.fail("The forked process did not end in 10 s") time.sleep(0.01) assert os.waitstatus_to_exitcode(waited[1]) == 0 + + +def test_completion_records_the_offered_tools(memory: SimpleNamespace) -> None: + instrument_litellm() + parameters = {"type": "object", "properties": {"city": {"type": "string"}}} + llm.completion( + model="gpt-4o-mini", + messages=[{"role": "user", "content": "weather"}], + tools=[ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Weather", + "parameters": parameters, + }, + } + ], + mock_response="Sunny.", + ) + + assert json_attr(attrs(only_span(memory))["gen_ai.tool.definitions"]) == [ + { + "type": "function", + "name": "get_weather", + "description": "Weather", + "parameters": parameters, + } + ] diff --git a/sdks/python-openai/README.md b/sdks/python-openai/README.md index cd803836..b802c124 100644 --- a/sdks/python-openai/README.md +++ b/sdks/python-openai/README.md @@ -80,7 +80,7 @@ Chat completion streams are traced. Requests are sent unchanged by default, so t Streamed chat output is kept up to 16 MiB, and all streams in flight share the `max_stream_bytes` bound of the core (64 MiB by default). These bounds need a `telemetry-dev` core with `max_stream_bytes`; with an older core, each stream keeps up to 64 KiB and 1,024 items. Each streamed finish reason is cut to its first 128 characters, without setting `telemetry.dev.capture.truncated`, and the finish reasons of a stream have their own budget, which fits at least 1,000 of them; the configured `max_attribute_length` does not shrink these retention bounds; the core applies it to the exported attribute after the mask runs, with its `...[truncated]` marker, without setting `telemetry.dev.capture.truncated`. A chat stream inspects at most 1,000 choices and 1,000 tool calls in each chunk; past these caps the rest is not kept and `telemetry.dev.capture.truncated` is set. When present, `gen_ai.output.messages` contains bounded partial output. If output and/or finish-reason capture is incomplete, including when a choice ends without `finish_reason`, `telemetry.dev.capture.truncated` is `true`. With a mask configured, incomplete output is omitted because the mask cannot inspect the complete value. When output capture is disabled or omitted, response IDs and models, finish reasons, usage, timing, and errors may still be recorded. -Capture flags do not gate stop sequences or caller-supplied metadata or raw attributes; redact those separately when needed. Exception messages and stack traces are recorded only when both `capture_input` and `capture_output` are on, and pass through `mask`. +Capture flags do not gate stop sequences or caller-supplied metadata or raw attributes; redact those separately when needed. Exception messages and stack traces are recorded only when both `capture_input` and `capture_output` are on, and pass through `mask`. Model spans list the request's tools in `gen_ai.tool.definitions`: each tool's type and name, and with `capture_input` on the description and parameters (a custom tool's input format) of each function and custom tool, which pass through `mask`. ```py client = wrap_openai(OpenAI(), inject_stream_usage=True) diff --git a/sdks/python-openai/src/telemetry_dev_openai/__init__.py b/sdks/python-openai/src/telemetry_dev_openai/__init__.py index d921f976..7fd5eba6 100644 --- a/sdks/python-openai/src/telemetry_dev_openai/__init__.py +++ b/sdks/python-openai/src/telemetry_dev_openai/__init__.py @@ -22,6 +22,7 @@ from openai.resources.embeddings import AsyncEmbeddings, Embeddings from openai.resources.images import AsyncImages, Images from openai.resources.responses.responses import AsyncResponses, Responses +from telemetry_dev._serialize import json_dumps __version__ = "0.2.6" @@ -435,9 +436,45 @@ def _prompt_attributes(messages: object) -> dict[str, Any]: return cast("dict[str, Any]", read(messages)) if callable(read) else {} +def _tool_definitions(tools: Any) -> dict[str, str] | None: + """The request tools as ``gen_ai.tool.definitions``: each tool's type and name, and with input + capture on a function or custom tool's description and its parameters (custom tools: their + input format). Chat Completions nests a tool under ``function`` or ``custom``; Responses puts + it at the top. A built-in tool without a name, such as ``web_search``, is listed by its type. + The core SDK also strips descriptions and schemas with capture off; this check keeps them out + with a core older than that rule.""" + client = telemetry_dev.get_client() + content = client is not None and client.capture_input + definitions: list[dict[str, Any]] = [] + for tool in _sequence_items(tools): + kind = _string(_field(tool, "type")) + if kind is None: + continue + spec = _field(tool, "custom" if kind == "custom" else "function") or tool + name = _string(_field(spec, "name")) + if kind not in ("function", "custom"): + definitions.append({"type": kind} if name is None else {"type": kind, "name": name}) + continue + if name is None: + continue + definition: dict[str, Any] = {"type": kind, "name": name} + if content: + description = _string(_field(spec, "description")) + if description is not None: + definition["description"] = description + parameters = _field(spec, "format" if kind == "custom" else "parameters") + if parameters is not None: + definition["parameters"] = parameters + definitions.append(definition) + return {"gen_ai.tool.definitions": _tools_json(definitions)} if definitions else None + + def _chat_request(params: Mapping[str, Any]) -> tuple[str, dict[str, Any]]: model = _string(params.get("model")) - attributes = _prompt_attributes(params.get("messages")) + attributes = { + **(_tool_definitions(params.get("tools")) or {}), + **_prompt_attributes(params.get("messages")), + } captured, truncated = _bounded_responses_capture(params.get("messages"), "input") if truncated: attributes["telemetry.dev.capture.truncated"] = True @@ -521,7 +558,10 @@ def _chat_response(response: Any) -> dict[str, Any]: def _responses_request(params: Mapping[str, Any]) -> tuple[str, dict[str, Any]]: model = _string(params.get("model")) - attributes = _prompt_attributes(params.get("input")) + attributes = { + **(_tool_definitions(params.get("tools")) or {}), + **_prompt_attributes(params.get("input")), + } captured, truncated = _bounded_responses_capture(params.get("input"), "input") if truncated: attributes["telemetry.dev.capture.truncated"] = True @@ -3231,3 +3271,14 @@ def uninstrument_openai() -> None: __all__ = ["__version__", "instrument_openai", "uninstrument_openai", "wrap_openai"] + + +def _tools_json(definitions: list[dict[str, Any]]) -> str: + """The definitions as JSON, or only their types and names when a schema cannot be + serialized, such as one holding a cycle: the wrapper maps the request outside any catch.""" + try: + return json_dumps(definitions) + except (TypeError, ValueError): + return json_dumps( + [{key: tool[key] for key in ("type", "name") if key in tool} for tool in definitions] + ) diff --git a/sdks/python-openai/tests/test_openai.py b/sdks/python-openai/tests/test_openai.py index 263e8a7d..42782f45 100644 --- a/sdks/python-openai/tests/test_openai.py +++ b/sdks/python-openai/tests/test_openai.py @@ -5376,3 +5376,84 @@ def hold() -> None: pytest.fail("The forked process did not end in 10 s") time.sleep(0.01) assert os.waitstatus_to_exitcode(waited[1]) == 0 + + +@pytest.mark.parametrize( + ("api", "capture_input"), + [("chat", True), ("chat", False), ("responses", True), ("responses", False)], +) +def test_offered_tools_are_recorded_with_descriptions_and_schemas_as_input( + make: Callable[..., SimpleNamespace], api: str, capture_input: bool +) -> None: + memory = make(capture_input=capture_input) + parameters = {"type": "object", "properties": {"order": {"type": "string"}}} + grammar = {"type": "grammar", "syntax": "regex", "definition": "\\d+"} + payload = response_payload() if api == "responses" else chat_completion() + client = wrap_openai(sync_client(lambda _request: json_response(payload))) + if api == "responses": + client.responses.create( + model="gpt-4.1", + input="Refund order 42", + tools=cast( + Any, + [ + { + "type": "function", + "name": "issue_refund", + "description": "Refund", + "parameters": parameters, + "strict": True, + }, + { + "type": "custom", + "name": "order_id", + "description": "An order id", + "format": grammar, + }, + {"type": "web_search"}, + ], + ), + ) + else: + client.chat.completions.create( + model="gpt-4o", + messages=cast(Any, CHAT_MESSAGES), + tools=cast( + Any, + [ + { + "type": "function", + "function": { + "name": "issue_refund", + "description": "Refund", + "parameters": parameters, + }, + }, + { + "type": "custom", + "custom": { + "name": "order_id", + "description": "An order id", + "format": grammar, + }, + }, + ], + ), + ) + + expected: list[dict[str, Any]] = [ + { + "type": "function", + "name": "issue_refund", + "description": "Refund", + "parameters": parameters, + } + if capture_input + else {"type": "function", "name": "issue_refund"}, + {"type": "custom", "name": "order_id", "description": "An order id", "parameters": grammar} + if capture_input + else {"type": "custom", "name": "order_id"}, + ] + if api == "responses": + expected.append({"type": "web_search"}) + assert json.loads(str(attrs(only_span(memory))["gen_ai.tool.definitions"])) == expected diff --git a/sdks/python-openrouter/README.md b/sdks/python-openrouter/README.md index b9791733..f0795077 100644 --- a/sdks/python-openrouter/README.md +++ b/sdks/python-openrouter/README.md @@ -74,6 +74,10 @@ input, supported sampling parameters, response model and ID, finish reasons, out token usage. Embedding spans capture the request input, request and response models, and token usage; embedding vectors are intentionally not captured as output. +Generation spans also list the request's tools in `gen_ai.tool.definitions`: each tool's type and +name, and with `capture_input` on the description and parameters of each function and custom tool +(a custom tool's input format), which pass through `mask`. + When OpenRouter returns cost information, the integration records `gen_ai.usage.cost` from `usage.cost`. If that field is absent, it falls back to `usage.cost_details.upstream_inference_cost`. The cost attribute is omitted when neither value is diff --git a/sdks/python-openrouter/src/telemetry_dev_openrouter/__init__.py b/sdks/python-openrouter/src/telemetry_dev_openrouter/__init__.py index 3ae3c546..79d7e036 100644 --- a/sdks/python-openrouter/src/telemetry_dev_openrouter/__init__.py +++ b/sdks/python-openrouter/src/telemetry_dev_openrouter/__init__.py @@ -14,6 +14,7 @@ from openrouter.chat import Chat from openrouter.embeddings import Embeddings from openrouter.responses import Responses +from telemetry_dev._serialize import json_dumps __version__ = "0.2.6" @@ -196,6 +197,39 @@ def _prompt_attributes(messages: object) -> dict[str, Any]: return cast("dict[str, Any]", read(messages)) if callable(read) else {} +def _tool_definitions(tools: Any) -> dict[str, str] | None: + """The request tools, in the OpenAI format, as ``gen_ai.tool.definitions``: each tool's type + and name, and with input capture on a function or custom tool's description and its + parameters (custom tools: their input format). Chat Completions nests a tool under + ``function`` or ``custom``; Responses puts it at the top. A built-in tool without a name is + listed by its type. The core SDK also strips descriptions and schemas with capture off; this + check keeps them out with a core older than that rule.""" + client = telemetry_dev.get_client() + content = client is not None and client.capture_input + definitions: list[dict[str, Any]] = [] + for tool in _sequence_items(tools): + kind = _string(_field(tool, "type")) + if kind is None: + continue + spec = _field(tool, "custom" if kind == "custom" else "function") or tool + name = _string(_field(spec, "name")) + if kind not in ("function", "custom"): + definitions.append({"type": kind} if name is None else {"type": kind, "name": name}) + continue + if name is None: + continue + definition: dict[str, Any] = {"type": kind, "name": name} + if content: + description = _string(_field(spec, "description")) + if description is not None: + definition["description"] = description + parameters = _field(spec, "format" if kind == "custom" else "parameters") + if parameters is not None: + definition["parameters"] = parameters + definitions.append(definition) + return {"gen_ai.tool.definitions": _tools_json(definitions)} if definitions else None + + def _chat_request(params: Mapping[str, Any]) -> tuple[str, dict[str, Any]]: model = _string(params.get("model")) max_completion_tokens = _number(params.get("max_completion_tokens")) @@ -215,7 +249,11 @@ def _chat_request(params: Mapping[str, Any]) -> tuple[str, dict[str, Any]]: "seed": _number(params.get("seed")), "frequency_penalty": _number(params.get("frequency_penalty")), "presence_penalty": _number(params.get("presence_penalty")), - "attributes": _prompt_attributes(params.get("messages")) or None, + "attributes": { + **(_tool_definitions(params.get("tools")) or {}), + **_prompt_attributes(params.get("messages")), + } + or None, }, ) @@ -283,7 +321,11 @@ def _responses_request(params: Mapping[str, Any]) -> tuple[str, dict[str, Any]]: "max_tokens": _number(params.get("max_output_tokens")), "frequency_penalty": _number(params.get("frequency_penalty")), "presence_penalty": _number(params.get("presence_penalty")), - "attributes": _prompt_attributes(params.get("input")) or None, + "attributes": { + **(_tool_definitions(params.get("tools")) or {}), + **_prompt_attributes(params.get("input")), + } + or None, }, ) @@ -1994,3 +2036,14 @@ def uninstrument_openrouter() -> None: "uninstrument_openrouter", "wrap_open_router", ] + + +def _tools_json(definitions: list[dict[str, Any]]) -> str: + """The definitions as JSON, or only their types and names when a schema cannot be + serialized, such as one holding a cycle: the wrapper maps the request outside any catch.""" + try: + return json_dumps(definitions) + except (TypeError, ValueError): + return json_dumps( + [{key: tool[key] for key in ("type", "name") if key in tool} for tool in definitions] + ) diff --git a/sdks/python-openrouter/tests/test_openrouter.py b/sdks/python-openrouter/tests/test_openrouter.py index 0ea44d79..b05e44f0 100644 --- a/sdks/python-openrouter/tests/test_openrouter.py +++ b/sdks/python-openrouter/tests/test_openrouter.py @@ -2846,3 +2846,34 @@ def hold() -> None: pytest.fail("The forked process did not end in 10 s") time.sleep(0.01) assert os.waitstatus_to_exitcode(waited[1]) == 0 + + +def test_chat_send_records_the_offered_tools(memory: SimpleNamespace) -> None: + parameters = {"type": "object", "properties": {"city": {"type": "string"}}} + client = wrap_open_router(sync_client(lambda _request: json_response(chat_payload()))) + client.chat.send( + model="openai/gpt-4o-mini", + messages=CHAT_MESSAGES, + tools=cast( + Any, + [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Weather", + "parameters": parameters, + }, + } + ], + ), + ) + + assert json.loads(str(attrs(only_span(memory))["gen_ai.tool.definitions"])) == [ + { + "type": "function", + "name": "get_weather", + "description": "Weather", + "parameters": parameters, + } + ] diff --git a/sdks/python/README.md b/sdks/python/README.md index fbc03d26..a0cd8372 100644 --- a/sdks/python/README.md +++ b/sdks/python/README.md @@ -182,9 +182,14 @@ single record larger than the bound is still queued when its queue is empty. `capture_input=False` and `capture_output=False` omit captured content. Provider integrations may still record non-content metadata such as response IDs and models, finish reasons, usage, timing, -and error types. Capture flags do not gate stop sequences, tool descriptions and definitions -(`gen_ai.tool.description`, `gen_ai.tool.definitions`), caller-supplied metadata or raw attributes; -redact those separately when needed. +and error types. Capture flags do not gate stop sequences, a tool span's description +(`gen_ai.tool.description`), or caller-supplied metadata or raw attributes; redact those separately +when needed. The one exception is `gen_ai.tool.definitions`, the tools offered to a model: with +input capture off it keeps only each tool's type and name, and with it on it passes through the +mask. Tool descriptions and input schemas are prompt content. Like other content, a list longer +than `max_attribute_length`, 0 included, keeps only the types and names, so that it stays JSON. The +names follow the limit of raw attributes, where 0 sets no limit, and are left out when they do +not fit. `mask` receives input and output content, system instructions, log messages, captured exception messages and stack traces, and content that diff --git a/sdks/python/src/telemetry_dev/_semconv.py b/sdks/python/src/telemetry_dev/_semconv.py index cfb79b75..7580fb63 100644 --- a/sdks/python/src/telemetry_dev/_semconv.py +++ b/sdks/python/src/telemetry_dev/_semconv.py @@ -71,6 +71,7 @@ ATTR_TOOL_NAME = "gen_ai.tool.name" ATTR_TOOL_CALL_ID = "gen_ai.tool.call.id" ATTR_TOOL_DESCRIPTION = "gen_ai.tool.description" +ATTR_TOOL_DEFINITIONS = "gen_ai.tool.definitions" ATTR_TOOL_ARGUMENTS = "gen_ai.tool.call.arguments" ATTR_TOOL_RESULT = "gen_ai.tool.call.result" ATTR_AGENT_NAME = "gen_ai.agent.name" diff --git a/sdks/python/src/telemetry_dev/_spans.py b/sdks/python/src/telemetry_dev/_spans.py index 334d7ca4..1ac03562 100644 --- a/sdks/python/src/telemetry_dev/_spans.py +++ b/sdks/python/src/telemetry_dev/_spans.py @@ -1,5 +1,6 @@ from __future__ import annotations +import json import math import sys import threading @@ -48,6 +49,7 @@ ATTR_SYSTEM_INSTRUCTIONS, ATTR_TIME_TO_FIRST_CHUNK, ATTR_TOOL_CALL_ID, + ATTR_TOOL_DEFINITIONS, ATTR_TOOL_DESCRIPTION, ATTR_TOOL_NAME, DURATION_BUCKETS, @@ -61,7 +63,13 @@ input_key, output_key, ) -from ._serialize import AttributeValue, coerce_attr_value +from ._serialize import ( + AttributeValue, + coerce_attr_value, + json_dumps, + serialize_content, + utf16_length, +) class _NotGiven: @@ -377,6 +385,15 @@ def _fields_to_attributes( # The variables are input, also when the app passes them from prompt_attributes_for(). if key == ATTR_PROMPT_VARIABLES and not state.capture_input: continue + if key == ATTR_TOOL_DEFINITIONS: + definitions = _tool_list(value) + if definitions is not None: + kept = _tool_definitions(client, state, value, definitions) + if kept is not None: + attrs[key] = kept + continue + if not state.capture_input or client.mask is not None: + continue attr = coerce_attr_value( value, max_len=sys.maxsize, @@ -389,6 +406,69 @@ def _fields_to_attributes( return attrs +def _tool_list(value: Any) -> list[Any] | None: + """The tools of a ``gen_ai.tool.definitions`` value: JSON text, a list of one JSON text per + tool, or a list of tool objects. None for any other value.""" + try: + if isinstance(value, str): + parsed = json.loads(value) + return cast("list[Any]", parsed) if isinstance(parsed, list) else None + if isinstance(value, (list, tuple)): + items = cast("Sequence[Any]", value) + if all(isinstance(item, str) for item in items): + return [json.loads(item) for item in items] + return list(items) + except (ValueError, RecursionError): + pass + return None + + +def _tool_definitions( + client: Client, state: _SpanState, value: Any, definitions: list[Any] +) -> str | None: + """The ``gen_ai.tool.definitions`` that a span keeps. Tool descriptions and schemas are prompt + content: with input capture off only each tool's type and name stay, and with a mask the + definitions go through it as input does. Like other content, a list longer than + ``max_attribute_length``, 0 included, keeps only the names, since a cut list is not JSON and + readers would lose every tool. The names follow the limit of raw attributes, where 0 sets no + limit; names that do not fit leave the attribute out.""" + if state.capture_input: + if client.mask is None: + try: + full = value if isinstance(value, str) else json_dumps(definitions) + except (TypeError, ValueError, RecursionError): + full = None + else: + full = serialize_content( + definitions, + key=ATTR_TOOL_DEFINITIONS, + mask=client.mask, + max_len=sys.maxsize, + on_error=client.on_error, + ) + if full is not None and utf16_length(full) <= client.max_attribute_length: + return full + names: list[dict[str, str]] = [] + for definition in definitions: + if not isinstance(definition, dict): + continue + fields = cast("dict[str, Any]", definition) + kept = {key: fields[key] for key in ("type", "name") if isinstance(fields.get(key), str)} + # OpenAI's Chat Completions form nests the name under ``function``. + function = fields.get("function") + if "name" not in kept and isinstance(function, dict): + nested = cast("dict[str, Any]", function).get("name") + if isinstance(nested, str): + kept["name"] = nested + if kept: + names.append(kept) + if not names: + return None + text = json_dumps(names) + raw_limit = client.max_attribute_length or sys.maxsize + return text if utf16_length(text) <= raw_limit else None + + def _apply_fields(client: Client, span: Span, state: _SpanState, fields: dict[str, Any]) -> None: name = fields.get("name") if name is not None: diff --git a/sdks/python/tests/test_masking.py b/sdks/python/tests/test_masking.py index 35d762f4..a86241e3 100644 --- a/sdks/python/tests/test_masking.py +++ b/sdks/python/tests/test_masking.py @@ -462,3 +462,83 @@ def on_error(error: BaseException) -> None: assert "exception.message" not in event_attrs assert "exception.stacktrace" not in event_attrs assert "PRIVATE_" not in str(event_attrs) + + +_TOOL_DEFINITIONS = json.dumps( + [ + { + "type": "function", + "name": "issue_refund", + "description": "Refund SECRET orders", + "parameters": {"type": "object", "properties": {"order": {"type": "string"}}}, + }, + {"type": "web_search_20250305", "name": "web_search", "max_uses": 3}, + {"type": "googleSearch"}, + {"description": "a tool without a name or type"}, + ], + separators=(",", ":"), +) + + +def test_tool_descriptions_and_schemas_are_kept_only_as_captured_input(make: MakeClient) -> None: + raw = {"gen_ai.tool.definitions": _TOOL_DEFINITIONS} + off = make(capture_input=False) + telemetry_dev.start_span("off", attributes=raw).end() + telemetry_dev.start_span("on", attributes=raw, capture_input=True).end() + telemetry_dev.start_span( + "not-a-list", attributes={"gen_ai.tool.definitions": '{"name":"SECRET"}'} + ).end() + # One JSON text per tool, and the tool objects themselves. + secret = {"type": "function", "name": "issue_refund", "description": "SECRET"} + telemetry_dev.start_span( + "texts", attributes={"gen_ai.tool.definitions": [json.dumps(secret)]} + ).end() + # Outside the declared types, but a caller without type checks can pass it. + objects = cast("Any", {"gen_ai.tool.definitions": [secret]}) + telemetry_dev.start_span("objects", attributes=objects).end() + nested = [{"type": "function", "function": {"name": "lookup", "description": "SECRET"}}] + telemetry_dev.start_span( + "nested", attributes={"gen_ai.tool.definitions": json.dumps(nested)} + ).end() + by_name = {span.name: attrs(span) for span in off.span_exporter.get_finished_spans()} + names = ( + '[{"type":"function","name":"issue_refund"},' + '{"type":"web_search_20250305","name":"web_search"},{"type":"googleSearch"}]' + ) + + assert by_name["off"]["gen_ai.tool.definitions"] == names + assert by_name["on"]["gen_ai.tool.definitions"] == _TOOL_DEFINITIONS + assert "gen_ai.tool.definitions" not in by_name["not-a-list"] + assert by_name["nested"]["gen_ai.tool.definitions"] == '[{"type":"function","name":"lookup"}]' + for name in ("texts", "objects"): + assert by_name[name]["gen_ai.tool.definitions"] == ( + '[{"type":"function","name":"issue_refund"}]' + ) + telemetry_dev.shutdown() + + # A list that the attribute limit would cut keeps its names, which still parse. + limited = make(max_attribute_length=len(names) + 1) + telemetry_dev.start_span("long", attributes=raw).end() + assert attrs(only_span(limited))["gen_ai.tool.definitions"] == names + telemetry_dev.shutdown() + + # A limit of 0 drops content, but not the names, which it does not limit. + zero = make(max_attribute_length=0) + telemetry_dev.start_span("zero", attributes=raw).end() + assert attrs(only_span(zero))["gen_ai.tool.definitions"] == names + telemetry_dev.shutdown() + + # Names that do not fit a limit above 0 leave the attribute out. + tiny = make(max_attribute_length=5) + telemetry_dev.start_span("tiny", attributes=raw).end() + assert "gen_ai.tool.definitions" not in attrs(only_span(tiny)) + telemetry_dev.shutdown() + + def mask(value: Any, _ctx: MaskContext) -> Any: + return json.loads(json.dumps(value).replace("SECRET", "[masked]")) + + masked = make(mask=mask) + telemetry_dev.start_span("masked", attributes=raw).end() + value = str(attrs(only_span(masked))["gen_ai.tool.definitions"]) + assert "Refund [masked] orders" in value + assert "SECRET" not in value