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
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import * as Sentry from '@sentry/node';
import { generateText, simulateReadableStream, stepCountIs, streamText, tool } from 'ai';
import { MockLanguageModelV2 } from 'ai/test';
import { z } from 'zod';

// `@ai-sdk/google` 2.x reports candidate-only `outputTokens` and a separate `reasoningTokens`, with the
// raw counts in `providerMetadata`. Two steps reason 80 and 100 tokens.
const STEPS = [
{ candidates: 20, thoughts: 80, finishReason: 'tool-calls' },
{ candidates: 20, thoughts: 100, finishReason: 'stop' },
];

function usage({ candidates, thoughts }) {
return {
inputTokens: 10,
outputTokens: candidates,
totalTokens: 10 + candidates + thoughts,
reasoningTokens: thoughts,
};
}

function providerMetadata({ candidates, thoughts }) {
return {
google: {
usageMetadata: {
promptTokenCount: 10,
candidatesTokenCount: candidates,
thoughtsTokenCount: thoughts,
totalTokenCount: 10 + candidates + thoughts,
},
},
};
}

const tools = {
getWeather: tool({
description: 'Get the current weather for a location',
inputSchema: z.object({ location: z.string() }),
execute: async ({ location }) => `Weather in ${location}: Sunny, 72°F`,
}),
};

const toolCall = {
type: 'tool-call',
toolCallId: 'call-1',
toolName: 'getWeather',
input: JSON.stringify({ location: 'San Francisco' }),
};

async function run() {
await Sentry.startSpan({ op: 'function', name: 'main' }, async () => {
let generateCalls = 0;
await generateText({
model: new MockLanguageModelV2({
doGenerate: async () => {
const step = STEPS[generateCalls++];
return {
finishReason: step.finishReason,
usage: usage(step),
content: generateCalls === 1 ? [toolCall] : [{ type: 'text', text: 'Sunny, 72°F.' }],
warnings: [],
providerMetadata: providerMetadata(step),
};
},
}),
tools,
stopWhen: stepCountIs(5),
prompt: 'What is the weather in San Francisco?',
});

let streamCalls = 0;
const result = streamText({
model: new MockLanguageModelV2({
doStream: async () => {
const step = STEPS[streamCalls++];
const content =
streamCalls === 1
? [toolCall]
: [
{ type: 'text-start', id: '0' },
{ type: 'text-delta', id: '0', delta: 'Sunny, 72°F.' },
{ type: 'text-end', id: '0' },
];
return {
stream: simulateReadableStream({
chunks: [
{ type: 'stream-start', warnings: [] },
...content,
{
type: 'finish',
finishReason: step.finishReason,
usage: usage(step),
providerMetadata: providerMetadata(step),
},
],
}),
};
},
}),
tools,
stopWhen: stepCountIs(5),
prompt: 'What is the weather in San Francisco?',
});
for await (const _part of result.fullStream) {
void _part;
}

// `@ai-sdk/openai` 2.x reports reasoning only in the usage, inside an output that includes it.
await generateText({
model: new MockLanguageModelV2({
doGenerate: async () => ({
finishReason: 'stop',
usage: { inputTokens: 10, outputTokens: 50, totalTokens: 60, reasoningTokens: 30 },
content: [{ type: 'text', text: 'Sunny.' }],
warnings: [],
providerMetadata: { openai: {} },
}),
}),
prompt: 'What is the weather in San Francisco?',
});
});
}

run();
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@ import {
GEN_AI_TOOL_NAME,
GEN_AI_USAGE_INPUT_TOKENS,
GEN_AI_USAGE_OUTPUT_TOKENS,
GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,
GEN_AI_USAGE_TOTAL_TOKENS,
SENTRY_OP,
SENTRY_ORIGIN,
} from '@sentry/conventions/attributes';
import { GEN_AI_GENERATE_CONTENT, GEN_AI_INVOKE_AGENT } from '@sentry/conventions/op';
import { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../../../../../../packages/server-utils/src/ai/core/gen-ai-attributes';
import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../../utils/runner';
import { getStringAttributeValue } from '../../../../utils';
Expand All @@ -27,6 +29,57 @@ describe('Vercel AI integration (v5)', () => {
cleanupChildProcesses();
});

createEsmAndCjsTests(
__dirname,
'scenario-reasoning-tokens.mjs',
'instrument.mjs',
(createRunner, test) => {
test('records reasoning tokens on model calls and sums them onto invoke_agent spans', async () => {
await createRunner()
.unordered()
.expect({
span: container => {
const spans = container.items.filter(
span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.vercelai',
);
const byOp = (op: string) => spans.filter(span => span.attributes[SENTRY_OP]?.value === op);
const tokens = (span: (typeof spans)[number]) => [
span.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]?.value,
span.attributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]?.value,
];

const sorted = (op: string) =>
byOp(op)
.map(tokens)
.sort((a, b) => Number(a[0]) - Number(b[0]));

// Each Google step's output gains its reasoning, which `@ai-sdk/google` 2.x reports separately.
expect(sorted(GEN_AI_GENERATE_CONTENT)).toEqual([
[50, 30],
[100, 80],
[100, 80],
[120, 100],
[120, 100],
]);
// One generateText and one streamText operation over the same two Google steps, then one OpenAI call.
expect(sorted(GEN_AI_INVOKE_AGENT)).toEqual([
[50, 30],
[220, 180],
[220, 180],
]);
},
})
.start()
.completed();
});
},
{
additionalDependencies: {
ai: '5.0.30',
},
},
);

