|
| 1 | +/* |
| 2 | + * Copyright 2026 New Relic Corporation. All rights reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +'use strict' |
| 7 | +const LlmChatCompletionMessage = require('../chat-message') |
| 8 | +const { isSimpleObject } = require('../../util/objects') |
| 9 | + |
| 10 | +/** |
| 11 | + * Encapsulates a LangChain LlmChatCompletionMessage. |
| 12 | + */ |
| 13 | +class LangChainLlmChatCompletionMessage extends LlmChatCompletionMessage { |
| 14 | + virtual_llm = true |
| 15 | + /** |
| 16 | + * @param {object} params constructor parameters |
| 17 | + * @param {Agent} params.agent New Relic agent instance |
| 18 | + * @param {object} params.segment Current segment |
| 19 | + * @param {object} params.transaction Current and active transaction |
| 20 | + * @param {string} params.runId LangChain run ID (will be used as response ID) |
| 21 | + * @param {number} params.sequence Index (beginning at 0) associated with |
| 22 | + * each message including the prompt and responses |
| 23 | + * @param {string} params.content Content of the message |
| 24 | + * @param {string} [params.role] Role of the message creator (e.g. `user`, `assistant`, `tool`) |
| 25 | + * @param {string} params.completionId ID of the `LlmChatCompletionSummary` event that |
| 26 | + * this message event is connected to |
| 27 | + * @param {boolean} [params.isResponse] `true` if a message is the result of a chat |
| 28 | + * completion and not an input message - omitted in `false` cases |
| 29 | + * @param {object} params.metadata LangChain metadata object |
| 30 | + * @param {object[]} params.tags LangChain tags |
| 31 | + */ |
| 32 | + constructor({ agent, segment, transaction, runId, sequence, role, content, completionId, isResponse, metadata, tags }) { |
| 33 | + super({ agent, |
| 34 | + segment, |
| 35 | + transaction, |
| 36 | + vendor: 'langchain', |
| 37 | + responseId: runId, |
| 38 | + requestId: runId, |
| 39 | + sequence, |
| 40 | + content, |
| 41 | + role, |
| 42 | + completionId, |
| 43 | + isResponse }) |
| 44 | + |
| 45 | + // TODO: Does not appear in AIM spec, but was a |
| 46 | + // requirement for LangChain instrumentation back in 2024? |
| 47 | + this.appName = agent.config.applications()[0] |
| 48 | + this.langchainMeta = metadata |
| 49 | + this.tags = Array.isArray(tags) ? tags.join(',') : tags |
| 50 | + } |
| 51 | + |
| 52 | + // eslint-disable-next-line accessor-pairs |
| 53 | + set langchainMeta(value) { |
| 54 | + if (isSimpleObject(value) === false) { |
| 55 | + return |
| 56 | + } |
| 57 | + for (const [key, val] of Object.entries(value)) { |
| 58 | + this[`metadata.${key}`] = val |
| 59 | + } |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +module.exports = LangChainLlmChatCompletionMessage |
0 commit comments