Repository navigation
fix(server-utils): Record Vercel AI experimental_telemetry.metadata on gen_ai spans
#24721
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
isaacs
merged 2 commits into
develop
from
isaacschlueter/js-3800-vercelaiintegration-experimental_telemetrymetadata-no-longer
Oct 5, 2026
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
82 changes: 82 additions & 0 deletions
82
...tegration-tests/suites/tracing/vercelai/span-streaming-v6/scenario-telemetry-metadata.mjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| import * as Sentry from '@sentry/node'; | ||
| import { embed, embedMany, generateText, streamText } from 'ai'; | ||
| import { MockEmbeddingModelV3, MockLanguageModelV3, simulateReadableStream } from 'ai/test'; | ||
|
|
||
| const usage = { | ||
| inputTokens: { total: 10, noCache: 10, cached: 0 }, | ||
| outputTokens: { total: 20, noCache: 20, cached: 0 }, | ||
| totalTokens: { total: 30, noCache: 30, cached: 0 }, | ||
| }; | ||
|
|
||
| async function run() { | ||
| await Sentry.startSpan({ op: 'function', name: 'main' }, async () => { | ||
| await generateText({ | ||
| experimental_telemetry: { | ||
| isEnabled: true, | ||
| functionId: 'support-chat', | ||
| metadata: { requestId: 'req_generate', tenantId: 'acme', attempt: 2 }, | ||
| }, | ||
| model: new MockLanguageModelV3({ | ||
| doGenerate: async () => ({ | ||
| finishReason: { unified: 'stop', raw: 'stop' }, | ||
| usage, | ||
| content: [{ type: 'text', text: 'Hello!' }], | ||
| warnings: [], | ||
| }), | ||
| }), | ||
| prompt: 'Hi', | ||
| }); | ||
|
|
||
| const result = streamText({ | ||
| experimental_telemetry: { | ||
| isEnabled: true, | ||
| functionId: 'support-stream', | ||
| metadata: { requestId: 'req_stream', tenantId: 'acme' }, | ||
| }, | ||
| model: new MockLanguageModelV3({ | ||
| doStream: async () => ({ | ||
| stream: simulateReadableStream({ | ||
| chunks: [ | ||
| { type: 'stream-start', warnings: [] }, | ||
| { type: 'text-start', id: '0' }, | ||
| { type: 'text-delta', id: '0', delta: 'Hello!' }, | ||
| { type: 'text-end', id: '0' }, | ||
| { type: 'finish', finishReason: { unified: 'stop', raw: 'stop' }, usage }, | ||
| ], | ||
| }), | ||
| }), | ||
| }), | ||
| prompt: 'Hi', | ||
| }); | ||
| for await (const _part of result.fullStream) { | ||
| void _part; | ||
| } | ||
|
|
||
| await embed({ | ||
| experimental_telemetry: { isEnabled: true, metadata: { requestId: 'req_embed', tenantId: 'acme' } }, | ||
| model: new MockEmbeddingModelV3({ | ||
| doEmbed: async () => ({ embeddings: [[0.1, 0.2, 0.3]], usage: { tokens: 10 } }), | ||
| }), | ||
| value: 'Embed me', | ||
| }); | ||
|
|
||
| await embedMany({ | ||
| experimental_telemetry: { isEnabled: true, metadata: { requestId: 'req_embed_many', tenantId: 'acme' } }, | ||
| model: new MockEmbeddingModelV3({ | ||
| maxEmbeddingsPerCall: 5, | ||
| doEmbed: async () => ({ | ||
| embeddings: [ | ||
| [0.1, 0.2, 0.3], | ||
| [0.4, 0.5, 0.6], | ||
| ], | ||
| usage: { tokens: 20 }, | ||
| }), | ||
| }), | ||
| values: ['First', 'Second'], | ||
| }); | ||
| }); | ||
|
|
||
| await Sentry.flush(2000); | ||
| } | ||
|
|
||
| run(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -86,6 +86,7 @@ type GenAiOperation = keyof typeof GEN_AI_OPERATION_SPAN_OPS; | |
| const VERCEL_AI_OPERATION_ID_ATTRIBUTE = 'vercel.ai.operationId'; | ||
| const VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE = 'vercel.ai.model.provider'; | ||
| const VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE = 'vercel.ai.settings.maxRetries'; | ||
| const VERCEL_AI_TELEMETRY_METADATA_ATTRIBUTE_PREFIX = 'vercel.ai.telemetry.metadata.'; | ||
|
|
||
| // Tracks the top-level operationId (and whether it streams) per `callId` so a model-call span can | ||
| // name its `doGenerate`/`doStream` operation the same way the OTel integration does. `isStream` is | ||
|
|
@@ -417,8 +418,9 @@ export function createSpanFromMessage( | |
| recordToolDescriptions(callId, event.tools); | ||
| } | ||
|
|
||
| const baseAttributes: Record<string, string | number | boolean> = { | ||
| const baseAttributes: SpanAttributes = { | ||
| [SENTRY_ORIGIN]: ORIGIN, | ||
| ...telemetryMetadataAttributes(event.telemetryMetadata), | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I wonder if this should be gated on recordInputs or dataCollection.genAI |
||
| ...(provider ? { [GEN_AI_PROVIDER_NAME]: provider, [VERCEL_AI_MODEL_PROVIDER_ATTRIBUTE]: provider } : {}), | ||
| ...(modelId ? { [GEN_AI_REQUEST_MODEL]: modelId } : {}), | ||
| ...(maxRetries !== undefined ? { [VERCEL_AI_SETTINGS_MAX_RETRIES_ATTRIBUTE]: maxRetries } : {}), | ||
|
|
@@ -466,6 +468,22 @@ export function createSpanFromMessage( | |
| } | ||
| } | ||
|
|
||
| /** | ||
| * `experimental_telemetry.metadata` (`ai` <= 6) as `vercel.ai.telemetry.metadata.<key>`, the names the OTel | ||
| * integration produced from the SDK's `ai.telemetry.metadata.*`. Only the orchestrion adapter sets | ||
| * `event.telemetryMetadata`; `ai` 7 has no `telemetry.metadata`. | ||
| */ | ||
| function telemetryMetadataAttributes(metadata: unknown): Record<string, string> { | ||
| const attributes: Record<string, string> = {}; | ||
| if (isObjectLike(metadata)) { | ||
| for (const [key, value] of Object.entries(metadata)) { | ||
| if (value === null || value === undefined) continue; | ||
| attributes[`${VERCEL_AI_TELEMETRY_METADATA_ATTRIBUTE_PREFIX}${key}`] = String(value); | ||
| } | ||
|
isaacs marked this conversation as resolved.
|
||
| } | ||
| return attributes; | ||
| } | ||
|
|
||
| /** Start a `gen_ai.<operation>` span named `<operation> <suffix>` (or just `<operation>` when no suffix). */ | ||
| function startGenAiSpan(operation: GenAiOperation, suffix: string | undefined, attributes: SpanAttributes): Span { | ||
| return startInactiveSpan({ | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
61 changes: 61 additions & 0 deletions
61
packages/server-utils/test/integrations/vercel-ai/telemetry-metadata.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| import { afterEach, beforeEach, describe, expect, it } from 'vitest'; | ||
| import { getMainCarrier, setCurrentClient, spanToStaticSpanJSON } from '@sentry/core'; | ||
| import type { Span } from '@sentry/core'; | ||
| import { createSpanFromMessage } from '../../../src/integrations/vercel-ai/vercel-ai-dc-subscriber'; | ||
| import { getDefaultTestClientOptions, TestClient } from '../../mocks/client'; | ||
|
|
||
| describe('Vercel AI telemetry metadata', () => { | ||
| beforeEach(() => { | ||
| getMainCarrier().__SENTRY__ = undefined; | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| getMainCarrier().__SENTRY__ = undefined; | ||
| }); | ||
|
|
||
| function setupClient(): Span[] { | ||
| const client = new TestClient( | ||
| getDefaultTestClientOptions({ | ||
| dsn: 'https://public@dsn.ingest.sentry.io/1337', | ||
| tracesSampleRate: 1, | ||
| }), | ||
| ); | ||
| setCurrentClient(client); | ||
| client.init(); | ||
|
|
||
| const endedSpans: Span[] = []; | ||
| client.on('spanEnd', span => endedSpans.push(span)); | ||
| return endedSpans; | ||
| } | ||
|
|
||
| it('records metadata values as strings and skips null and undefined', () => { | ||
| const endedSpans = setupClient(); | ||
| const span = createSpanFromMessage( | ||
| { | ||
| type: 'generateText', | ||
| event: { | ||
| telemetryMetadata: { | ||
| requestId: 'req_1', | ||
| attempt: 2, | ||
| cached: false, | ||
| tags: ['a', 'b'], | ||
| empty: null, | ||
| missing: undefined, | ||
| }, | ||
| }, | ||
| } as Parameters<typeof createSpanFromMessage>[0], | ||
| {} as Parameters<typeof createSpanFromMessage>[1], | ||
| ); | ||
| span?.end(); | ||
|
|
||
| const data = spanToStaticSpanJSON(endedSpans[0]!).data; | ||
| expect(data).toMatchObject({ | ||
| 'vercel.ai.telemetry.metadata.requestId': 'req_1', | ||
| 'vercel.ai.telemetry.metadata.attempt': '2', | ||
| 'vercel.ai.telemetry.metadata.cached': 'false', | ||
| 'vercel.ai.telemetry.metadata.tags': 'a,b', | ||
| }); | ||
| expect(data).not.toHaveProperty('vercel.ai.telemetry.metadata.empty'); | ||
| expect(data).not.toHaveProperty('vercel.ai.telemetry.metadata.missing'); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.