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,10 @@
import * as Sentry from '@sentry/node';
import { loggingTransport } from '@sentry-internal/node-integration-tests';

Sentry.init({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
release: '1.0',
tracesSampleRate: 1.0,
dataCollection: { genAI: { inputs: false, outputs: false } },
transport: loggingTransport,
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import * as Sentry from '@sentry/node';
import { streamObject } from 'ai';
import { convertArrayToReadableStream, MockLanguageModelV1 } from 'ai/test';
import { z } from 'zod';

async function run() {
await Sentry.startSpan({ op: 'function', name: 'main' }, async () => {
const result = streamObject({
experimental_telemetry: { isEnabled: true, recordInputs: true, recordOutputs: true },
model: new MockLanguageModelV1({
defaultObjectGenerationMode: 'json',
doStream: async () => ({
stream: convertArrayToReadableStream([
{ type: 'response-metadata', id: 'resp-1', modelId: 'mock-model-id' },
{ type: 'text-delta', textDelta: '{ "name": "John Doe",' },
{ type: 'text-delta', textDelta: ' "age": 30 }' },
{
type: 'finish',
finishReason: 'stop',
usage: { promptTokens: 15, completionTokens: 25 },
},
]),
rawCall: { rawPrompt: null, rawSettings: {} },
}),
}),
schema: z.object({
name: z.string(),
age: z.number(),
}),
prompt: 'Generate a person object',
});

// streamObject returns synchronously; drive the lazy stream to completion so the spans finish.
for await (const _part of result.partialObjectStream) {
void _part;
}
});

await Sentry.flush(2000);
}

run();
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
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 Down Expand Up @@ -697,6 +698,41 @@ describe('Vercel AI integration (v4)', () => {
});
});

