|
| 1 | +import { SEMANTIC_ATTRIBUTE_SENTRY_OP, defineIntegration, spanToJSON } from '@sentry/core'; |
| 2 | +import type { IntegrationFn } from '@sentry/types'; |
| 3 | + |
| 4 | +import { addOriginToSpan } from '../../utils/addOriginToSpan'; |
| 5 | + |
| 6 | +const INTEGRATION_NAME = 'VercelAi'; |
| 7 | + |
| 8 | +const _vercelAiIntegration = (() => { |
| 9 | + return { |
| 10 | + name: INTEGRATION_NAME, |
| 11 | + setupOnce() { |
| 12 | + // TODO: Vercel Instrumentation. |
| 13 | + }, |
| 14 | + |
| 15 | + setup(client) { |
| 16 | + // TODO: Only run if @vercel/ai is installed. |
| 17 | + client.on('spanStart', span => { |
| 18 | + const { data: attributes, description: name } = spanToJSON(span); |
| 19 | + |
| 20 | + if (!attributes || !name) { |
| 21 | + return; |
| 22 | + } |
| 23 | + |
| 24 | + // https://sdk.vercel.ai/docs/ai-sdk-core/telemetry#basic-llm-span-information |
| 25 | + if (attributes['ai.model.id'] && attributes['ai.model.provider']) { |
| 26 | + addOriginToSpan(span, 'auto.vercel.ai'); |
| 27 | + |
| 28 | + const aiOperation = name.replace('ai.', ''); |
| 29 | + if (aiOperation.includes('embed')) { |
| 30 | + span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'ai.embeddings'); |
| 31 | + } else { |
| 32 | + span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'ai.run'); |
| 33 | + } |
| 34 | + |
| 35 | + if (attributes['ai.prompt']) { |
| 36 | + span.setAttribute('ai.input_messages', attributes['ai.prompt']); |
| 37 | + } |
| 38 | + if (attributes['ai.usage.completionTokens'] != undefined) { |
| 39 | + span.setAttribute('ai.completion_tokens.used', attributes['ai.usage.completionTokens']); |
| 40 | + } |
| 41 | + if (attributes['ai.usage.promptTokens'] != undefined) { |
| 42 | + span.setAttribute('ai.prompt_tokens.used', attributes['ai.usage.promptTokens']); |
| 43 | + } |
| 44 | + if ( |
| 45 | + attributes['ai.usage.completionTokens'] != undefined && |
| 46 | + attributes['ai.usage.promptTokens'] != undefined |
| 47 | + ) { |
| 48 | + span.setAttribute( |
| 49 | + 'ai.tokens.used', |
| 50 | + attributes['ai.usage.completionTokens'] + attributes['ai.usage.promptTokens'], |
| 51 | + ); |
| 52 | + } |
| 53 | + if (attributes['ai.model.id']) { |
| 54 | + span.setAttribute('ai.model_id', attributes['ai.model.id']); |
| 55 | + } |
| 56 | + |
| 57 | + span.setAttribute('ai.streaming', name.includes('stream')); |
| 58 | + } |
| 59 | + }); |
| 60 | + }, |
| 61 | + }; |
| 62 | +}) satisfies IntegrationFn; |
| 63 | + |
| 64 | +/** |
| 65 | + * Integration for @vercel/ai |
| 66 | + */ |
| 67 | +export const vercelAiIntegration = defineIntegration(_vercelAiIntegration); |
0 commit comments