Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
Expand Up @@ -432,6 +432,9 @@ describe('Vercel AI integration', () => {
'vercel.ai.settings.maxSteps': 1,
'vercel.ai.streaming': false,
'gen_ai.response.model': 'mock-model-id',
'gen_ai.usage.input_tokens': 15,
'gen_ai.usage.output_tokens': 25,
'gen_ai.usage.total_tokens': 40,
'operation.name': 'ai.generateText',
'sentry.op': 'gen_ai.invoke_agent',
'sentry.origin': 'auto.vercelai.otel',
Expand Down Expand Up @@ -550,6 +553,9 @@ describe('Vercel AI integration', () => {
'vercel.ai.settings.maxSteps': 1,
'vercel.ai.streaming': false,
'gen_ai.response.model': 'mock-model-id',
'gen_ai.usage.input_tokens': 15,
'gen_ai.usage.output_tokens': 25,
'gen_ai.usage.total_tokens': 40,
'operation.name': 'ai.generateText',
'sentry.op': 'gen_ai.invoke_agent',
'sentry.origin': 'auto.vercelai.otel',
Expand Down
48 changes: 48 additions & 0 deletions packages/core/src/utils/vercel-ai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,17 @@ function onVercelAiSpanStart(span: Span): void {

function vercelAiEventProcessor(event: Event): Event {
if (event.type === 'transaction' && event.spans) {
// First pass: process all spans normally
for (const span of event.spans) {
// this mutates spans in-place
processEndedVercelAiSpan(span);
}

// Second pass: accumulate tokens for gen_ai.invoke_agent spans
// TODO: Determine how to handle token aggregation for tool call spans.
for (const span of event.spans) {
accumulateTokensFromChildSpans(span, event.spans);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm, can we combine this into a single pass somehow? 🤔 that would be more efficient I suppose.

Copy link
Member Author

@RulaKhaled RulaKhaled Aug 4, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can but it's safer to leave them separate because we are processing child spans to accumulate the tokens, we need to make sure they are all transformed completely to the attribute we are expecting, otherwise we could end up with a parent span first that have child spans that still use vercel naming so we end up not processing it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm overall this is quite expensive, looking at it :D because we loop over all spans a lot:

  1. Once in the first pass
  2. Once in the second pass
    a. for each second pass, we iterate over all spans again when filtering
    b. then finally once more over the filtered spans (which is a subset already, but still)

IMHO it's probably worth it to find a way to streamline this to get to max. 2 passes. I would propose something like this:

  1. We create an object to hold the summarized tokens. e.g. something like this: const tmpAmounts: Map<string, TokenSummary> = new Map();
  2. We pass this into the first pass function as second argument, so that can mutate it
  3. The function that transforms attributes, at the very end, updates the passed in map by incrementing the token summary for the map item of the parentSpanId, e.g. something like this (simplified...):
const parentSpanId = spanToJSON(span).parent_span_id;
if (parentSpanId) {
  const parentSummary = tmpAmounts.get(parentSpanId) || { total: 0 };
  parentSummary.total += amount;
  tmpAmounts.set(parentSpanId, parentSummary);
}
  1. Finally, after the first pass, we iterate over tmpAmounts and update the parent spans with the stored summaries.

I think this or something like this should reduce overhead considerably 🤔

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

very nice, i'll try it out.

}
}
return event;
}
Expand Down Expand Up @@ -241,6 +248,47 @@ export function addVercelAiProcessors(client: Client): void {
client.addEventProcessor(Object.assign(vercelAiEventProcessor, { id: 'VercelAiEventProcessor' }));
}

/**
* For the gen_ai.invoke_agent span, iterate over child spans and aggregate tokens:
* - Input tokens from client LLM child spans that include `gen_ai.usage.input_tokens` attribute.
* - Output tokens from client LLM child spans that include `gen_ai.usage.output_tokens` attribute.
* - Total tokens from client LLM child spans that include `gen_ai.usage.total_tokens` attribute.
*
* Only immediate children of the `gen_ai.invoke_agent` span need to be considered,
* since aggregation will automatically occur for each parent span.
*/
function accumulateTokensFromChildSpans(spanJSON: SpanJSON, allSpans: SpanJSON[]): void {
if (spanJSON.op !== 'gen_ai.invoke_agent') {
return;
}
const childSpans = allSpans.filter(childSpan => childSpan.parent_span_id === spanJSON.span_id);

let totalInputTokens = 0;
let totalOutputTokens = 0;

for (const childSpan of childSpans) {
const inputTokens = childSpan.data[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE];
const outputTokens = childSpan.data[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE];

if (typeof inputTokens === 'number') {
totalInputTokens += inputTokens;
}
if (typeof outputTokens === 'number') {
totalOutputTokens += outputTokens;
}
}

if (totalInputTokens > 0) {
spanJSON.data[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = totalInputTokens;
}
if (totalOutputTokens > 0) {
spanJSON.data[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = totalOutputTokens;
}
if (totalInputTokens > 0 || totalOutputTokens > 0) {
spanJSON.data['gen_ai.usage.total_tokens'] = totalInputTokens + totalOutputTokens;
}
}

function addProviderMetadataToAttributes(attributes: SpanAttributes): void {
const providerMetadata = attributes[AI_RESPONSE_PROVIDER_METADATA_ATTRIBUTE] as string | undefined;
if (providerMetadata) {
Expand Down