|
| 1 | +/* |
| 2 | + * Copyright 2025 New Relic Corporation. All rights reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +const { |
| 7 | + LlmChatCompletionMessage, |
| 8 | + LlmChatCompletionSummary, |
| 9 | + LlmErrorMessage |
| 10 | +} = require('../../../lib/llm-events/google-genai') |
| 11 | +const { extractLlmContext } = require('../../util/llm-utils') |
| 12 | +const { AI } = require('../../../lib/metrics/names') |
| 13 | +const { GEMINI } = AI |
| 14 | +const { DESTINATIONS } = require('../../config/attribute-filter') |
| 15 | + |
| 16 | +const Subscriber = require('../base') |
| 17 | + |
| 18 | +class GoogleGenAISubscriber extends Subscriber { |
| 19 | + constructor({ agent, logger, channelName, packageName = '@google/genai' }) { |
| 20 | + super({ agent, logger, channelName, packageName }) |
| 21 | + this.events = ['asyncEnd'] |
| 22 | + } |
| 23 | + |
| 24 | + get enabled() { |
| 25 | + return super.enabled && this.config?.ai_monitoring?.enabled |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Enqueues a LLM event to the custom event aggregator |
| 30 | + * |
| 31 | + * @param {object} params input params |
| 32 | + * @param {string} params.type LLM event type |
| 33 | + * @param {object} params.msg LLM event |
| 34 | + */ |
| 35 | + recordEvent({ type, msg }) { |
| 36 | + const llmContext = extractLlmContext(this.agent) |
| 37 | + |
| 38 | + this.agent.customEventAggregator.add([ |
| 39 | + { type, timestamp: Date.now() }, |
| 40 | + Object.assign({}, msg, llmContext) |
| 41 | + ]) |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Generates LlmChatCompletionSummary for a chat completion creation. |
| 46 | + * Also iterates over both input messages and the first response message |
| 47 | + * and creates LlmChatCompletionMessage. |
| 48 | + * |
| 49 | + * Also assigns relevant ids by response id for LlmFeedbackEvent creation |
| 50 | + * |
| 51 | + * @param {object} params input params |
| 52 | + * @param {TraceSegment} params.segment active segment from chat completion |
| 53 | + * @param {object} params.request chat completion params |
| 54 | + * @param {object} [params.response] chat completion response |
| 55 | + * @param {boolean} [params.err] err if it exists |
| 56 | + * @param {Transaction} params.transaction active transaction |
| 57 | + */ |
| 58 | + recordChatCompletionMessages({ |
| 59 | + segment, |
| 60 | + request, |
| 61 | + response, |
| 62 | + err, |
| 63 | + transaction |
| 64 | + }) { |
| 65 | + const agent = this.agent |
| 66 | + if (!response) { |
| 67 | + // If we get an error, it is possible that `response = null`. |
| 68 | + // In that case, we define it to be an empty object. |
| 69 | + response = {} |
| 70 | + } |
| 71 | + |
| 72 | + // Explicitly end segment to provide consistent duration |
| 73 | + // for both LLM events and the segment |
| 74 | + segment.end() |
| 75 | + const completionSummary = new LlmChatCompletionSummary({ |
| 76 | + agent, |
| 77 | + segment, |
| 78 | + transaction, |
| 79 | + request, |
| 80 | + response, |
| 81 | + withError: err != null |
| 82 | + }) |
| 83 | + |
| 84 | + // Only take the first response message and append to input messages |
| 85 | + // request.contents can be a string or an array of strings |
| 86 | + // response.candidates is an array of candidates (choices); we only take the first one |
| 87 | + const inputMessages = Array.isArray(request.contents) ? request.contents : [request.contents] |
| 88 | + const responseMessage = response?.candidates?.[0]?.content |
| 89 | + const messages = responseMessage !== undefined ? [...inputMessages, responseMessage] : inputMessages |
| 90 | + messages.forEach((message, index) => { |
| 91 | + const completionMsg = new LlmChatCompletionMessage({ |
| 92 | + agent, |
| 93 | + segment, |
| 94 | + transaction, |
| 95 | + request, |
| 96 | + response, |
| 97 | + index, |
| 98 | + completionId: completionSummary.id, |
| 99 | + message |
| 100 | + }) |
| 101 | + |
| 102 | + this.recordEvent({ type: 'LlmChatCompletionMessage', msg: completionMsg }) |
| 103 | + }) |
| 104 | + |
| 105 | + this.recordEvent({ type: 'LlmChatCompletionSummary', msg: completionSummary }) |
| 106 | + |
| 107 | + if (err) { |
| 108 | + const llmError = new LlmErrorMessage({ cause: err, summary: completionSummary, response }) |
| 109 | + agent.errors.add(transaction, err, llmError) |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + /** |
| 114 | + * Increments the tracking metric and sets the llm attribute on transactions |
| 115 | + * |
| 116 | + * @param {object} params input params |
| 117 | + * @param {Transaction} params.transaction active transaction |
| 118 | + * @param {string} params.version package version |
| 119 | + */ |
| 120 | + addLlmMeta({ transaction, version }) { |
| 121 | + const TRACKING_METRIC = `${GEMINI.TRACKING_PREFIX}/${version}` |
| 122 | + this.agent.metrics.getOrCreateMetric(TRACKING_METRIC).incrementCallCount() |
| 123 | + transaction.trace.attributes.addAttribute(DESTINATIONS.TRANS_EVENT, 'llm', true) |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +module.exports = GoogleGenAISubscriber |
0 commit comments