UNPKG

@sentry/core

Version:
78 lines (66 loc) 2.64 kB
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); const genAiAttributes = require('../ai/gen-ai-attributes.js'); const constants = require('./constants.js'); /** * Accumulates token data from a span to its parent in the token accumulator map. * This function extracts token usage from the current span and adds it to the * accumulated totals for its parent span. */ function accumulateTokensForParent(span, tokenAccumulator) { const parentSpanId = span.parent_span_id; if (!parentSpanId) { return; } const inputTokens = span.data[genAiAttributes.GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]; const outputTokens = span.data[genAiAttributes.GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]; if (typeof inputTokens === 'number' || typeof outputTokens === 'number') { const existing = tokenAccumulator.get(parentSpanId) || { inputTokens: 0, outputTokens: 0 }; if (typeof inputTokens === 'number') { existing.inputTokens += inputTokens; } if (typeof outputTokens === 'number') { existing.outputTokens += outputTokens; } tokenAccumulator.set(parentSpanId, existing); } } /** * Applies accumulated token data to the `gen_ai.invoke_agent` span. * Only immediate children of the `gen_ai.invoke_agent` span are considered, * since aggregation will automatically occur for each parent span. */ function applyAccumulatedTokens( spanOrTrace, tokenAccumulator, ) { const accumulated = tokenAccumulator.get(spanOrTrace.span_id); if (!accumulated || !spanOrTrace.data) { return; } if (accumulated.inputTokens > 0) { spanOrTrace.data[genAiAttributes.GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = accumulated.inputTokens; } if (accumulated.outputTokens > 0) { spanOrTrace.data[genAiAttributes.GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = accumulated.outputTokens; } if (accumulated.inputTokens > 0 || accumulated.outputTokens > 0) { spanOrTrace.data['gen_ai.usage.total_tokens'] = accumulated.inputTokens + accumulated.outputTokens; } } /** * Get the span associated with a tool call ID */ function _INTERNAL_getSpanForToolCallId(toolCallId) { return constants.toolCallSpanMap.get(toolCallId); } /** * Clean up the span mapping for a tool call ID */ function _INTERNAL_cleanupToolCallSpan(toolCallId) { constants.toolCallSpanMap.delete(toolCallId); } exports._INTERNAL_cleanupToolCallSpan = _INTERNAL_cleanupToolCallSpan; exports._INTERNAL_getSpanForToolCallId = _INTERNAL_getSpanForToolCallId; exports.accumulateTokensForParent = accumulateTokensForParent; exports.applyAccumulatedTokens = applyAccumulatedTokens; //# sourceMappingURL=utils.js.map