createEsmAndCjsTests(__dirname, 'scenario-stream-object.mjs', 'instrument-streamed.mjs', (createRunner, test) => {
test('creates ai spans for streamObject (doStream)', async () => {
await createRunner()
.expect({
span: container => {
expect(container.items.find(span => span.is_segment && span.name === 'main')).toBeDefined();

const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === expectedOrigin);
expect(spans).toHaveLength(2);

const invokeAgentSpan = spans.find(span => span.attributes[SENTRY_OP]?.value === GEN_AI_INVOKE_AGENT)!;
expect(invokeAgentSpan.status).toBe('ok');
expect(invokeAgentSpan.attributes[SENTRY_OP].value).toBe(GEN_AI_INVOKE_AGENT);
expect(invokeAgentSpan.attributes[SENTRY_ORIGIN].value).toBe(expectedOrigin);
expect(invokeAgentSpan.attributes['vercel.ai.operationId'].value).toBe('ai.streamObject');
expect(invokeAgentSpan.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(15);
expect(invokeAgentSpan.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(25);
expect(invokeAgentSpan.attributes[GEN_AI_USAGE_TOTAL_TOKENS].value).toBe(40);

const generateContentSpan = spans.find(
span => span.attributes[SENTRY_OP]?.value === GEN_AI_GENERATE_CONTENT,
)!;
expect(generateContentSpan.status).toBe('ok');
expect(generateContentSpan.parent_span_id).toBe(invokeAgentSpan.span_id);
expect(generateContentSpan.attributes['vercel.ai.operationId'].value).toBe('ai.streamObject.doStream');
expect(generateContentSpan.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(15);
expect(generateContentSpan.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(25);
},
})
.unordered()
.start()
.completed();
});
});

createEsmAndCjsTests(__dirname, 'scenario-generate-object.mjs', 'instrument-with-pii.mjs', (createRunner, test) => {
test('captures generateObject spans with schema attributes', async () => {
await createRunner()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import * as Sentry from '@sentry/node';
import { streamObject } from 'ai';
import { MockLanguageModelV3, simulateReadableStream } from 'ai/test';
import { z } from 'zod';

async function run() {
await Sentry.startSpan({ op: 'function', name: 'main' }, async () => {
const result = streamObject({
experimental_telemetry: { isEnabled: true, recordInputs: true, recordOutputs: true },
model: new MockLanguageModelV3({
doStream: async () => ({
stream: simulateReadableStream({
chunks: [
{ type: 'stream-start', warnings: [] },
{ type: 'text-start', id: '0' },
{ type: 'text-delta', id: '0', delta: '{ "name": "John Doe",' },
{ type: 'text-delta', id: '0', delta: ' "age": "thirty" }' },
{ type: 'text-end', id: '0' },
{
type: 'finish',
finishReason: { unified: 'stop', raw: 'stop' },
usage: {
inputTokens: { total: 15, noCache: 15, cached: 0 },
outputTokens: { total: 25, noCache: 25, cached: 0 },
totalTokens: { total: 40, noCache: 40, cached: 0 },
},
},
],
}),
}),
}),
schema: z.object({
name: z.string(),
age: z.number(),
}),
prompt: 'Generate a person object',
});

// streamObject returns synchronously; drive the lazy stream to completion so
// the spans actually finish.
for await (const _part of result.partialObjectStream) {
void _part;
}

try {
await result.object;
} catch {
// Expected: `age` fails schema validation after the model call succeeded.
}
});
}

run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import * as Sentry from '@sentry/node';
import { streamObject } from 'ai';
import { MockLanguageModelV3, simulateReadableStream } from 'ai/test';
import { z } from 'zod';

async function run() {
await Sentry.startSpan({ op: 'function', name: 'main' }, async () => {
const result = streamObject({
experimental_telemetry: { isEnabled: true, recordInputs: true, recordOutputs: true },
model: new MockLanguageModelV3({
doStream: async () => ({
stream: simulateReadableStream({
chunks: [
{ type: 'stream-start', warnings: [] },
{ type: 'text-start', id: '0' },
{ type: 'text-delta', id: '0', delta: '{ "name": "John Doe",' },
{ type: 'text-delta', id: '0', delta: ' "age": 30 }' },
{ type: 'text-end', id: '0' },
{
type: 'finish',
finishReason: { unified: 'stop', raw: 'stop' },
usage: {
inputTokens: { total: 15, noCache: 15, cached: 0 },
outputTokens: { total: 25, noCache: 25, cached: 0 },
totalTokens: { total: 40, noCache: 40, cached: 0 },
},
},
],
}),
}),
}),
schema: z.object({
name: z.string(),
age: z.number(),
}),
prompt: 'Generate a person object',
});

// streamObject returns synchronously; drive the lazy stream to completion so
// the spans actually finish.
for await (const _part of result.partialObjectStream) {
void _part;
}
});
}

run();
Original file line number Diff line number Diff line change
Expand Up @@ -850,6 +850,52 @@ describe.each(matrix)('Vercel AI integration (version %s)', (version, vercelAiVe
},
);

createEsmTests(
__dirname,
'scenario-stream-object.mjs',
'instrument.mjs',
(createRunner, test) => {
// v7's native `ai:telemetry` channel does not publish `streamObject`, same as `generateObject`.
test.skipIf(version === '7')(
'creates streamObject spans with the model call parented to invoke_agent',
async () => {
await createRunner()
.expect({
span: container => {
const segment = container.items.find(span => span.is_segment && span.name === 'main');
expect(segment).toBeDefined();
const spans = container.items.filter(
span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.vercelai',
);
const invokeAgent = spans.find(span => span.attributes[SENTRY_OP]?.value === GEN_AI_INVOKE_AGENT)!;
expect(invokeAgent.attributes['vercel.ai.operationId']?.value).toBe('ai.streamObject');
expect(invokeAgent.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value).toBe(15);
expect(invokeAgent.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]?.value).toBe(25);
expect(invokeAgent.attributes[GEN_AI_USAGE_TOTAL_TOKENS]?.value).toBe(40);

const generateContent = spans.find(
span => span.attributes[SENTRY_OP]?.value === GEN_AI_GENERATE_CONTENT,
)!;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
expect(generateContent.parent_span_id).toBe(invokeAgent.span_id);
expect(generateContent.attributes['vercel.ai.operationId']?.value).toBe('ai.streamObject.doStream');
expect(generateContent.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value).toBe(15);
expect(generateContent.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]?.value).toBe(25);
expect(generateContent.attributes[GEN_AI_USAGE_TOTAL_TOKENS]?.value).toBe(40);
},
})
.unordered()
.start()
.completed();
},
);
},
{
additionalDependencies: {
ai: vercelAiVersion,
},
},
);

createEsmTests(
__dirname,
'scenario-stream-tools.mjs',
Expand Down Expand Up @@ -958,6 +1004,39 @@ describe.each(matrix)('Vercel AI integration (version %s)', (version, vercelAiVe
},
);

createEsmTests(
__dirname,
'scenario-stream-object-invalid.mjs',
'instrument.mjs',
(createRunner, test) => {
// v7's native `ai:telemetry` channel does not publish `streamObject`, same as `generateObject`.
test.skipIf(version === '7')('keeps streamObject usage when the object fails schema validation', async () => {
await createRunner()
.expect({
span: container => {
const spans = container.items.filter(
span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.vercelai',
);
const invokeAgent = spans.find(span => span.attributes[SENTRY_OP]?.value === GEN_AI_INVOKE_AGENT)!;
expect(invokeAgent.attributes['vercel.ai.operationId']?.value).toBe('ai.streamObject');
expect(invokeAgent.status).toBe('error');
expect(invokeAgent.attributes[GEN_AI_USAGE_INPUT_TOKENS]?.value).toBe(15);
expect(invokeAgent.attributes[GEN_AI_USAGE_OUTPUT_TOKENS]?.value).toBe(25);
expect(invokeAgent.attributes[GEN_AI_USAGE_TOTAL_TOKENS]?.value).toBe(40);
},
})
.unordered()
.start()
.completed();
});
},
{
additionalDependencies: {
ai: vercelAiVersion,
},
},
);

createEsmTests(
__dirname,
'scenario-rejected-model.mjs',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ const runtimeContextAttributesByCallId = new Map<string, SpanAttributes>();
const ROOT_OPERATION_TYPES = new Set<ChannelEventType>([
'generateText',
'streamText',
'streamObject',
'generateObject',
'embed',
'embedMany',
Expand All @@ -141,9 +142,10 @@ export function clearOperationId(data: VercelAiChannelMessage): void {

/**
* Drop the per-operation `callId` maps for a single id. The v6 orchestrion adapter uses this to clear a
* `streamText` operation only after its lazily-run model call settles — the operation's own span ends
* synchronously (when `streamText` returns) but the model call runs later as the stream is consumed, and
* it still needs the operation's `operationId`/`isStream` entry to name itself `ai.streamText.doStream`.
* `streamText`/`streamObject` operation only after its lazily-run model call settles — the operation's own
* span ends synchronously (when the call returns) but the model call runs later as the stream is consumed,
* and it still needs the operation's `operationId`/`isStream` entry to name itself `ai.streamText.doStream`
* (or `ai.streamObject.doStream`).
*/
export function clearOperationCallId(callId: string): void {
operationIdByCallId.delete(callId);
Expand Down Expand Up @@ -244,6 +246,7 @@ function resolveToolDescription(callId: string | undefined, toolName: string, to
export type ChannelEventType =
| 'generateText'
| 'streamText'
| 'streamObject'
| 'generateObject'
| 'step'
| 'languageModelCall'
Expand Down Expand Up @@ -482,10 +485,16 @@ export function createSpanFromMessage(
case 'generateText':
case 'streamText':
case 'generateObject':
// `generateObject` builds the same `invoke_agent` span as `generateText` (non-streaming); its
// distinct `ai.generateObject` operationId rides on `event.operationId`. The JSON-schema attribute
// the OTel path derives from the SDK's Zod schema is not reconstructed on the channel path.
return buildInvokeAgentSpan(event, baseAttributes, recordInputs, callId, type === 'streamText');
case 'streamObject':
// The object variants' operationId rides on `event.operationId`. The JSON-schema attribute the OTel
// path derives from the SDK's Zod schema is not reconstructed on the channel path.
return buildInvokeAgentSpan(
event,
baseAttributes,
recordInputs,
callId,
type === 'streamText' || type === 'streamObject',
);
case 'languageModelCall':
_INTERNAL_skipAiProviderWrapping([WORKERS_AI_INTEGRATION_NAME]);

Expand Down
Loading
Loading