createEsmAndCjsTests(
__dirname,
'scenario.mjs',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import * as Sentry from '@sentry/node';
import { generateText, stepCountIs, streamText, tool } from 'ai';
import { MockLanguageModelV3, simulateReadableStream } from 'ai/test';
import { z } from 'zod';

// Two Gemini steps that reason 80 and 100 tokens. `providerMetadata` describes one step, so only the
// SDK's usage can give the operation its 180.
const STEPS = [
{ candidates: 20, thoughts: 80, finishReason: { unified: 'tool-calls', raw: 'tool_calls' } },
{ candidates: 20, thoughts: 100, finishReason: { unified: 'stop', raw: 'STOP' } },
];

function usage({ candidates, thoughts }) {
return {
inputTokens: { total: 10, noCache: 10, cacheRead: 0, cacheWrite: undefined },
outputTokens: { total: candidates + thoughts, text: candidates, reasoning: thoughts },
};
}

function providerMetadata({ candidates, thoughts }) {
return {
google: {
usageMetadata: {
promptTokenCount: 10,
candidatesTokenCount: candidates,
thoughtsTokenCount: thoughts,
totalTokenCount: 10 + candidates + thoughts,
},
},
};
}

const tools = {
getWeather: tool({
description: 'Get the current weather for a location',
inputSchema: z.object({ location: z.string() }),
execute: async ({ location }) => `Weather in ${location}: Sunny, 72°F`,
}),
};

const toolCall = {
type: 'tool-call',
toolCallId: 'call-1',
toolName: 'getWeather',
input: JSON.stringify({ location: 'San Francisco' }),
};

async function run() {
await Sentry.startSpan({ op: 'function', name: 'main' }, async () => {
let generateCalls = 0;
await generateText({
experimental_telemetry: { isEnabled: true },
model: new MockLanguageModelV3({
doGenerate: async () => {
const step = STEPS[generateCalls++];
return {
finishReason: step.finishReason,
usage: usage(step),
content: generateCalls === 1 ? [toolCall] : [{ type: 'text', text: 'Sunny, 72°F.' }],
warnings: [],
providerMetadata: providerMetadata(step),
};
},
}),
tools,
stopWhen: stepCountIs(5),
prompt: 'What is the weather in San Francisco?',
});

let streamCalls = 0;
const result = streamText({
experimental_telemetry: { isEnabled: true },
model: new MockLanguageModelV3({
doStream: async () => {
const step = STEPS[streamCalls++];
const content =
streamCalls === 1
? [toolCall]
: [
{ type: 'text-start', id: '0' },
{ type: 'text-delta', id: '0', delta: 'Sunny, 72°F.' },
{ type: 'text-end', id: '0' },
];
return {
stream: simulateReadableStream({
chunks: [
{ type: 'stream-start', warnings: [] },
...content,
{
type: 'finish',
finishReason: step.finishReason,
usage: usage(step),
providerMetadata: providerMetadata(step),
},
],
}),
};
},
}),
tools,
stopWhen: stepCountIs(5),
prompt: 'What is the weather in San Francisco?',
});
for await (const _part of result.fullStream) {
void _part;
}
});
}

run();
Original file line number Diff line number Diff line change
Expand Up @@ -938,6 +938,46 @@ export function registerVercelAiGenerationTests(version: '6' | '7', vercelAiVers
},
},
);
createEsmTests(
__dirname,
'scenario-reasoning-tokens.mjs',
'instrument.mjs',
(createRunner, test) => {
test('sums reasoning tokens across steps onto invoke_agent spans', async () => {
await createRunner()
.unordered()
.expect({
span: container => {
const spans = container.items.filter(
span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.vercelai',
);
const generateContent = spans.filter(
span => span.attributes[SENTRY_OP]?.value === GEN_AI_GENERATE_CONTENT,
);
const stepReasoning = generateContent.map(
span => span.attributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]?.value as number,
);
expect(stepReasoning.sort((a, b) => a - b)).toEqual([80, 80, 100, 100]);

// One generateText and one streamText operation, each over the same two steps.
const invokeAgents = spans.filter(span => span.attributes[SENTRY_OP]?.value === GEN_AI_INVOKE_AGENT);
expect(invokeAgents).toHaveLength(2);
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
for (const invokeAgent of invokeAgents) {
expect(invokeAgent.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]?.value).toBe(220);
expect(invokeAgent.attributes[GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]?.value).toBe(180);
}
},
})
.start()
.completed();
});
},
{
additionalDependencies: {
ai: vercelAiVersion,
},
},
);
createEsmTests(
__dirname,
'scenario-embeddings.mjs',
Expand Down
12 changes: 0 additions & 12 deletions packages/server-utils/src/ai/vercel-ai/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,18 +92,6 @@ export function getProviderMetadataAttributes(providerMetadata: unknown): Record
return attributes;
}

/**
* Usage attributes derived from `providerMetadata`, which describes only the last step of a call.
* They must not be written onto a span that reports usage aggregated across steps
* (`gen_ai.invoke_agent`), where they would replace the aggregate with one step's figures.
*/
export const LAST_STEP_ONLY_USAGE_KEYS = new Set<string>([
GEN_AI_USAGE_OUTPUT_TOKENS,
GEN_AI_USAGE_TOTAL_TOKENS,
GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,
]);

/**
* Sets an attribute only if the value is not null or undefined.
*/
Expand Down
Loading
Loading