|
| 1 | +/* |
| 2 | + * Copyright 2026 New Relic Corporation. All rights reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +'use strict' |
| 7 | + |
| 8 | +const { DESTINATIONS } = require('../config/attribute-filter') |
| 9 | +const { makeId } = require('../util/hashes') |
| 10 | + |
| 11 | +/** |
| 12 | + * The base LLM event class that contains logic and properties |
| 13 | + * (e.g. `trace_id`, `vendor`) that are common to all LLM events. |
| 14 | + * |
| 15 | + * @property {string} id UUID or identifier for the event |
| 16 | + * @property {string} request_id ID from request/response headers |
| 17 | + * @property {string} span_id GUID of active span |
| 18 | + * @property {string} trace_id Current trace ID |
| 19 | + * @property {string} response.model Model name from response |
| 20 | + * @property {string} vendor Lowercased vendor name, e.g. "openai" |
| 21 | + * @property {string} ingest_source Always set to 'Node' |
| 22 | + * @property {boolean|undefined} error Set to `true` if an error occurred |
| 23 | + * during creation call, omitted if no error occurred |
| 24 | + */ |
| 25 | +class LlmEvent { |
| 26 | + ingest_source = 'Node' |
| 27 | + |
| 28 | + /** |
| 29 | + * @param {object} params Constructor parameters |
| 30 | + * @param {Agent} params.agent New Relic agent instance |
| 31 | + * @param {TraceSegment} params.segment Current segment |
| 32 | + * @param {Transaction} params.transaction Current and active transaction |
| 33 | + * @param {string} params.vendor Lowercase vendor name, e.g. "openai" |
| 34 | + * @param {string} [params.responseModel] Model name from response |
| 35 | + * @param {string} [params.requestId] ID from request/response headers |
| 36 | + * @param {boolean} [params.error] Set to `true` if an error occurred during |
| 37 | + * creation call, omitted if no error occurred |
| 38 | + */ |
| 39 | + constructor({ agent, segment, transaction, vendor, responseModel, requestId, error }) { |
| 40 | + this.id = makeId(32) |
| 41 | + this.span_id = segment.id |
| 42 | + this.trace_id = transaction.traceId |
| 43 | + this.vendor = vendor |
| 44 | + this.metadata = agent |
| 45 | + |
| 46 | + // Omit `error` property if no error occurred |
| 47 | + if (error === true) { |
| 48 | + this.error = error |
| 49 | + } |
| 50 | + |
| 51 | + // If a certain attribute value is not accessible via instrumentation, |
| 52 | + // it can be omitted from the event. |
| 53 | + if (requestId) this.request_id = requestId |
| 54 | + if (responseModel) this['response.model'] = responseModel |
| 55 | + } |
| 56 | + |
| 57 | + // eslint-disable-next-line accessor-pairs |
| 58 | + set metadata(agent) { |
| 59 | + const transaction = agent.tracer.getTransaction() |
| 60 | + const attrs = transaction?.trace?.custom.get(DESTINATIONS.TRANS_SCOPE) || {} |
| 61 | + for (const [key, value] of Object.entries(attrs)) { |
| 62 | + if (key.startsWith('llm.')) { |
| 63 | + this[key] = value |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Determines if the provided token count is valid. |
| 70 | + * A valid token count is greater than 0 and not null. |
| 71 | + * @param {number} tokenCount The token count obtained from the token callback |
| 72 | + * @returns {boolean} Whether the token count is valid |
| 73 | + */ |
| 74 | + validTokenCount(tokenCount) { |
| 75 | + return tokenCount !== null && tokenCount > 0 |
| 76 | + } |
| 77 | + |
| 78 | + /** |
| 79 | + * Calculates the total token count from the prompt tokens and completion tokens |
| 80 | + * set in the event. |
| 81 | + * @returns {number} The total token count |
| 82 | + */ |
| 83 | + getTotalTokenCount() { |
| 84 | + return Number(this['response.usage.prompt_tokens']) + Number(this['response.usage.completion_tokens']) |
| 85 | + } |
| 86 | + |
| 87 | + /** |
| 88 | + * If `totalTokens` is valid, assigns it to |
| 89 | + * `this['response.usage.total_tokens']`. |
| 90 | + * @param {number} totalTokens total tokens on embedding message |
| 91 | + */ |
| 92 | + setTokensOnEmbeddingMessage(totalTokens) { |
| 93 | + if (this.validTokenCount(totalTokens)) { |
| 94 | + this['response.usage.total_tokens'] = totalTokens |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + /** |
| 99 | + * Sets the provided tokens counts on the LLM event. |
| 100 | + * Checks if promptToken and completionToken are greater than zero before setting. |
| 101 | + * This is because the spec states that token counts should only be set if both |
| 102 | + * are present. |
| 103 | + * @param {object} params to the function |
| 104 | + * @param {object} params.promptTokens value of prompt token count |
| 105 | + * @param {object} params.completionTokens value of completion(s) token count |
| 106 | + * @param {object} params.totalTokens value of prompt + completion(s) token count |
| 107 | + */ |
| 108 | + setTokensInResponse({ promptTokens, completionTokens, totalTokens }) { |
| 109 | + if (this.validTokenCount(promptTokens) && this.validTokenCount(completionTokens)) { |
| 110 | + this['response.usage.prompt_tokens'] = promptTokens |
| 111 | + this['response.usage.completion_tokens'] = completionTokens |
| 112 | + this['response.usage.total_tokens'] = totalTokens || this.getTotalTokenCount() |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + /** |
| 117 | + * Sets `token_count` to 0 on the LlmChatCompletionMessage if both prompt and completion tokens are greater than zero. |
| 118 | + * This is because the spec states that if token counts are set, then we should set token_count to 0 to indicate |
| 119 | + * that the token calculation does not have to occur in the ingest pipeline. |
| 120 | + * @param {object} params to the function |
| 121 | + * @param {object} params.promptTokens value of prompt token count |
| 122 | + * @param {object} params.completionTokens value of completion(s) token count |
| 123 | + */ |
| 124 | + setTokenInCompletionMessage({ promptTokens, completionTokens }) { |
| 125 | + if (this.validTokenCount(promptTokens) && this.validTokenCount(completionTokens)) { |
| 126 | + this.token_count = 0 |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + /** |
| 131 | + * Calculates prompt and completion token counts using the provided callback and models. |
| 132 | + * If both counts are valid, sets this.token_count to 0. |
| 133 | + * |
| 134 | + * @param {object} options - The params object. |
| 135 | + * @param {Function} options.tokenCB - The token counting callback function. |
| 136 | + * @param {string} options.reqModel - The model used for the prompt. |
| 137 | + * @param {string} options.resModel - The model used for the completion. |
| 138 | + * @param {string} options.promptContent - The prompt content to count tokens for. |
| 139 | + * @param {string} options.completionContent - The completion content to count tokens for. |
| 140 | + * @returns {void} |
| 141 | + */ |
| 142 | + setTokenFromCallback({ tokenCB, reqModel, resModel, promptContent, completionContent }) { |
| 143 | + const promptToken = this.calculateCallbackTokens(tokenCB, reqModel, promptContent) |
| 144 | + const completionToken = this.calculateCallbackTokens(tokenCB, resModel, completionContent) |
| 145 | + |
| 146 | + this.setTokenInCompletionMessage({ promptTokens: promptToken, completionTokens: completionToken }) |
| 147 | + } |
| 148 | + |
| 149 | + /** |
| 150 | + * Calculates prompt and completion token counts using the provided callback and models. |
| 151 | + * If both counts are valid, sets token prompt, completion and total counts on the event. |
| 152 | + * |
| 153 | + * @param {object} options - The params object. |
| 154 | + * @param {Function} options.tokenCB - The token counting callback function. |
| 155 | + * @param {string} options.reqModel - The model used for the prompt. |
| 156 | + * @param {string} options.resModel - The model used for the completion. |
| 157 | + * @param {string} options.promptContent - The prompt content to count tokens for. |
| 158 | + * @param {string} options.completionContent - The completion content to count tokens for. |
| 159 | + * @returns {void} |
| 160 | + */ |
| 161 | + setTokenUsageFromCallback({ tokenCB, reqModel, resModel, promptContent, completionContent }) { |
| 162 | + const promptTokens = this.calculateCallbackTokens(tokenCB, reqModel, promptContent) |
| 163 | + const completionTokens = this.calculateCallbackTokens(tokenCB, resModel, completionContent) |
| 164 | + this.setTokensInResponse({ promptTokens, completionTokens, totalTokens: promptTokens + completionTokens }) |
| 165 | + } |
| 166 | + |
| 167 | + /** |
| 168 | + * Calculate the token counts using the provided callback. |
| 169 | + * @param {Function} tokenCB - The token count callback function. |
| 170 | + * @param {string} model - The model. |
| 171 | + * @param {string} content - The content to calculate tokens for, such as prompt or completion response. |
| 172 | + * @returns {number|undefined} - The calculated token count or undefined if callback is not a function. |
| 173 | + */ |
| 174 | + calculateCallbackTokens(tokenCB, model, content) { |
| 175 | + if (typeof tokenCB === 'function') { |
| 176 | + return tokenCB(model, content) |
| 177 | + } |
| 178 | + return undefined |
| 179 | + } |
| 180 | +} |
| 181 | + |
| 182 | +module.exports = LlmEvent |
0 commit comments