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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
17 changes: 13 additions & 4 deletions docs/sdk-conformance.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 6 additions & 3 deletions packages/ai/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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
Expand Down
69 changes: 69 additions & 0 deletions packages/ai/src/integration_v6.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import {
SEVERITY_WARN,
type TelemetryDevEvent,
type JsonValue,
type ToolDefinition,
toolDefinitionsAttr,
unknownErrorMessage,
} from "./shared.ts";

Expand Down Expand Up @@ -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<string, V6Tool | undefined>;
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 {
Expand Down Expand Up @@ -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),
Expand Down
55 changes: 55 additions & 0 deletions packages/ai/src/integration_v7.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import {
SEVERITY_WARN,
type TelemetryDevEvent,
type JsonValue,
type ToolDefinition,
toolDefinitionsAttr,
} from "./shared.ts";

type TelemetryDevHook = (event: TelemetryDevEvent) => void | PromiseLike<void>;
Expand All @@ -42,6 +44,7 @@ type TelemetryDevHook = (event: TelemetryDevEvent) => void | PromiseLike<void>;
export interface TelemetryDevIntegration {
onStart?: TelemetryDevHook;
onStepStart?: TelemetryDevHook;
onLanguageModelCallStart?: TelemetryDevHook;
onLanguageModelCallEnd?: TelemetryDevHook;
onStepEnd?: TelemetryDevHook;
onToolExecutionStart?: TelemetryDevHook;
Expand Down Expand Up @@ -155,6 +158,13 @@ interface V7StepStartEvent {
runtimeContext?: Record<string, JsonValue>;
}

// 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<Record<string, JsonValue>>;
}

interface V7Performance {
stepTimeMs?: number;
responseTimeMs?: number;
Expand Down Expand Up @@ -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<Record<string, JsonValue>> | 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":
Expand Down Expand Up @@ -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);
Expand Down
28 changes: 28 additions & 0 deletions packages/ai/src/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ResolvedConfig, "mask" | "onError">,
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
Expand Down
22 changes: 21 additions & 1 deletion packages/ai/tests/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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: {
Expand Down Expand Up @@ -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([
Expand Down
51 changes: 51 additions & 0 deletions packages/ai/tests/integration_v7.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
2 changes: 1 addition & 1 deletion packages/anthropic/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading