Skip to content

Commit ec1380c

Browse files
cursoragentmydea
authored andcommitted
Add Vercel AI integration with telemetry for Next.js 15 test app
1 parent 33d04d5 commit ec1380c

File tree

6 files changed

+237
-3
lines changed

6 files changed

+237
-3
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Vercel AI Integration - Next.js 15 E2E Test Implementation
2+
3+
## Overview
4+
This document summarizes the implementation of the Vercel AI integration for the Next.js 15 E2E test application.
5+
6+
## Changes Made
7+
8+
### 1. Updated Dependencies (package.json)
9+
Added the following dependencies:
10+
- `ai`: ^3.0.0 - Vercel AI SDK
11+
- `zod`: ^3.22.4 - For tool parameter schemas
12+
13+
### 2. Server Configuration (sentry.server.config.ts)
14+
Added the Vercel AI integration to the Sentry initialization:
15+
```typescript
16+
integrations: [
17+
Sentry.vercelAIIntegration(),
18+
],
19+
```
20+
21+
### 3. Test Page (app/ai-test/page.tsx)
22+
Created a new test page that demonstrates various AI SDK features:
23+
- Basic text generation with automatic telemetry
24+
- Explicit telemetry configuration
25+
- Tool calls and execution
26+
- Disabled telemetry
27+
28+
The page wraps AI operations in a Sentry span for proper tracing.
29+
30+
### 4. Test Suite (tests/ai-test.test.ts)
31+
Created a Playwright test that verifies:
32+
- AI spans are created with correct operations (`ai.pipeline.generate_text`, `gen_ai.generate_text`, `gen_ai.execute_tool`)
33+
- Span attributes match expected values (model info, tokens, prompts, etc.)
34+
- Input/output recording respects `sendDefaultPii: true` setting
35+
- Tool calls are properly traced
36+
- Disabled telemetry prevents span creation
37+
38+
## Expected Behavior
39+
40+
When `sendDefaultPii: true` (as configured in this test app):
41+
1. AI operations automatically enable telemetry
42+
2. Input prompts and output responses are recorded in spans
43+
3. Tool calls include arguments and results
44+
4. Token usage is tracked
45+
46+
## Running the Tests
47+
48+
Prerequisites:
49+
1. Build packages: `yarn build:tarball` (from repository root)
50+
2. Start the test registry (Verdaccio)
51+
3. Run the test: `yarn test:e2e nextjs-15` or `yarn test:run nextjs-15`
52+
53+
## Instrumentation Notes
54+
55+
The Vercel AI integration uses OpenTelemetry instrumentation to automatically patch the `ai` module methods. The instrumentation:
56+
- Enables telemetry by default for all AI operations
57+
- Respects the `sendDefaultPii` client option for recording inputs/outputs
58+
- Allows per-call telemetry configuration via `experimental_telemetry`
59+
- Follows a precedence hierarchy: integration options > method options > defaults
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
import { generateText } from 'ai';
2+
import { MockLanguageModelV1 } from 'ai/test';
3+
import { z } from 'zod';
4+
import * as Sentry from '@sentry/nextjs';
5+
6+
export const dynamic = 'force-dynamic';
7+
8+
async function runAITest() {
9+
// First span - telemetry should be enabled automatically but no input/output recorded when sendDefaultPii: true
10+
const result1 = await generateText({
11+
model: new MockLanguageModelV1({
12+
doGenerate: async () => ({
13+
rawCall: { rawPrompt: null, rawSettings: {} },
14+
finishReason: 'stop',
15+
usage: { promptTokens: 10, completionTokens: 20 },
16+
text: 'First span here!',
17+
}),
18+
}),
19+
prompt: 'Where is the first span?',
20+
});
21+
22+
// Second span - explicitly enabled telemetry, should record inputs/outputs
23+
const result2 = await generateText({
24+
experimental_telemetry: { isEnabled: true },
25+
model: new MockLanguageModelV1({
26+
doGenerate: async () => ({
27+
rawCall: { rawPrompt: null, rawSettings: {} },
28+
finishReason: 'stop',
29+
usage: { promptTokens: 10, completionTokens: 20 },
30+
text: 'Second span here!',
31+
}),
32+
}),
33+
prompt: 'Where is the second span?',
34+
});
35+
36+
// Third span - with tool calls and tool results
37+
const result3 = await generateText({
38+
model: new MockLanguageModelV1({
39+
doGenerate: async () => ({
40+
rawCall: { rawPrompt: null, rawSettings: {} },
41+
finishReason: 'tool-calls',
42+
usage: { promptTokens: 15, completionTokens: 25 },
43+
text: 'Tool call completed!',
44+
toolCalls: [
45+
{
46+
toolCallType: 'function',
47+
toolCallId: 'call-1',
48+
toolName: 'getWeather',
49+
args: '{ "location": "San Francisco" }',
50+
},
51+
],
52+
}),
53+
}),
54+
tools: {
55+
getWeather: {
56+
parameters: z.object({ location: z.string() }),
57+
execute: async (args) => {
58+
return `Weather in ${args.location}: Sunny, 72°F`;
59+
},
60+
},
61+
},
62+
prompt: 'What is the weather in San Francisco?',
63+
});
64+
65+
// Fourth span - explicitly disabled telemetry, should not be captured
66+
const result4 = await generateText({
67+
experimental_telemetry: { isEnabled: false },
68+
model: new MockLanguageModelV1({
69+
doGenerate: async () => ({
70+
rawCall: { rawPrompt: null, rawSettings: {} },
71+
finishReason: 'stop',
72+
usage: { promptTokens: 10, completionTokens: 20 },
73+
text: 'Third span here!',
74+
}),
75+
}),
76+
prompt: 'Where is the third span?',
77+
});
78+
79+
return {
80+
result1: result1.text,
81+
result2: result2.text,
82+
result3: result3.text,
83+
result4: result4.text,
84+
};
85+
}
86+
87+
export default async function Page() {
88+
const results = await Sentry.startSpan(
89+
{ op: 'function', name: 'ai-test' },
90+
async () => {
91+
return await runAITest();
92+
}
93+
);
94+
95+
return (
96+
<div>
97+
<h1>AI Test Results</h1>
98+
<pre id="ai-results">{JSON.stringify(results, null, 2)}</pre>
99+
</div>
100+
);
101+
}

dev-packages/e2e-tests/test-applications/nextjs-15/package.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,12 @@
1818
"@types/node": "^18.19.1",
1919
"@types/react": "18.0.26",
2020
"@types/react-dom": "18.0.9",
21+
"ai": "^3.0.0",
2122
"next": "15.3.0-canary.33",
2223
"react": "beta",
2324
"react-dom": "beta",
24-
"typescript": "~5.0.0"
25+
"typescript": "~5.0.0",
26+
"zod": "^3.22.4"
2527
},
2628
"devDependencies": {
2729
"@playwright/test": "~1.50.0",

dev-packages/e2e-tests/test-applications/nextjs-15/sentry.server.config.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,7 @@ Sentry.init({
1010
// We are doing a lot of events at once in this test
1111
bufferSize: 1000,
1212
},
13+
integrations: [
14+
Sentry.vercelAIIntegration(),
15+
],
1316
});
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import { expect, test } from '@playwright/test';
2+
import { waitForTransaction } from '@sentry-internal/test-utils';
3+
4+
test('should create AI spans with correct attributes', async ({ page }) => {
5+
const aiTransactionPromise = waitForTransaction('nextjs-15', async transactionEvent => {
6+
return transactionEvent?.transaction === 'ai-test';
7+
});
8+
9+
await page.goto('/ai-test');
10+
11+
const aiTransaction = await aiTransactionPromise;
12+
13+
expect(aiTransaction).toBeDefined();
14+
expect(aiTransaction.contexts?.trace?.op).toBe('function');
15+
expect(aiTransaction.transaction).toBe('ai-test');
16+
17+
const spans = aiTransaction.spans || [];
18+
19+
// We expect spans for the first 3 AI calls (4th is disabled)
20+
// Each generateText call should create 2 spans: one for the pipeline and one for doGenerate
21+
// Plus a span for the tool call
22+
const aiPipelineSpans = spans.filter(span => span.op === 'ai.pipeline.generate_text');
23+
const aiGenerateSpans = spans.filter(span => span.op === 'gen_ai.generate_text');
24+
const toolCallSpans = spans.filter(span => span.op === 'gen_ai.execute_tool');
25+
26+
expect(aiPipelineSpans.length).toBeGreaterThanOrEqual(3);
27+
expect(aiGenerateSpans.length).toBeGreaterThanOrEqual(3);
28+
expect(toolCallSpans.length).toBeGreaterThanOrEqual(1);
29+
30+
// First AI call - should have telemetry enabled and record inputs/outputs (sendDefaultPii: true)
31+
const firstPipelineSpan = aiPipelineSpans[0];
32+
expect(firstPipelineSpan?.data?.['ai.model.id']).toBe('mock-model-id');
33+
expect(firstPipelineSpan?.data?.['ai.model.provider']).toBe('mock-provider');
34+
expect(firstPipelineSpan?.data?.['ai.prompt']).toContain('Where is the first span?');
35+
expect(firstPipelineSpan?.data?.['ai.response.text']).toBe('First span here!');
36+
expect(firstPipelineSpan?.data?.['gen_ai.usage.input_tokens']).toBe(10);
37+
expect(firstPipelineSpan?.data?.['gen_ai.usage.output_tokens']).toBe(20);
38+
39+
// Second AI call - explicitly enabled telemetry
40+
const secondPipelineSpan = aiPipelineSpans[1];
41+
expect(secondPipelineSpan?.data?.['ai.prompt']).toContain('Where is the second span?');
42+
expect(secondPipelineSpan?.data?.['ai.response.text']).toContain('Second span here!');
43+
44+
// Third AI call - with tool calls
45+
const thirdPipelineSpan = aiPipelineSpans[2];
46+
expect(thirdPipelineSpan?.data?.['ai.response.finishReason']).toBe('tool-calls');
47+
expect(thirdPipelineSpan?.data?.['gen_ai.usage.input_tokens']).toBe(15);
48+
expect(thirdPipelineSpan?.data?.['gen_ai.usage.output_tokens']).toBe(25);
49+
50+
// Tool call span
51+
const toolSpan = toolCallSpans[0];
52+
expect(toolSpan?.data?.['ai.toolCall.name']).toBe('getWeather');
53+
expect(toolSpan?.data?.['ai.toolCall.id']).toBe('call-1');
54+
expect(toolSpan?.data?.['ai.toolCall.args']).toContain('San Francisco');
55+
expect(toolSpan?.data?.['ai.toolCall.result']).toContain('Sunny, 72°F');
56+
57+
// Verify the fourth call was not captured (telemetry disabled)
58+
const promptsInSpans = spans
59+
.map(span => span.data?.['ai.prompt'])
60+
.filter(Boolean);
61+
const hasDisabledPrompt = promptsInSpans.some(prompt => prompt.includes('Where is the third span?'));
62+
expect(hasDisabledPrompt).toBe(false);
63+
64+
// Verify results are displayed on the page
65+
const resultsText = await page.locator('#ai-results').textContent();
66+
expect(resultsText).toContain('First span here!');
67+
expect(resultsText).toContain('Second span here!');
68+
expect(resultsText).toContain('Tool call completed!');
69+
expect(resultsText).toContain('Third span here!');
70+
});

packages/node/src/integrations/tracing/vercelai/instrumentation.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ export class SentryVercelAiInstrumentation extends InstrumentationBase {
109109
this._callbacks = [];
110110

111111
function generatePatch(originalMethod: (...args: MethodArgs) => unknown) {
112-
return (...args: MethodArgs) => {
112+
return function (this: unknown, ...args: MethodArgs) {
113113
const existingExperimentalTelemetry = args[0].experimental_telemetry || {};
114114
const isEnabled = existingExperimentalTelemetry.isEnabled;
115115

@@ -132,7 +132,6 @@ export class SentryVercelAiInstrumentation extends InstrumentationBase {
132132
recordOutputs,
133133
};
134134

135-
// @ts-expect-error we know that the method exists
136135
return originalMethod.apply(this, args);
137136
};
138137
}

0 commit comments

Comments
 (0)