@n8n/n8n-nodes-langchain 2.1.2 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/nodes/Guardrails/actions/checks/keywords.js +25 -7
  2. package/dist/nodes/Guardrails/actions/checks/keywords.js.map +1 -1
  3. package/dist/nodes/agents/OpenAiAssistant/OpenAiAssistant.node.js +5 -1
  4. package/dist/nodes/agents/OpenAiAssistant/OpenAiAssistant.node.js.map +1 -1
  5. package/dist/nodes/chains/ChainLLM/ChainLlm.node.js +1 -1
  6. package/dist/nodes/chains/ChainLLM/ChainLlm.node.js.map +1 -1
  7. package/dist/nodes/chains/ChainLLM/methods/chainExecutor.js +27 -13
  8. package/dist/nodes/chains/ChainLLM/methods/chainExecutor.js.map +1 -1
  9. package/dist/nodes/chains/ChainLLM/methods/promptUtils.js +35 -2
  10. package/dist/nodes/chains/ChainLLM/methods/promptUtils.js.map +1 -1
  11. package/dist/nodes/embeddings/EmbeddingsOpenAI/EmbeddingsOpenAi.node.js +6 -1
  12. package/dist/nodes/embeddings/EmbeddingsOpenAI/EmbeddingsOpenAi.node.js.map +1 -1
  13. package/dist/nodes/llms/LMChatOpenAi/LmChatOpenAi.node.js +7 -1
  14. package/dist/nodes/llms/LMChatOpenAi/LmChatOpenAi.node.js.map +1 -1
  15. package/dist/nodes/llms/LMChatOpenAi/methods/loadModels.js +5 -1
  16. package/dist/nodes/llms/LMChatOpenAi/methods/loadModels.js.map +1 -1
  17. package/dist/nodes/llms/LMOpenAi/LmOpenAi.node.js +5 -1
  18. package/dist/nodes/llms/LMOpenAi/LmOpenAi.node.js.map +1 -1
  19. package/dist/nodes/tools/ToolWorkflow/v2/ToolWorkflowV2.node.js +13 -8
  20. package/dist/nodes/tools/ToolWorkflow/v2/ToolWorkflowV2.node.js.map +1 -1
  21. package/dist/nodes/tools/ToolWorkflow/v2/utils/WorkflowToolService.js +2 -1
  22. package/dist/nodes/tools/ToolWorkflow/v2/utils/WorkflowToolService.js.map +1 -1
  23. package/dist/nodes/vendors/OpenAi/v1/actions/assistant/message.operation.js +5 -1
  24. package/dist/nodes/vendors/OpenAi/v1/actions/assistant/message.operation.js.map +1 -1
  25. package/dist/types/nodes.json +1 -1
  26. package/dist/utils/agent-execution/buildSteps.js +14 -1
  27. package/dist/utils/agent-execution/buildSteps.js.map +1 -1
  28. package/dist/utils/embeddings/embeddingInputValidation.js +55 -0
  29. package/dist/utils/embeddings/embeddingInputValidation.js.map +1 -0
  30. package/dist/utils/logWrapper.js +10 -4
  31. package/dist/utils/logWrapper.js.map +1 -1
  32. package/package.json +7 -7
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../nodes/vendors/OpenAi/v1/actions/assistant/message.operation.ts"],"sourcesContent":["import type { BaseMessage } from '@langchain/core/messages';\nimport { AgentExecutor } from '@langchain/classic/agents';\nimport type { OpenAIToolType } from '@langchain/classic/dist/experimental/openai_assistant/schema';\nimport { OpenAIAssistantRunnable } from '@langchain/classic/experimental/openai_assistant';\nimport type { BufferWindowMemory } from '@langchain/classic/memory';\nimport omit from 'lodash/omit';\nimport type {\n\tIDataObject,\n\tIExecuteFunctions,\n\tINodeExecutionData,\n\tINodeProperties,\n} from 'n8n-workflow';\nimport {\n\tApplicationError,\n\tNodeConnectionTypes,\n\tNodeOperationError,\n\tupdateDisplayOptions,\n} from 'n8n-workflow';\nimport { OpenAI as OpenAIClient } from 'openai';\n\nimport { promptTypeOptionsDeprecated } from '@utils/descriptions';\nimport { getConnectedTools, getPromptInputByType } from '@utils/helpers';\nimport { getTracingConfig } from '@utils/tracing';\n\nimport { formatToOpenAIAssistantTool, getChatMessages } from '../../../helpers/utils';\nimport { assistantRLC } from '../descriptions';\nimport { getProxyAgent } from '@utils/httpProxyAgent';\n\nconst properties: INodeProperties[] = [\n\tassistantRLC,\n\t{\n\t\t...promptTypeOptionsDeprecated,\n\t\tname: 'prompt',\n\t},\n\t{\n\t\tdisplayName: 'Prompt (User Message)',\n\t\tname: 'text',\n\t\ttype: 'string',\n\t\tdefault: '',\n\t\tplaceholder: 'e.g. Hello, how can you help me?',\n\t\ttypeOptions: {\n\t\t\trows: 2,\n\t\t},\n\t\tdisplayOptions: {\n\t\t\tshow: {\n\t\t\t\tprompt: ['define'],\n\t\t\t},\n\t\t},\n\t},\n\t{\n\t\tdisplayName: 'Memory',\n\t\tname: 'memory',\n\t\ttype: 'options',\n\t\toptions: [\n\t\t\t{\n\t\t\t\tname: 'Use memory connector',\n\t\t\t\tvalue: 'connector',\n\t\t\t\tdescription: 'Connect one of the supported memory nodes',\n\t\t\t},\n\t\t\t{\n\t\t\t\t// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased\n\t\t\t\tname: 'Use thread ID',\n\t\t\t\tvalue: 'threadId',\n\t\t\t\tdescription: 'Specify the ID of the thread to continue',\n\t\t\t},\n\t\t],\n\t\tdisplayOptions: {\n\t\t\tshow: {\n\t\t\t\t'@version': [{ _cnd: { gte: 1.6 } }],\n\t\t\t},\n\t\t},\n\t\tdefault: 'connector',\n\t},\n\t{\n\t\tdisplayName: 'Thread ID',\n\t\tname: 'threadId',\n\t\ttype: 'string',\n\t\tdefault: '',\n\t\tplaceholder: '',\n\t\tdescription: 'The ID of the thread to continue, a new thread will be created if not specified',\n\t\thint: 'If the thread ID is empty or undefined a new thread will be created and included in the response',\n\t\tdisplayOptions: {\n\t\t\tshow: {\n\t\t\t\t'@version': [{ _cnd: { gte: 1.6 } }],\n\t\t\t\tmemory: ['threadId'],\n\t\t\t},\n\t\t},\n\t},\n\t{\n\t\tdisplayName: 'Connect your own custom n8n tools to this node on the canvas',\n\t\tname: 'noticeTools',\n\t\ttype: 'notice',\n\t\tdefault: '',\n\t},\n\t{\n\t\tdisplayName: 'Options',\n\t\tname: 'options',\n\t\tplaceholder: 'Add Option',\n\t\tdescription: 'Additional options to add',\n\t\ttype: 'collection',\n\t\tdefault: {},\n\t\toptions: [\n\t\t\t{\n\t\t\t\tdisplayName: 'Base URL',\n\t\t\t\tname: 'baseURL',\n\t\t\t\tdefault: 'https://api.openai.com/v1',\n\t\t\t\tdescription: 'Override the default base URL for the API',\n\t\t\t\ttype: 'string',\n\t\t\t\tdisplayOptions: {\n\t\t\t\t\thide: {\n\t\t\t\t\t\t'@version': [{ _cnd: { gte: 1.8 } }],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tdisplayName: 'Max Retries',\n\t\t\t\tname: 'maxRetries',\n\t\t\t\tdefault: 2,\n\t\t\t\tdescription: 'Maximum number of retries to attempt',\n\t\t\t\ttype: 'number',\n\t\t\t},\n\t\t\t{\n\t\t\t\tdisplayName: 'Timeout',\n\t\t\t\tname: 'timeout',\n\t\t\t\tdefault: 10000,\n\t\t\t\tdescription: 'Maximum amount of time a request is allowed to take in milliseconds',\n\t\t\t\ttype: 'number',\n\t\t\t},\n\t\t\t{\n\t\t\t\tdisplayName: 'Preserve Original Tools',\n\t\t\t\tname: 'preserveOriginalTools',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: true,\n\t\t\t\tdescription:\n\t\t\t\t\t'Whether to preserve the original tools of the assistant after the execution of this node, otherwise the tools will be replaced with the connected tools, if any, default is true',\n\t\t\t\tdisplayOptions: {\n\t\t\t\t\tshow: {\n\t\t\t\t\t\t'@version': [{ _cnd: { gte: 1.3 } }],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t},\n];\n\nconst displayOptions = {\n\tshow: {\n\t\toperation: ['message'],\n\t\tresource: ['assistant'],\n\t},\n};\n\nexport const description = updateDisplayOptions(displayOptions, properties);\nconst mapChatMessageToThreadMessage = (\n\tmessage: BaseMessage,\n): OpenAIClient.Beta.Threads.ThreadCreateParams.Message => ({\n\trole: message._getType() === 'ai' ? 'assistant' : 'user',\n\tcontent: message.content.toString(),\n});\n\nexport async function execute(this: IExecuteFunctions, i: number): Promise<INodeExecutionData[]> {\n\tconst credentials = await this.getCredentials('openAiApi');\n\tconst nodeVersion = this.getNode().typeVersion;\n\n\tconst input = getPromptInputByType({\n\t\tctx: this,\n\t\ti,\n\t\tinputKey: 'text',\n\t\tpromptTypeKey: 'prompt',\n\t});\n\n\tconst assistantId = this.getNodeParameter('assistantId', i, '', { extractValue: true }) as string;\n\n\tconst options = this.getNodeParameter('options', i, {}) as {\n\t\tbaseURL?: string;\n\t\tmaxRetries: number;\n\t\ttimeout: number;\n\t\tpreserveOriginalTools?: boolean;\n\t};\n\n\tconst baseURL = (options.baseURL ?? credentials.url) as string;\n\n\tconst client = new OpenAIClient({\n\t\tapiKey: credentials.apiKey as string,\n\t\tmaxRetries: options.maxRetries ?? 2,\n\t\ttimeout: options.timeout ?? 10000,\n\t\tbaseURL,\n\t\tfetchOptions: {\n\t\t\tdispatcher: getProxyAgent(baseURL),\n\t\t},\n\t});\n\n\tconst agent = new OpenAIAssistantRunnable({ assistantId, client, asAgent: true });\n\n\tconst tools = await getConnectedTools(this, nodeVersion > 1, false);\n\tlet assistantTools;\n\n\tif (tools.length) {\n\t\tconst transformedConnectedTools = tools?.map(formatToOpenAIAssistantTool) ?? [];\n\t\tconst nativeToolsParsed: OpenAIToolType = [];\n\n\t\tassistantTools = (await client.beta.assistants.retrieve(assistantId)).tools;\n\n\t\tconst useCodeInterpreter = assistantTools.some((tool) => tool.type === 'code_interpreter');\n\t\tif (useCodeInterpreter) {\n\t\t\tnativeToolsParsed.push({\n\t\t\t\ttype: 'code_interpreter',\n\t\t\t});\n\t\t}\n\n\t\tconst useRetrieval = assistantTools.some((tool) => tool.type === 'file_search');\n\t\tif (useRetrieval) {\n\t\t\tnativeToolsParsed.push({\n\t\t\t\ttype: 'file_search',\n\t\t\t});\n\t\t}\n\n\t\tawait client.beta.assistants.update(assistantId, {\n\t\t\ttools: [...nativeToolsParsed, ...transformedConnectedTools],\n\t\t});\n\t}\n\n\tconst agentExecutor = AgentExecutor.fromAgentAndTools({\n\t\tagent,\n\t\ttools: tools ?? [],\n\t});\n\n\tconst useMemoryConnector =\n\t\tnodeVersion >= 1.6 && this.getNodeParameter('memory', i) === 'connector';\n\tconst memory =\n\t\tuseMemoryConnector || nodeVersion < 1.6\n\t\t\t? ((await this.getInputConnectionData(NodeConnectionTypes.AiMemory, 0)) as\n\t\t\t\t\t| BufferWindowMemory\n\t\t\t\t\t| undefined)\n\t\t\t: undefined;\n\n\tconst threadId =\n\t\tnodeVersion >= 1.6 && !useMemoryConnector\n\t\t\t? (this.getNodeParameter('threadId', i) as string)\n\t\t\t: undefined;\n\n\tconst chainValues: IDataObject = {\n\t\tcontent: input,\n\t\tsignal: this.getExecutionCancelSignal(),\n\t\ttimeout: options.timeout ?? 10000,\n\t};\n\tlet thread: OpenAIClient.Beta.Threads.Thread;\n\tif (memory) {\n\t\tconst chatMessages = await getChatMessages(memory);\n\n\t\t// Construct a new thread from the chat history to map the memory\n\t\tif (chatMessages.length) {\n\t\t\tconst first32Messages = chatMessages.slice(0, 32);\n\t\t\t// There is a undocumented limit of 32 messages per thread when creating a thread with messages\n\t\t\tconst mappedMessages: OpenAIClient.Beta.Threads.ThreadCreateParams.Message[] =\n\t\t\t\tfirst32Messages.map(mapChatMessageToThreadMessage);\n\n\t\t\tthread = await client.beta.threads.create({ messages: mappedMessages });\n\t\t\tconst overLimitMessages = chatMessages.slice(32).map(mapChatMessageToThreadMessage);\n\n\t\t\t// Send the remaining messages that exceed the limit of 32 sequentially\n\t\t\tfor (const message of overLimitMessages) {\n\t\t\t\tawait client.beta.threads.messages.create(thread.id, message);\n\t\t\t}\n\n\t\t\tchainValues.threadId = thread.id;\n\t\t}\n\t} else if (threadId) {\n\t\tchainValues.threadId = threadId;\n\t}\n\n\tlet filteredResponse: IDataObject = {};\n\ttry {\n\t\tconst response = await agentExecutor.withConfig(getTracingConfig(this)).invoke(chainValues);\n\t\tif (memory) {\n\t\t\tawait memory.saveContext({ input }, { output: response.output });\n\n\t\t\tif (response.threadId && response.runId) {\n\t\t\t\tconst threadRun = await client.beta.threads.runs.retrieve(response.runId, {\n\t\t\t\t\tthread_id: response.threadId,\n\t\t\t\t});\n\t\t\t\tresponse.usage = threadRun.usage;\n\t\t\t}\n\t\t}\n\n\t\tif (\n\t\t\toptions.preserveOriginalTools !== false &&\n\t\t\tnodeVersion >= 1.3 &&\n\t\t\t(assistantTools ?? [])?.length\n\t\t) {\n\t\t\tawait client.beta.assistants.update(assistantId, {\n\t\t\t\ttools: assistantTools,\n\t\t\t});\n\t\t}\n\t\t// Remove configuration properties and runId added by Langchain that are not relevant to the user\n\t\tfilteredResponse = omit(response, ['signal', 'timeout', 'content', 'runId']) as IDataObject;\n\t} catch (error) {\n\t\tif (!(error instanceof ApplicationError)) {\n\t\t\tthrow new NodeOperationError(this.getNode(), error.message, { itemIndex: i });\n\t\t}\n\t}\n\n\treturn [{ json: filteredResponse, pairedItem: { item: i } }];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAA8B;AAE9B,8BAAwC;AAExC,kBAAiB;AAOjB,0BAKO;AACP,oBAAuC;AAEvC,0BAA4C;AAC5C,qBAAwD;AACxD,qBAAiC;AAEjC,mBAA6D;AAC7D,IAAAA,uBAA6B;AAC7B,4BAA8B;AAE9B,MAAM,aAAgC;AAAA,EACrC;AAAA,EACA;AAAA,IACC,GAAG;AAAA,IACH,MAAM;AAAA,EACP;AAAA,EACA;AAAA,IACC,aAAa;AAAA,IACb,MAAM;AAAA,IACN,MAAM;AAAA,IACN,SAAS;AAAA,IACT,aAAa;AAAA,IACb,aAAa;AAAA,MACZ,MAAM;AAAA,IACP;AAAA,IACA,gBAAgB;AAAA,MACf,MAAM;AAAA,QACL,QAAQ,CAAC,QAAQ;AAAA,MAClB;AAAA,IACD;AAAA,EACD;AAAA,EACA;AAAA,IACC,aAAa;AAAA,IACb,MAAM;AAAA,IACN,MAAM;AAAA,IACN,SAAS;AAAA,MACR;AAAA,QACC,MAAM;AA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D;","names":["import_descriptions","OpenAIClient","omit"]}
1
+ {"version":3,"sources":["../../../../../../../nodes/vendors/OpenAi/v1/actions/assistant/message.operation.ts"],"sourcesContent":["import type { BaseMessage } from '@langchain/core/messages';\nimport { AgentExecutor } from '@langchain/classic/agents';\nimport type { OpenAIToolType } from '@langchain/classic/dist/experimental/openai_assistant/schema';\nimport { OpenAIAssistantRunnable } from '@langchain/classic/experimental/openai_assistant';\nimport type { BufferWindowMemory } from '@langchain/classic/memory';\nimport omit from 'lodash/omit';\nimport type {\n\tIDataObject,\n\tIExecuteFunctions,\n\tINodeExecutionData,\n\tINodeProperties,\n} from 'n8n-workflow';\nimport {\n\tApplicationError,\n\tNodeConnectionTypes,\n\tNodeOperationError,\n\tupdateDisplayOptions,\n} from 'n8n-workflow';\nimport { OpenAI as OpenAIClient } from 'openai';\n\nimport { promptTypeOptionsDeprecated } from '@utils/descriptions';\nimport { getConnectedTools, getPromptInputByType } from '@utils/helpers';\nimport { getTracingConfig } from '@utils/tracing';\n\nimport { formatToOpenAIAssistantTool, getChatMessages } from '../../../helpers/utils';\nimport { assistantRLC } from '../descriptions';\nimport { getProxyAgent } from '@utils/httpProxyAgent';\nimport { Container } from '@n8n/di';\nimport { AiConfig } from '@n8n/config';\n\nconst properties: INodeProperties[] = [\n\tassistantRLC,\n\t{\n\t\t...promptTypeOptionsDeprecated,\n\t\tname: 'prompt',\n\t},\n\t{\n\t\tdisplayName: 'Prompt (User Message)',\n\t\tname: 'text',\n\t\ttype: 'string',\n\t\tdefault: '',\n\t\tplaceholder: 'e.g. Hello, how can you help me?',\n\t\ttypeOptions: {\n\t\t\trows: 2,\n\t\t},\n\t\tdisplayOptions: {\n\t\t\tshow: {\n\t\t\t\tprompt: ['define'],\n\t\t\t},\n\t\t},\n\t},\n\t{\n\t\tdisplayName: 'Memory',\n\t\tname: 'memory',\n\t\ttype: 'options',\n\t\toptions: [\n\t\t\t{\n\t\t\t\tname: 'Use memory connector',\n\t\t\t\tvalue: 'connector',\n\t\t\t\tdescription: 'Connect one of the supported memory nodes',\n\t\t\t},\n\t\t\t{\n\t\t\t\t// eslint-disable-next-line n8n-nodes-base/node-param-display-name-miscased\n\t\t\t\tname: 'Use thread ID',\n\t\t\t\tvalue: 'threadId',\n\t\t\t\tdescription: 'Specify the ID of the thread to continue',\n\t\t\t},\n\t\t],\n\t\tdisplayOptions: {\n\t\t\tshow: {\n\t\t\t\t'@version': [{ _cnd: { gte: 1.6 } }],\n\t\t\t},\n\t\t},\n\t\tdefault: 'connector',\n\t},\n\t{\n\t\tdisplayName: 'Thread ID',\n\t\tname: 'threadId',\n\t\ttype: 'string',\n\t\tdefault: '',\n\t\tplaceholder: '',\n\t\tdescription: 'The ID of the thread to continue, a new thread will be created if not specified',\n\t\thint: 'If the thread ID is empty or undefined a new thread will be created and included in the response',\n\t\tdisplayOptions: {\n\t\t\tshow: {\n\t\t\t\t'@version': [{ _cnd: { gte: 1.6 } }],\n\t\t\t\tmemory: ['threadId'],\n\t\t\t},\n\t\t},\n\t},\n\t{\n\t\tdisplayName: 'Connect your own custom n8n tools to this node on the canvas',\n\t\tname: 'noticeTools',\n\t\ttype: 'notice',\n\t\tdefault: '',\n\t},\n\t{\n\t\tdisplayName: 'Options',\n\t\tname: 'options',\n\t\tplaceholder: 'Add Option',\n\t\tdescription: 'Additional options to add',\n\t\ttype: 'collection',\n\t\tdefault: {},\n\t\toptions: [\n\t\t\t{\n\t\t\t\tdisplayName: 'Base URL',\n\t\t\t\tname: 'baseURL',\n\t\t\t\tdefault: 'https://api.openai.com/v1',\n\t\t\t\tdescription: 'Override the default base URL for the API',\n\t\t\t\ttype: 'string',\n\t\t\t\tdisplayOptions: {\n\t\t\t\t\thide: {\n\t\t\t\t\t\t'@version': [{ _cnd: { gte: 1.8 } }],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tdisplayName: 'Max Retries',\n\t\t\t\tname: 'maxRetries',\n\t\t\t\tdefault: 2,\n\t\t\t\tdescription: 'Maximum number of retries to attempt',\n\t\t\t\ttype: 'number',\n\t\t\t},\n\t\t\t{\n\t\t\t\tdisplayName: 'Timeout',\n\t\t\t\tname: 'timeout',\n\t\t\t\tdefault: 10000,\n\t\t\t\tdescription: 'Maximum amount of time a request is allowed to take in milliseconds',\n\t\t\t\ttype: 'number',\n\t\t\t},\n\t\t\t{\n\t\t\t\tdisplayName: 'Preserve Original Tools',\n\t\t\t\tname: 'preserveOriginalTools',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: true,\n\t\t\t\tdescription:\n\t\t\t\t\t'Whether to preserve the original tools of the assistant after the execution of this node, otherwise the tools will be replaced with the connected tools, if any, default is true',\n\t\t\t\tdisplayOptions: {\n\t\t\t\t\tshow: {\n\t\t\t\t\t\t'@version': [{ _cnd: { gte: 1.3 } }],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t},\n];\n\nconst displayOptions = {\n\tshow: {\n\t\toperation: ['message'],\n\t\tresource: ['assistant'],\n\t},\n};\n\nexport const description = updateDisplayOptions(displayOptions, properties);\nconst mapChatMessageToThreadMessage = (\n\tmessage: BaseMessage,\n): OpenAIClient.Beta.Threads.ThreadCreateParams.Message => ({\n\trole: message._getType() === 'ai' ? 'assistant' : 'user',\n\tcontent: message.content.toString(),\n});\n\nexport async function execute(this: IExecuteFunctions, i: number): Promise<INodeExecutionData[]> {\n\tconst credentials = await this.getCredentials('openAiApi');\n\tconst nodeVersion = this.getNode().typeVersion;\n\n\tconst input = getPromptInputByType({\n\t\tctx: this,\n\t\ti,\n\t\tinputKey: 'text',\n\t\tpromptTypeKey: 'prompt',\n\t});\n\n\tconst assistantId = this.getNodeParameter('assistantId', i, '', { extractValue: true }) as string;\n\n\tconst options = this.getNodeParameter('options', i, {}) as {\n\t\tbaseURL?: string;\n\t\tmaxRetries: number;\n\t\ttimeout: number;\n\t\tpreserveOriginalTools?: boolean;\n\t};\n\n\tconst baseURL = (options.baseURL ?? credentials.url) as string;\n\tconst { openAiDefaultHeaders: defaultHeaders } = Container.get(AiConfig);\n\n\tconst client = new OpenAIClient({\n\t\tapiKey: credentials.apiKey as string,\n\t\tmaxRetries: options.maxRetries ?? 2,\n\t\ttimeout: options.timeout ?? 10000,\n\t\tbaseURL,\n\t\tfetchOptions: {\n\t\t\tdispatcher: getProxyAgent(baseURL),\n\t\t},\n\t\tdefaultHeaders,\n\t});\n\n\tconst agent = new OpenAIAssistantRunnable({ assistantId, client, asAgent: true });\n\n\tconst tools = await getConnectedTools(this, nodeVersion > 1, false);\n\tlet assistantTools;\n\n\tif (tools.length) {\n\t\tconst transformedConnectedTools = tools?.map(formatToOpenAIAssistantTool) ?? [];\n\t\tconst nativeToolsParsed: OpenAIToolType = [];\n\n\t\tassistantTools = (await client.beta.assistants.retrieve(assistantId)).tools;\n\n\t\tconst useCodeInterpreter = assistantTools.some((tool) => tool.type === 'code_interpreter');\n\t\tif (useCodeInterpreter) {\n\t\t\tnativeToolsParsed.push({\n\t\t\t\ttype: 'code_interpreter',\n\t\t\t});\n\t\t}\n\n\t\tconst useRetrieval = assistantTools.some((tool) => tool.type === 'file_search');\n\t\tif (useRetrieval) {\n\t\t\tnativeToolsParsed.push({\n\t\t\t\ttype: 'file_search',\n\t\t\t});\n\t\t}\n\n\t\tawait client.beta.assistants.update(assistantId, {\n\t\t\ttools: [...nativeToolsParsed, ...transformedConnectedTools],\n\t\t});\n\t}\n\n\tconst agentExecutor = AgentExecutor.fromAgentAndTools({\n\t\tagent,\n\t\ttools: tools ?? [],\n\t});\n\n\tconst useMemoryConnector =\n\t\tnodeVersion >= 1.6 && this.getNodeParameter('memory', i) === 'connector';\n\tconst memory =\n\t\tuseMemoryConnector || nodeVersion < 1.6\n\t\t\t? ((await this.getInputConnectionData(NodeConnectionTypes.AiMemory, 0)) as\n\t\t\t\t\t| BufferWindowMemory\n\t\t\t\t\t| undefined)\n\t\t\t: undefined;\n\n\tconst threadId =\n\t\tnodeVersion >= 1.6 && !useMemoryConnector\n\t\t\t? (this.getNodeParameter('threadId', i) as string)\n\t\t\t: undefined;\n\n\tconst chainValues: IDataObject = {\n\t\tcontent: input,\n\t\tsignal: this.getExecutionCancelSignal(),\n\t\ttimeout: options.timeout ?? 10000,\n\t};\n\tlet thread: OpenAIClient.Beta.Threads.Thread;\n\tif (memory) {\n\t\tconst chatMessages = await getChatMessages(memory);\n\n\t\t// Construct a new thread from the chat history to map the memory\n\t\tif (chatMessages.length) {\n\t\t\tconst first32Messages = chatMessages.slice(0, 32);\n\t\t\t// There is a undocumented limit of 32 messages per thread when creating a thread with messages\n\t\t\tconst mappedMessages: OpenAIClient.Beta.Threads.ThreadCreateParams.Message[] =\n\t\t\t\tfirst32Messages.map(mapChatMessageToThreadMessage);\n\n\t\t\tthread = await client.beta.threads.create({ messages: mappedMessages });\n\t\t\tconst overLimitMessages = chatMessages.slice(32).map(mapChatMessageToThreadMessage);\n\n\t\t\t// Send the remaining messages that exceed the limit of 32 sequentially\n\t\t\tfor (const message of overLimitMessages) {\n\t\t\t\tawait client.beta.threads.messages.create(thread.id, message);\n\t\t\t}\n\n\t\t\tchainValues.threadId = thread.id;\n\t\t}\n\t} else if (threadId) {\n\t\tchainValues.threadId = threadId;\n\t}\n\n\tlet filteredResponse: IDataObject = {};\n\ttry {\n\t\tconst response = await agentExecutor.withConfig(getTracingConfig(this)).invoke(chainValues);\n\t\tif (memory) {\n\t\t\tawait memory.saveContext({ input }, { output: response.output });\n\n\t\t\tif (response.threadId && response.runId) {\n\t\t\t\tconst threadRun = await client.beta.threads.runs.retrieve(response.runId, {\n\t\t\t\t\tthread_id: response.threadId,\n\t\t\t\t});\n\t\t\t\tresponse.usage = threadRun.usage;\n\t\t\t}\n\t\t}\n\n\t\tif (\n\t\t\toptions.preserveOriginalTools !== false &&\n\t\t\tnodeVersion >= 1.3 &&\n\t\t\t(assistantTools ?? [])?.length\n\t\t) {\n\t\t\tawait client.beta.assistants.update(assistantId, {\n\t\t\t\ttools: assistantTools,\n\t\t\t});\n\t\t}\n\t\t// Remove configuration properties and runId added by Langchain that are not relevant to the user\n\t\tfilteredResponse = omit(response, ['signal', 'timeout', 'content', 'runId']) as IDataObject;\n\t} catch (error) {\n\t\tif (!(error instanceof ApplicationError)) {\n\t\t\tthrow new NodeOperationError(this.getNode(), error.message, { itemIndex: i });\n\t\t}\n\t}\n\n\treturn [{ json: filteredResponse, pairedItem: { item: i } }];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAA8B;AAE9B,8BAAwC;AAExC,kBAAiB;AAOjB,0BAKO;AACP,oBAAuC;AAEvC,0BAA4C;AAC5C,qBAAwD;AACxD,qBAAiC;AAEjC,mBAA6D;AAC7D,IAAAA,uBAA6B;AAC7B,4BAA8B;AAC9B,gBAA0B;AAC1B,oBAAyB;AAEzB,MAAM,aAAgC;AAAA,EACrC;AAAA,EACA;AAAA,IACC,GAAG;AAAA,IACH,MAAM;AAAA,EACP;AAAA,EACA;AAAA,IACC,aAAa;AAAA,IACb,MAAM;AAAA,IACN,MAAM;AAAA,IACN,SAAS;AAAA,IACT,aAAa;AAAA,IACb,aAAa;AAAA,MACZ,MAAM;AAAA,IACP;AAAA,IACA,gBAAgB;AAAA,MACf,MAAM;AAAA,QACL,QAAQ,CAAC,QAAQ;AAAA,MAClB;AAAA,IACD;AAAA,EACD;AAAA,EACA;AAAA,IACC,aAAa;AAAA,IACb,MAAM;AAAA,IACN,MAAM;AAAA,IACN,SAAS;AAAA,MACR;AAAA,QACC,MAAM;AAAA,QACN,OAAO;AAAA,QACP,aAAa;AAAA,MACd;AAAA,MACA;AAAA;AAAA,QAEC,MAAM;AAAA,QACN,OAAO;AAAA,QACP,aAAa;AAAA,MACd;AAAA,IACD;AAAA,IACA,gBAAgB;AAAA,MACf,MAAM;AAAA,QACL,YAAY,CAAC,EAAE,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC;AAAA,MACpC;AAA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,WAAW,mBAAmB;AACxC,cAAM,OAAO,KAAK,QAAQ,SAAS,OAAO,OAAO,IAAI,OAAO;AAAA,MAC7D;AAEA,kBAAY,WAAW,OAAO;AAAA,IAC/B;AAAA,EACD,WAAW,UAAU;AACpB,gBAAY,WAAW;AAAA,EACxB;AAEA,MAAI,mBAAgC,CAAC;AACrC,MAAI;AACH,UAAM,WAAW,MAAM,cAAc,eAAW,iCAAiB,IAAI,CAAC,EAAE,OAAO,WAAW;AAC1F,QAAI,QAAQ;AACX,YAAM,OAAO,YAAY,EAAE,MAAM,GAAG,EAAE,QAAQ,SAAS,OAAO,CAAC;AAE/D,UAAI,SAAS,YAAY,SAAS,OAAO;AACxC,cAAM,YAAY,MAAM,OAAO,KAAK,QAAQ,KAAK,SAAS,SAAS,OAAO;AAAA,UACzE,WAAW,SAAS;AAAA,QACrB,CAAC;AACD,iBAAS,QAAQ,UAAU;AAAA,MAC5B;AAAA,IACD;AAEA,QACC,QAAQ,0BAA0B,SAClC,eAAe,QACd,kBAAkB,CAAC,IAAI,QACvB;AACD,YAAM,OAAO,KAAK,WAAW,OAAO,aAAa;AAAA,QAChD,OAAO;AAAA,MACR,CAAC;AAAA,IACF;AAEA,2BAAmB,YAAAC,SAAK,UAAU,CAAC,UAAU,WAAW,WAAW,OAAO,CAAC;AAAA,EAC5E,SAAS,OAAO;AACf,QAAI,EAAE,iBAAiB,uCAAmB;AACzC,YAAM,IAAI,uCAAmB,KAAK,QAAQ,GAAG,MAAM,SAAS,EAAE,WAAW,EAAE,CAAC;AAAA,IAC7E;AAAA,EACD;AAEA,SAAO,CAAC,EAAE,MAAM,kBAAkB,YAAY,EAAE,MAAM,EAAE,EAAE,CAAC;AAC5D;","names":["import_descriptions","OpenAIClient","omit"]}
@@ -12,7 +12,7 @@
12
12
  {"displayName":"OpenAI Assistant","name":"openAiAssistant","hidden":true,"icon":"fa:robot","group":["transform"],"version":[1,1.1],"description":"Utilizes Assistant API from Open AI.","subtitle":"Open AI Assistant","defaults":{"name":"OpenAI Assistant","color":"#404040"},"codex":{"alias":["LangChain"],"categories":["AI"],"subcategories":{"AI":["Agents","Root Nodes"]},"resources":{"primaryDocumentation":[{"url":"https://docs.n8n.io/integrations/builtin/cluster-nodes/root-nodes/n8n-nodes-langchain.openaiassistant/"}]}},"inputs":[{"type":"main"},{"type":"ai_tool","displayName":"Tools"}],"outputs":["main"],"credentials":[{"name":"openAiApi","required":true}],"requestDefaults":{"ignoreHttpStatusErrors":true,"baseURL":"={{ $parameter.options?.baseURL?.split(\"/\").slice(0,-1).join(\"/\") || \"https://api.openai.com\" }}"},"properties":[{"displayName":"Operation","name":"mode","type":"options","noDataExpression":true,"default":"existing","options":[{"name":"Use New Assistant","value":"new"},{"name":"Use Existing Assistant","value":"existing"}]},{"displayName":"Name","name":"name","type":"string","default":"","required":true,"displayOptions":{"show":{"/mode":["new"]}}},{"displayName":"Instructions","name":"instructions","type":"string","description":"How the Assistant and model should behave or respond","default":"","typeOptions":{"rows":5},"displayOptions":{"show":{"/mode":["new"]}}},{"displayName":"Model","name":"model","type":"options","description":"The model which will be used to power the assistant. <a href=\"https://beta.openai.com/docs/models/overview\">Learn more</a>. The Retrieval tool requires gpt-3.5-turbo-1106 and gpt-4-1106-preview models.","required":true,"displayOptions":{"show":{"/mode":["new"]}},"typeOptions":{"loadOptions":{"routing":{"request":{"method":"GET","url":"={{ $parameter.options?.baseURL?.split(\"/\").slice(-1).pop() || \"v1\" }}/models"},"output":{"postReceive":[{"type":"rootProperty","properties":{"property":"data"}},{"type":"filter","properties":{"pass":"={{ $responseItem.id.startsWith('gpt-') && !$responseItem.id.includes('instruct') }}"}},{"type":"setKeyValue","properties":{"name":"={{$responseItem.id}}","value":"={{$responseItem.id}}"}},{"type":"sort","properties":{"key":"name"}}]}}}},"routing":{"send":{"type":"body","property":"model"}},"default":"gpt-3.5-turbo-1106"},{"displayName":"Assistant","name":"assistantId","type":"options","noDataExpression":true,"displayOptions":{"show":{"/mode":["existing"]}},"description":"The assistant to use. <a href=\"https://beta.openai.com/docs/assistants/overview\">Learn more</a>.","typeOptions":{"loadOptions":{"routing":{"request":{"method":"GET","headers":{"OpenAI-Beta":"assistants=v1"},"url":"={{ $parameter.options?.baseURL?.split(\"/\").slice(-1).pop() || \"v1\" }}/assistants"},"output":{"postReceive":[{"type":"rootProperty","properties":{"property":"data"}},{"type":"setKeyValue","properties":{"name":"={{$responseItem.name}}","value":"={{$responseItem.id}}","description":"={{$responseItem.model}}"}},{"type":"sort","properties":{"key":"name"}}]}}}},"routing":{"send":{"type":"body","property":"assistant"}},"required":true,"default":""},{"displayName":"Text","name":"text","type":"string","required":true,"default":"={{ $json.chat_input }}","displayOptions":{"show":{"@version":[1]}}},{"displayName":"Text","name":"text","type":"string","required":true,"default":"={{ $json.chatInput }}","displayOptions":{"show":{"@version":[1.1]}}},{"displayName":"OpenAI Tools","name":"nativeTools","type":"multiOptions","default":[],"options":[{"name":"Code Interpreter","value":"code_interpreter"},{"name":"Knowledge Retrieval","value":"retrieval"}]},{"displayName":"Connect your own custom tools to this node on the canvas","name":"noticeTools","type":"notice","default":""},{"displayName":"Upload files for retrieval using the <a href=\"https://platform.openai.com/playground\" target=\"_blank\">OpenAI website<a/>","name":"noticeTools","type":"notice","typeOptions":{"noticeTheme":"info"},"displayOptions":{"show":{"/nativeTools":["retrieval"]}},"default":""},{"displayName":"Options","name":"options","placeholder":"Add Option","description":"Additional options to add","type":"collection","default":{},"options":[{"displayName":"Base URL","name":"baseURL","default":"https://api.openai.com/v1","description":"Override the default base URL for the API","type":"string"},{"displayName":"Max Retries","name":"maxRetries","default":2,"description":"Maximum number of retries to attempt","type":"number"},{"displayName":"Timeout","name":"timeout","default":10000,"description":"Maximum amount of time a request is allowed to take in milliseconds","type":"number"}]}]},
13
13
  {"displayName":"Summarization Chain","name":"chainSummarization","icon":"fa:link","iconColor":"black","group":["transform"],"description":"Transforms text into a concise summary","codex":{"alias":["LangChain"],"categories":["AI"],"subcategories":{"AI":["Chains","Root Nodes"]},"resources":{"primaryDocumentation":[{"url":"https://docs.n8n.io/integrations/builtin/cluster-nodes/root-nodes/n8n-nodes-langchain.chainsummarization/"}]}},"defaultVersion":2.1,"version":[2,2.1],"defaults":{"name":"Summarization Chain","color":"#909298"},"inputs":"={{ ((parameter) => { function getInputs(parameters) {\n const chunkingMode = parameters?.chunkingMode;\n const operationMode = parameters?.operationMode;\n const inputs = [\n { displayName: \"\", type: \"main\" },\n {\n displayName: \"Model\",\n maxConnections: 1,\n type: \"ai_languageModel\",\n required: true\n }\n ];\n if (operationMode === \"documentLoader\") {\n inputs.push({\n displayName: \"Document\",\n type: \"ai_document\",\n required: true,\n maxConnections: 1\n });\n return inputs;\n }\n if (chunkingMode === \"advanced\") {\n inputs.push({\n displayName: \"Text Splitter\",\n type: \"ai_textSplitter\",\n required: false,\n maxConnections: 1\n });\n return inputs;\n }\n return inputs;\n}; return getInputs(parameter) })($parameter) }}","outputs":["main"],"credentials":[],"properties":[{"displayName":"Save time with an <a href=\"/templates/1951\" target=\"_blank\">example</a> of how this node works","name":"notice","type":"notice","default":""},{"displayName":"Data to Summarize","name":"operationMode","noDataExpression":true,"type":"options","description":"How to pass data into the summarization chain","default":"nodeInputJson","options":[{"name":"Use Node Input (JSON)","value":"nodeInputJson","description":"Summarize the JSON data coming into this node from the previous one"},{"name":"Use Node Input (Binary)","value":"nodeInputBinary","description":"Summarize the binary data coming into this node from the previous one"},{"name":"Use Document Loader","value":"documentLoader","description":"Use a loader sub-node with more configuration options"}]},{"displayName":"Chunking Strategy","name":"chunkingMode","noDataExpression":true,"type":"options","description":"Chunk splitting strategy","default":"simple","options":[{"name":"Simple (Define Below)","value":"simple"},{"name":"Advanced","value":"advanced","description":"Use a splitter sub-node with more configuration options"}],"displayOptions":{"show":{"/operationMode":["nodeInputJson","nodeInputBinary"]}}},{"displayName":"Characters Per Chunk","name":"chunkSize","description":"Controls the max size (in terms of number of characters) of the final document chunk","type":"number","default":1000,"displayOptions":{"show":{"/chunkingMode":["simple"]}}},{"displayName":"Chunk Overlap (Characters)","name":"chunkOverlap","type":"number","description":"Specifies how much characters overlap there should be between chunks","default":200,"displayOptions":{"show":{"/chunkingMode":["simple"]}}},{"displayName":"Options","name":"options","type":"collection","default":{},"placeholder":"Add Option","options":[{"displayName":"Input Data Field Name","name":"binaryDataKey","type":"string","default":"data","description":"The name of the field in the agent or chain’s input that contains the binary file to be processed","displayOptions":{"show":{"/operationMode":["nodeInputBinary"]}}},{"displayName":"Summarization Method and Prompts","name":"summarizationMethodAndPrompts","type":"fixedCollection","default":{"values":{"summarizationMethod":"map_reduce","prompt":"Write a concise summary of the following:\n\n\n\"{text}\"\n\n\nCONCISE SUMMARY:","combineMapPrompt":"Write a concise summary of the following:\n\n\n\"{text}\"\n\n\nCONCISE SUMMARY:"}},"placeholder":"Add Option","typeOptions":{},"options":[{"name":"values","displayName":"Values","values":[{"displayName":"Summarization Method","name":"summarizationMethod","type":"options","description":"The type of summarization to run","default":"map_reduce","options":[{"name":"Map Reduce (Recommended)","value":"map_reduce","description":"Summarize each document (or chunk) individually, then summarize those summaries"},{"name":"Refine","value":"refine","description":"Summarize the first document (or chunk). Then update that summary based on the next document (or chunk), and repeat."},{"name":"Stuff","value":"stuff","description":"Pass all documents (or chunks) at once. Ideal for small datasets."}]},{"displayName":"Individual Summary Prompt","name":"combineMapPrompt","type":"string","hint":"The prompt to summarize an individual document (or chunk)","displayOptions":{"hide":{"/options.summarizationMethodAndPrompts.values.summarizationMethod":["stuff","refine"]}},"default":"Write a concise summary of the following:\n\n\n\"{text}\"\n\n\nCONCISE SUMMARY:","typeOptions":{"rows":9}},{"displayName":"Final Prompt to Combine","name":"prompt","type":"string","default":"Write a concise summary of the following:\n\n\n\"{text}\"\n\n\nCONCISE SUMMARY:","hint":"The prompt to combine individual summaries","displayOptions":{"hide":{"/options.summarizationMethodAndPrompts.values.summarizationMethod":["stuff","refine"]}},"typeOptions":{"rows":9}},{"displayName":"Prompt","name":"prompt","type":"string","default":"Write a concise summary of the following:\n\n\n\"{text}\"\n\n\nCONCISE SUMMARY:","displayOptions":{"hide":{"/options.summarizationMethodAndPrompts.values.summarizationMethod":["refine","map_reduce"]}},"typeOptions":{"rows":9}},{"displayName":"Subsequent (Refine) Prompt","name":"refinePrompt","type":"string","displayOptions":{"hide":{"/options.summarizationMethodAndPrompts.values.summarizationMethod":["stuff","map_reduce"]}},"default":"Your job is to produce a final summary\nWe have provided an existing summary up to a certain point: \"{existing_answer}\"\nWe have the opportunity to refine the existing summary\n(only if needed) with some more context below.\n------------\n\"{text}\"\n------------\n\nGiven the new context, refine the original summary\nIf the context isn't useful, return the original summary.\n\nREFINED SUMMARY:","hint":"The prompt to refine the summary based on the next document (or chunk)","typeOptions":{"rows":9}},{"displayName":"Initial Prompt","name":"refineQuestionPrompt","type":"string","displayOptions":{"hide":{"/options.summarizationMethodAndPrompts.values.summarizationMethod":["stuff","map_reduce"]}},"default":"Write a concise summary of the following:\n\n\n\"{text}\"\n\n\nCONCISE SUMMARY:","hint":"The prompt for the first document (or chunk)","typeOptions":{"rows":9}}]}]},{"displayName":"Batch Processing","name":"batching","type":"collection","placeholder":"Add Batch Processing Option","description":"Batch processing options for rate limiting","default":{},"options":[{"displayName":"Batch Size","name":"batchSize","default":5,"type":"number","description":"How many items to process in parallel. This is useful for rate limiting, but might impact the log output ordering."},{"displayName":"Delay Between Batches","name":"delayBetweenBatches","default":0,"type":"number","description":"Delay in milliseconds between batches. This is useful for rate limiting."}],"displayOptions":{"show":{"@version":[{"_cnd":{"gte":2.1}}]}}}]}]},
14
14
  {"displayName":"Summarization Chain","name":"chainSummarization","icon":"fa:link","iconColor":"black","group":["transform"],"description":"Transforms text into a concise summary","codex":{"alias":["LangChain"],"categories":["AI"],"subcategories":{"AI":["Chains","Root Nodes"]},"resources":{"primaryDocumentation":[{"url":"https://docs.n8n.io/integrations/builtin/cluster-nodes/root-nodes/n8n-nodes-langchain.chainsummarization/"}]}},"defaultVersion":2.1,"version":1,"defaults":{"name":"Summarization Chain","color":"#909298"},"inputs":["main",{"displayName":"Model","maxConnections":1,"type":"ai_languageModel","required":true},{"displayName":"Document","maxConnections":1,"type":"ai_document","required":true}],"outputs":["main"],"credentials":[],"properties":[{"displayName":"Save time with an <a href=\"/templates/1951\" target=\"_blank\">example</a> of how this node works","name":"notice","type":"notice","default":""},{"displayName":"Type","name":"type","type":"options","description":"The type of summarization to run","default":"map_reduce","options":[{"name":"Map Reduce (Recommended)","value":"map_reduce","description":"Summarize each document (or chunk) individually, then summarize those summaries"},{"name":"Refine","value":"refine","description":"Summarize the first document (or chunk). Then update that summary based on the next document (or chunk), and repeat."},{"name":"Stuff","value":"stuff","description":"Pass all documents (or chunks) at once. Ideal for small datasets."}]},{"displayName":"Options","name":"options","type":"collection","default":{},"placeholder":"Add Option","options":[{"displayName":"Final Prompt to Combine","name":"combineMapPrompt","type":"string","hint":"The prompt to combine individual summaries","displayOptions":{"show":{"/type":["map_reduce"]}},"default":"Write a concise summary of the following:\n\n\n\"{text}\"\n\n\nCONCISE SUMMARY:","typeOptions":{"rows":6}},{"displayName":"Individual Summary Prompt","name":"prompt","type":"string","default":"Write a concise summary of the following:\n\n\n\"{text}\"\n\n\nCONCISE SUMMARY:","hint":"The prompt to summarize an individual document (or chunk)","displayOptions":{"show":{"/type":["map_reduce"]}},"typeOptions":{"rows":6}},{"displayName":"Prompt","name":"prompt","type":"string","default":"Write a concise summary of the following:\n\n\n\"{text}\"\n\n\nCONCISE SUMMARY:","displayOptions":{"show":{"/type":["stuff"]}},"typeOptions":{"rows":6}},{"displayName":"Subsequent (Refine) Prompt","name":"refinePrompt","type":"string","displayOptions":{"show":{"/type":["refine"]}},"default":"Your job is to produce a final summary\nWe have provided an existing summary up to a certain point: \"{existing_answer}\"\nWe have the opportunity to refine the existing summary\n(only if needed) with some more context below.\n------------\n\"{text}\"\n------------\n\nGiven the new context, refine the original summary\nIf the context isn't useful, return the original summary.\n\nREFINED SUMMARY:","hint":"The prompt to refine the summary based on the next document (or chunk)","typeOptions":{"rows":6}},{"displayName":"Initial Prompt","name":"refineQuestionPrompt","type":"string","displayOptions":{"show":{"/type":["refine"]}},"default":"Write a concise summary of the following:\n\n\n\"{text}\"\n\n\nCONCISE SUMMARY:","hint":"The prompt for the first document (or chunk)","typeOptions":{"rows":6}}]}]},
15
- {"displayName":"Basic LLM Chain","name":"chainLlm","icon":"fa:link","iconColor":"black","group":["transform"],"version":[1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8],"description":"A simple chain to prompt a large language model","defaults":{"name":"Basic LLM Chain","color":"#909298"},"codex":{"alias":["LangChain"],"categories":["AI"],"subcategories":{"AI":["Chains","Root Nodes"]},"resources":{"primaryDocumentation":[{"url":"https://docs.n8n.io/integrations/builtin/cluster-nodes/root-nodes/n8n-nodes-langchain.chainllm/"}]}},"inputs":"={{ ((parameter) => { function getInputs(parameters) {\n const inputs = [\n { displayName: \"\", type: \"main\" },\n {\n displayName: \"Model\",\n maxConnections: 1,\n type: \"ai_languageModel\",\n required: true\n }\n ];\n const needsFallback = parameters?.needsFallback;\n if (needsFallback === true) {\n inputs.push({\n displayName: \"Fallback Model\",\n maxConnections: 1,\n type: \"ai_languageModel\",\n required: true\n });\n }\n const hasOutputParser = parameters?.hasOutputParser;\n if (hasOutputParser === void 0 || hasOutputParser === true) {\n inputs.push({\n displayName: \"Output Parser\",\n type: \"ai_outputParser\",\n maxConnections: 1,\n required: false\n });\n }\n return inputs;\n}; return getInputs(parameter) })($parameter) }}","outputs":["main"],"credentials":[],"properties":[{"displayName":"Save time with an <a href=\"/templates/1978\" target=\"_blank\">example</a> of how this node works","name":"notice","type":"notice","default":""},{"displayName":"Prompt","name":"prompt","type":"string","required":true,"default":"={{ $json.input }}","displayOptions":{"show":{"@version":[1]}}},{"displayName":"Prompt","name":"prompt","type":"string","required":true,"default":"={{ $json.chat_input }}","displayOptions":{"show":{"@version":[1.1,1.2]}}},{"displayName":"Prompt","name":"prompt","type":"string","required":true,"default":"={{ $json.chatInput }}","displayOptions":{"show":{"@version":[1.3]}}},{"displayName":"Source for Prompt (User Message)","name":"promptType","type":"options","options":[{"name":"Connected Chat Trigger Node","value":"auto","description":"Looks for an input field called 'chatInput' that is coming from a directly connected Chat Trigger"},{"name":"Connected Guardrails Node","value":"guardrails","description":"Looks for an input field called 'guardrailsInput' that is coming from a directly connected Guardrails Node"},{"name":"Define below","value":"define","description":"Use an expression to reference data in previous nodes or enter static text"}],"default":"auto","displayOptions":{"hide":{"@version":[{"_cnd":{"lte":1.3}},{"_cnd":{"gte":1.8}}]}}},{"displayName":"Source for Prompt (User Message)","name":"promptType","type":"options","options":[{"name":"Connected Chat Trigger Node","value":"auto","description":"Looks for an input field called 'chatInput' that is coming from a directly connected Chat Trigger"},{"name":"Define below","value":"define","description":"Use an expression to reference data in previous nodes or enter static text"}],"default":"auto","displayOptions":{"show":{"@version":[{"_cnd":{"gte":1.8}}]}}},{"displayName":"Prompt (User Message)","name":"text","type":"string","required":true,"default":"={{ $json.guardrailsInput }}","typeOptions":{"rows":2},"disabledOptions":{"show":{"promptType":["guardrails"]}},"displayOptions":{"show":{"promptType":["guardrails"],"@version":[{"_cnd":{"gte":1.5}}]}}},{"displayName":"Prompt (User Message)","name":"text","type":"string","required":true,"default":"={{ $json.chatInput }}","typeOptions":{"rows":2},"disabledOptions":{"show":{"promptType":["auto"]}},"displayOptions":{"show":{"promptType":["auto"],"@version":[{"_cnd":{"gte":1.5}}]}}},{"displayName":"Prompt (User Message)","name":"text","type":"string","required":true,"default":"","placeholder":"e.g. Hello, how can you help me?","typeOptions":{"rows":2},"displayOptions":{"show":{"promptType":["define"]}}},{"displayName":"Require Specific Output Format","name":"hasOutputParser","type":"boolean","default":false,"noDataExpression":true,"displayOptions":{"hide":{"@version":[1,1.1,1.3]}}},{"displayName":"Enable Fallback Model","name":"needsFallback","type":"boolean","default":false,"noDataExpression":true,"displayOptions":{"hide":{"@version":[1,1.1,1.3]}}},{"displayName":"Chat Messages (if Using a Chat Model)","name":"messages","type":"fixedCollection","typeOptions":{"multipleValues":true},"default":{},"placeholder":"Add prompt","options":[{"name":"messageValues","displayName":"Prompt","values":[{"displayName":"Type Name or ID","name":"type","type":"options","options":[{"name":"AI","value":"AIMessagePromptTemplate"},{"name":"System","value":"SystemMessagePromptTemplate"},{"name":"User","value":"HumanMessagePromptTemplate"}],"default":"SystemMessagePromptTemplate"},{"displayName":"Message Type","name":"messageType","type":"options","displayOptions":{"show":{"type":["HumanMessagePromptTemplate"]}},"options":[{"name":"Text","value":"text","description":"Simple text message"},{"name":"Image (Binary)","value":"imageBinary","description":"Process the binary input from the previous node"},{"name":"Image (URL)","value":"imageUrl","description":"Process the image from the specified URL"}],"default":"text"},{"displayName":"Image Data Field Name","name":"binaryImageDataKey","type":"string","default":"data","required":true,"description":"The name of the field in the chain's input that contains the binary image file to be processed","displayOptions":{"show":{"messageType":["imageBinary"]}}},{"displayName":"Image URL","name":"imageUrl","type":"string","default":"","required":true,"description":"URL to the image to be processed","displayOptions":{"show":{"messageType":["imageUrl"]}}},{"displayName":"Image Details","description":"Control how the model processes the image and generates its textual understanding","name":"imageDetail","type":"options","displayOptions":{"show":{"type":["HumanMessagePromptTemplate"],"messageType":["imageBinary","imageUrl"]}},"options":[{"name":"Auto","value":"auto","description":"Model will use the auto setting which will look at the image input size and decide if it should use the low or high setting"},{"name":"Low","value":"low","description":"The model will receive a low-res 512px x 512px version of the image, and represent the image with a budget of 65 tokens. This allows the API to return faster responses and consume fewer input tokens for use cases that do not require high detail."},{"name":"High","value":"high","description":"Allows the model to see the low res image and then creates detailed crops of input images as 512px squares based on the input image size. Each of the detailed crops uses twice the token budget (65 tokens) for a total of 129 tokens."}],"default":"auto"},{"displayName":"Message","name":"message","type":"string","required":true,"displayOptions":{"hide":{"messageType":["imageBinary","imageUrl"]}},"default":""}]}]},{"displayName":"Batch Processing","name":"batching","type":"collection","placeholder":"Add Batch Processing Option","description":"Batch processing options for rate limiting","default":{},"options":[{"displayName":"Batch Size","name":"batchSize","default":5,"type":"number","description":"How many items to process in parallel. This is useful for rate limiting, but might impact the log output ordering."},{"displayName":"Delay Between Batches","name":"delayBetweenBatches","default":0,"type":"number","description":"Delay in milliseconds between batches. This is useful for rate limiting."}],"displayOptions":{"show":{"@version":[{"_cnd":{"gte":1.7}}]}}},{"displayName":"Connect an <a data-action='openSelectiveNodeCreator' data-action-parameter-connectiontype='ai_outputParser'>output parser</a> on the canvas to specify the output format you require","name":"notice","type":"notice","default":"","displayOptions":{"show":{"hasOutputParser":[true]}}},{"displayName":"Connect an additional language model on the canvas to use it as a fallback if the main model fails","name":"fallbackNotice","type":"notice","default":"","displayOptions":{"show":{"needsFallback":[true]}}}]},
15
+ {"displayName":"Basic LLM Chain","name":"chainLlm","icon":"fa:link","iconColor":"black","group":["transform"],"version":[1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9],"description":"A simple chain to prompt a large language model","defaults":{"name":"Basic LLM Chain","color":"#909298"},"codex":{"alias":["LangChain"],"categories":["AI"],"subcategories":{"AI":["Chains","Root Nodes"]},"resources":{"primaryDocumentation":[{"url":"https://docs.n8n.io/integrations/builtin/cluster-nodes/root-nodes/n8n-nodes-langchain.chainllm/"}]}},"inputs":"={{ ((parameter) => { function getInputs(parameters) {\n const inputs = [\n { displayName: \"\", type: \"main\" },\n {\n displayName: \"Model\",\n maxConnections: 1,\n type: \"ai_languageModel\",\n required: true\n }\n ];\n const needsFallback = parameters?.needsFallback;\n if (needsFallback === true) {\n inputs.push({\n displayName: \"Fallback Model\",\n maxConnections: 1,\n type: \"ai_languageModel\",\n required: true\n });\n }\n const hasOutputParser = parameters?.hasOutputParser;\n if (hasOutputParser === void 0 || hasOutputParser === true) {\n inputs.push({\n displayName: \"Output Parser\",\n type: \"ai_outputParser\",\n maxConnections: 1,\n required: false\n });\n }\n return inputs;\n}; return getInputs(parameter) })($parameter) }}","outputs":["main"],"credentials":[],"properties":[{"displayName":"Save time with an <a href=\"/templates/1978\" target=\"_blank\">example</a> of how this node works","name":"notice","type":"notice","default":""},{"displayName":"Prompt","name":"prompt","type":"string","required":true,"default":"={{ $json.input }}","displayOptions":{"show":{"@version":[1]}}},{"displayName":"Prompt","name":"prompt","type":"string","required":true,"default":"={{ $json.chat_input }}","displayOptions":{"show":{"@version":[1.1,1.2]}}},{"displayName":"Prompt","name":"prompt","type":"string","required":true,"default":"={{ $json.chatInput }}","displayOptions":{"show":{"@version":[1.3]}}},{"displayName":"Source for Prompt (User Message)","name":"promptType","type":"options","options":[{"name":"Connected Chat Trigger Node","value":"auto","description":"Looks for an input field called 'chatInput' that is coming from a directly connected Chat Trigger"},{"name":"Connected Guardrails Node","value":"guardrails","description":"Looks for an input field called 'guardrailsInput' that is coming from a directly connected Guardrails Node"},{"name":"Define below","value":"define","description":"Use an expression to reference data in previous nodes or enter static text"}],"default":"auto","displayOptions":{"hide":{"@version":[{"_cnd":{"lte":1.3}},{"_cnd":{"gte":1.8}}]}}},{"displayName":"Source for Prompt (User Message)","name":"promptType","type":"options","options":[{"name":"Connected Chat Trigger Node","value":"auto","description":"Looks for an input field called 'chatInput' that is coming from a directly connected Chat Trigger"},{"name":"Define below","value":"define","description":"Use an expression to reference data in previous nodes or enter static text"}],"default":"auto","displayOptions":{"show":{"@version":[{"_cnd":{"gte":1.8}}]}}},{"displayName":"Prompt (User Message)","name":"text","type":"string","required":true,"default":"={{ $json.guardrailsInput }}","typeOptions":{"rows":2},"disabledOptions":{"show":{"promptType":["guardrails"]}},"displayOptions":{"show":{"promptType":["guardrails"],"@version":[{"_cnd":{"gte":1.5}}]}}},{"displayName":"Prompt (User Message)","name":"text","type":"string","required":true,"default":"={{ $json.chatInput }}","typeOptions":{"rows":2},"disabledOptions":{"show":{"promptType":["auto"]}},"displayOptions":{"show":{"promptType":["auto"],"@version":[{"_cnd":{"gte":1.5}}]}}},{"displayName":"Prompt (User Message)","name":"text","type":"string","required":true,"default":"","placeholder":"e.g. Hello, how can you help me?","typeOptions":{"rows":2},"displayOptions":{"show":{"promptType":["define"]}}},{"displayName":"Require Specific Output Format","name":"hasOutputParser","type":"boolean","default":false,"noDataExpression":true,"displayOptions":{"hide":{"@version":[1,1.1,1.3]}}},{"displayName":"Enable Fallback Model","name":"needsFallback","type":"boolean","default":false,"noDataExpression":true,"displayOptions":{"hide":{"@version":[1,1.1,1.3]}}},{"displayName":"Chat Messages (if Using a Chat Model)","name":"messages","type":"fixedCollection","typeOptions":{"multipleValues":true},"default":{},"placeholder":"Add prompt","options":[{"name":"messageValues","displayName":"Prompt","values":[{"displayName":"Type Name or ID","name":"type","type":"options","options":[{"name":"AI","value":"AIMessagePromptTemplate"},{"name":"System","value":"SystemMessagePromptTemplate"},{"name":"User","value":"HumanMessagePromptTemplate"}],"default":"SystemMessagePromptTemplate"},{"displayName":"Message Type","name":"messageType","type":"options","displayOptions":{"show":{"type":["HumanMessagePromptTemplate"]}},"options":[{"name":"Text","value":"text","description":"Simple text message"},{"name":"Image (Binary)","value":"imageBinary","description":"Process the binary input from the previous node"},{"name":"Image (URL)","value":"imageUrl","description":"Process the image from the specified URL"}],"default":"text"},{"displayName":"Image Data Field Name","name":"binaryImageDataKey","type":"string","default":"data","required":true,"description":"The name of the field in the chain's input that contains the binary image file to be processed","displayOptions":{"show":{"messageType":["imageBinary"]}}},{"displayName":"Image URL","name":"imageUrl","type":"string","default":"","required":true,"description":"URL to the image to be processed","displayOptions":{"show":{"messageType":["imageUrl"]}}},{"displayName":"Image Details","description":"Control how the model processes the image and generates its textual understanding","name":"imageDetail","type":"options","displayOptions":{"show":{"type":["HumanMessagePromptTemplate"],"messageType":["imageBinary","imageUrl"]}},"options":[{"name":"Auto","value":"auto","description":"Model will use the auto setting which will look at the image input size and decide if it should use the low or high setting"},{"name":"Low","value":"low","description":"The model will receive a low-res 512px x 512px version of the image, and represent the image with a budget of 65 tokens. This allows the API to return faster responses and consume fewer input tokens for use cases that do not require high detail."},{"name":"High","value":"high","description":"Allows the model to see the low res image and then creates detailed crops of input images as 512px squares based on the input image size. Each of the detailed crops uses twice the token budget (65 tokens) for a total of 129 tokens."}],"default":"auto"},{"displayName":"Message","name":"message","type":"string","required":true,"displayOptions":{"hide":{"messageType":["imageBinary","imageUrl"]}},"default":""}]}]},{"displayName":"Batch Processing","name":"batching","type":"collection","placeholder":"Add Batch Processing Option","description":"Batch processing options for rate limiting","default":{},"options":[{"displayName":"Batch Size","name":"batchSize","default":5,"type":"number","description":"How many items to process in parallel. This is useful for rate limiting, but might impact the log output ordering."},{"displayName":"Delay Between Batches","name":"delayBetweenBatches","default":0,"type":"number","description":"Delay in milliseconds between batches. This is useful for rate limiting."}],"displayOptions":{"show":{"@version":[{"_cnd":{"gte":1.7}}]}}},{"displayName":"Connect an <a data-action='openSelectiveNodeCreator' data-action-parameter-connectiontype='ai_outputParser'>output parser</a> on the canvas to specify the output format you require","name":"notice","type":"notice","default":"","displayOptions":{"show":{"hasOutputParser":[true]}}},{"displayName":"Connect an additional language model on the canvas to use it as a fallback if the main model fails","name":"fallbackNotice","type":"notice","default":"","displayOptions":{"show":{"needsFallback":[true]}}}]},
16
16
  {"displayName":"Question and Answer Chain","name":"chainRetrievalQa","icon":"fa:link","iconColor":"black","group":["transform"],"version":[1,1.1,1.2,1.3,1.4,1.5,1.6,1.7],"description":"Answer questions about retrieved documents","defaults":{"name":"Question and Answer Chain","color":"#909298"},"codex":{"alias":["LangChain"],"categories":["AI"],"subcategories":{"AI":["Chains","Root Nodes"]},"resources":{"primaryDocumentation":[{"url":"https://docs.n8n.io/integrations/builtin/cluster-nodes/root-nodes/n8n-nodes-langchain.chainretrievalqa/"}]}},"inputs":["main",{"displayName":"Model","maxConnections":1,"type":"ai_languageModel","required":true},{"displayName":"Retriever","maxConnections":1,"type":"ai_retriever","required":true}],"outputs":["main"],"credentials":[],"properties":[{"displayName":"Save time with an <a href=\"/templates/1960\" target=\"_blank\">example</a> of how this node works","name":"notice","type":"notice","default":""},{"displayName":"Query","name":"query","type":"string","required":true,"default":"={{ $json.input }}","displayOptions":{"show":{"@version":[1]}}},{"displayName":"Query","name":"query","type":"string","required":true,"default":"={{ $json.chat_input }}","displayOptions":{"show":{"@version":[1.1]}}},{"displayName":"Query","name":"query","type":"string","required":true,"default":"={{ $json.chatInput }}","displayOptions":{"show":{"@version":[1.2]}}},{"displayName":"Source for Prompt (User Message)","name":"promptType","type":"options","options":[{"name":"Connected Chat Trigger Node","value":"auto","description":"Looks for an input field called 'chatInput' that is coming from a directly connected Chat Trigger"},{"name":"Connected Guardrails Node","value":"guardrails","description":"Looks for an input field called 'guardrailsInput' that is coming from a directly connected Guardrails Node"},{"name":"Define below","value":"define","description":"Use an expression to reference data in previous nodes or enter static text"}],"default":"auto","displayOptions":{"hide":{"@version":[{"_cnd":{"lte":1.2}},{"_cnd":{"gte":1.7}}]}}},{"displayName":"Source for Prompt (User Message)","name":"promptType","type":"options","options":[{"name":"Connected Chat Trigger Node","value":"auto","description":"Looks for an input field called 'chatInput' that is coming from a directly connected Chat Trigger"},{"name":"Define below","value":"define","description":"Use an expression to reference data in previous nodes or enter static text"}],"default":"auto","displayOptions":{"show":{"@version":[{"_cnd":{"gte":1.7}}]}}},{"displayName":"Prompt (User Message)","name":"text","type":"string","required":true,"default":"={{ $json.guardrailsInput }}","typeOptions":{"rows":2},"disabledOptions":{"show":{"promptType":["guardrails"]}},"displayOptions":{"show":{"promptType":["guardrails"],"@version":[{"_cnd":{"gte":1.4}}]}}},{"displayName":"Prompt (User Message)","name":"text","type":"string","required":true,"default":"={{ $json.chatInput }}","typeOptions":{"rows":2},"disabledOptions":{"show":{"promptType":["auto"]}},"displayOptions":{"show":{"promptType":["auto"],"@version":[{"_cnd":{"gte":1.4}}]}}},{"displayName":"Prompt (User Message)","name":"text","type":"string","required":true,"default":"","placeholder":"e.g. Hello, how can you help me?","typeOptions":{"rows":2},"displayOptions":{"show":{"promptType":["define"]}}},{"displayName":"Options","name":"options","type":"collection","default":{},"placeholder":"Add Option","options":[{"displayName":"System Prompt Template","name":"systemPromptTemplate","type":"string","default":"You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question.\nIf you don't know the answer, just say that you don't know, don't try to make up an answer.\n----------------\nContext: {context}","typeOptions":{"rows":6},"description":"Template string used for the system prompt. This should include the variable `{context}` for the provided context. For text completion models, you should also include the variable `{question}` for the user’s query.","displayOptions":{"show":{"@version":[{"_cnd":{"lt":1.5}}]}}},{"displayName":"System Prompt Template","name":"systemPromptTemplate","type":"string","default":"You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question.\nIf you don't know the answer, just say that you don't know, don't try to make up an answer.\n----------------\nContext: {context}","typeOptions":{"rows":6},"description":"Template string used for the system prompt. This should include the variable `{context}` for the provided context. For text completion models, you should also include the variable `{input}` for the user’s query.","displayOptions":{"show":{"@version":[{"_cnd":{"gte":1.5}}]}}},{"displayName":"Batch Processing","name":"batching","type":"collection","placeholder":"Add Batch Processing Option","description":"Batch processing options for rate limiting","default":{},"options":[{"displayName":"Batch Size","name":"batchSize","default":5,"type":"number","description":"How many items to process in parallel. This is useful for rate limiting, but might impact the log output ordering."},{"displayName":"Delay Between Batches","name":"delayBetweenBatches","default":0,"type":"number","description":"Delay in milliseconds between batches. This is useful for rate limiting."}],"displayOptions":{"show":{"@version":[{"_cnd":{"gte":1.6}}]}}}]}]},
17
17
  {"displayName":"Sentiment Analysis","name":"sentimentAnalysis","icon":"fa:balance-scale-left","iconColor":"black","group":["transform"],"version":[1,1.1],"description":"Analyze the sentiment of your text","codex":{"categories":["AI"],"subcategories":{"AI":["Chains","Root Nodes"]},"resources":{"primaryDocumentation":[{"url":"https://docs.n8n.io/integrations/builtin/cluster-nodes/root-nodes/n8n-nodes-langchain.sentimentanalysis/"}]}},"defaults":{"name":"Sentiment Analysis"},"inputs":[{"displayName":"","type":"main"},{"displayName":"Model","maxConnections":1,"type":"ai_languageModel","required":true}],"outputs":"={{((parameters, defaultCategories) => {\n const options = parameters?.options ?? {};\n const categories = options?.categories ?? defaultCategories;\n const categoriesArray = categories.split(\",\").map((cat) => cat.trim());\n const ret = categoriesArray.map((cat) => ({ type: \"main\", displayName: cat }));\n return ret;\n})($parameter, \"Positive, Neutral, Negative\")}}","properties":[{"displayName":"Text to Analyze","name":"inputText","type":"string","required":true,"default":"","description":"Use an expression to reference data in previous nodes or enter static text","typeOptions":{"rows":2}},{"displayName":"Sentiment scores are LLM-generated estimates, not statistically rigorous measurements. They may be inconsistent across runs and should be used as rough indicators only.","name":"detailedResultsNotice","type":"notice","default":"","displayOptions":{"show":{"/options.includeDetailedResults":[true]}}},{"displayName":"Options","name":"options","type":"collection","default":{},"placeholder":"Add Option","options":[{"displayName":"Sentiment Categories","name":"categories","type":"string","default":"Positive, Neutral, Negative","description":"A comma-separated list of categories to analyze","noDataExpression":true,"typeOptions":{"rows":2}},{"displayName":"System Prompt Template","name":"systemPromptTemplate","type":"string","default":"You are highly intelligent and accurate sentiment analyzer. Analyze the sentiment of the provided text. Categorize it into one of the following: {categories}. Use the provided formatting instructions. Only output the JSON.","description":"String to use directly as the system prompt template","typeOptions":{"rows":6}},{"displayName":"Include Detailed Results","name":"includeDetailedResults","type":"boolean","default":false,"description":"Whether to include sentiment strength and confidence scores in the output"},{"displayName":"Enable Auto-Fixing","name":"enableAutoFixing","type":"boolean","default":true,"description":"Whether to enable auto-fixing (may trigger an additional LLM call if output is broken)"},{"displayName":"Batch Processing","name":"batching","type":"collection","placeholder":"Add Batch Processing Option","description":"Batch processing options for rate limiting","default":{},"options":[{"displayName":"Batch Size","name":"batchSize","default":5,"type":"number","description":"How many items to process in parallel. This is useful for rate limiting, but might impact the log output ordering."},{"displayName":"Delay Between Batches","name":"delayBetweenBatches","default":0,"type":"number","description":"Delay in milliseconds between batches. This is useful for rate limiting."}],"displayOptions":{"show":{"@version":[{"_cnd":{"gte":1.1}}]}}}]}]},
18
18
  {"displayName":"Information Extractor","name":"informationExtractor","icon":"fa:project-diagram","iconColor":"black","group":["transform"],"version":[1,1.1,1.2],"defaultVersion":1.2,"description":"Extract information from text in a structured format","codex":{"alias":["NER","parse","parsing","JSON","data extraction","structured"],"categories":["AI"],"subcategories":{"AI":["Chains","Root Nodes"]},"resources":{"primaryDocumentation":[{"url":"https://docs.n8n.io/integrations/builtin/cluster-nodes/root-nodes/n8n-nodes-langchain.information-extractor/"}]}},"defaults":{"name":"Information Extractor"},"inputs":[{"displayName":"","type":"main"},{"displayName":"Model","maxConnections":1,"type":"ai_languageModel","required":true}],"outputs":["main"],"properties":[{"displayName":"Text","name":"text","type":"string","default":"","description":"The text to extract information from","typeOptions":{"rows":2}},{"displayName":"Schema Type","name":"schemaType","type":"options","noDataExpression":true,"options":[{"name":"From Attribute Descriptions","value":"fromAttributes","description":"Extract specific attributes from the text based on types and descriptions"},{"name":"Generate From JSON Example","value":"fromJson","description":"Generate a schema from an example JSON object"},{"name":"Define using JSON Schema","value":"manual","description":"Define the JSON schema manually"}],"default":"fromAttributes","description":"How to specify the schema for the desired output"},{"displayName":"JSON Example","name":"jsonSchemaExample","type":"json","default":"{\n\t\"state\": \"California\",\n\t\"cities\": [\"Los Angeles\", \"San Francisco\", \"San Diego\"]\n}","noDataExpression":true,"typeOptions":{"rows":10},"displayOptions":{"show":{"schemaType":["fromJson"]}},"description":"Example JSON object to use to generate the schema"},{"displayName":"All properties will be required. To make them optional, use the 'JSON Schema' schema type instead","name":"notice","type":"notice","default":"","displayOptions":{"show":{"@version":[{"_cnd":{"gte":1.2}}],"schemaType":["fromJson"]}}},{"displayName":"Input Schema","name":"inputSchema","type":"json","default":"{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"state\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"cities\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"items\": {\n\t\t\t\t\"type\": \"string\"\n\t\t\t}\n\t\t}\n\t}\n}","noDataExpression":false,"typeOptions":{"rows":10},"displayOptions":{"show":{"schemaType":["manual"]}},"description":"Schema to use for the function","hint":"Use <a target=\"_blank\" href=\"https://json-schema.org/\">JSON Schema</a> format (<a target=\"_blank\" href=\"https://json-schema.org/learn/miscellaneous-examples.html\">examples</a>). $refs syntax is currently not supported."},{"displayName":"Attributes","name":"attributes","placeholder":"Add Attribute","type":"fixedCollection","default":{},"displayOptions":{"show":{"schemaType":["fromAttributes"]}},"typeOptions":{"multipleValues":true},"options":[{"name":"attributes","displayName":"Attribute List","values":[{"displayName":"Name","name":"name","type":"string","default":"","description":"Attribute to extract","placeholder":"e.g. company_name","required":true},{"displayName":"Type","name":"type","type":"options","description":"Data type of the attribute","required":true,"options":[{"name":"Boolean","value":"boolean"},{"name":"Date","value":"date"},{"name":"Number","value":"number"},{"name":"String","value":"string"}],"default":"string"},{"displayName":"Description","name":"description","type":"string","default":"","description":"Describe your attribute","placeholder":"Add description for the attribute","required":true},{"displayName":"Required","name":"required","type":"boolean","default":false,"description":"Whether attribute is required","required":true}]}]},{"displayName":"Options","name":"options","type":"collection","default":{},"placeholder":"Add Option","options":[{"displayName":"System Prompt Template","name":"systemPromptTemplate","type":"string","default":"You are an expert extraction algorithm.\nOnly extract relevant information from the text.\nIf you do not know the value of an attribute asked to extract, you may omit the attribute's value.","description":"String to use directly as the system prompt template","typeOptions":{"rows":6}},{"displayName":"Batch Processing","name":"batching","type":"collection","placeholder":"Add Batch Processing Option","description":"Batch processing options for rate limiting","default":{},"options":[{"displayName":"Batch Size","name":"batchSize","default":5,"type":"number","description":"How many items to process in parallel. This is useful for rate limiting, but might impact the log output ordering."},{"displayName":"Delay Between Batches","name":"delayBetweenBatches","default":0,"type":"number","description":"Delay in milliseconds between batches. This is useful for rate limiting."}],"displayOptions":{"show":{"@version":[{"_cnd":{"gte":1.1}}]}}}]}]},
@@ -117,6 +117,19 @@ function buildSteps(response, itemIndex) {
117
117
  ...typeof messageContent === "string" && { tool_calls: [toolCall] }
118
118
  });
119
119
  const toolInputForResult = toolInput.input;
120
+ const aiToolData = tool.data?.data?.ai_tool?.[0]?.map((item) => item?.json);
121
+ let observation;
122
+ if (aiToolData && aiToolData.length > 0) {
123
+ observation = JSON.stringify(aiToolData);
124
+ } else if (tool.data?.error) {
125
+ const errorInfo = {
126
+ error: tool.data.error.message ?? "Unknown error",
127
+ ...tool.data.error.name && { errorType: tool.data.error.name }
128
+ };
129
+ observation = JSON.stringify(errorInfo);
130
+ } else {
131
+ observation = JSON.stringify("");
132
+ }
120
133
  const toolResult = {
121
134
  action: {
122
135
  tool: (0, import_n8n_workflow.nodeNameToToolName)(tool.action.nodeName),
@@ -126,7 +139,7 @@ function buildSteps(response, itemIndex) {
126
139
  toolCallId: toolInput?.id,
127
140
  type: toolInput.type || "tool_call"
128
141
  },
129
- observation: JSON.stringify(tool.data?.data?.ai_tool?.[0]?.map((item) => item?.json) ?? "")
142
+ observation
130
143
  };
131
144
  steps.push(toolResult);
132
145
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../utils/agent-execution/buildSteps.ts"],"sourcesContent":["import { AIMessage } from '@langchain/core/messages';\nimport { nodeNameToToolName } from 'n8n-workflow';\nimport type { EngineResponse, IDataObject } from 'n8n-workflow';\n\nimport type {\n\tRequestResponseMetadata,\n\tToolCallData,\n\tThinkingContentBlock,\n\tRedactedThinkingContentBlock,\n\tToolUseContentBlock,\n} from './types';\n\n/**\n * Provider-specific metadata extracted from tool action metadata\n */\ninterface ProviderMetadata {\n\t/** Gemini thought_signature for extended thinking */\n\tthoughtSignature?: string;\n\t/** Anthropic thinking content */\n\tthinkingContent?: string;\n\t/** Anthropic thinking type (thinking or redacted_thinking) */\n\tthinkingType?: 'thinking' | 'redacted_thinking';\n\t/** Anthropic thinking signature */\n\tthinkingSignature?: string;\n}\n\n/**\n * Extracts provider-specific metadata from tool action metadata.\n * Validates and normalizes metadata from different LLM providers.\n *\n * @param metadata - The request/response metadata from tool action\n * @returns Extracted and validated provider metadata\n */\nfunction extractProviderMetadata(metadata?: RequestResponseMetadata): ProviderMetadata {\n\tif (!metadata) return {};\n\n\t// Extract Google/Gemini metadata\n\tconst thoughtSignature =\n\t\ttypeof metadata.google?.thoughtSignature === 'string'\n\t\t\t? metadata.google.thoughtSignature\n\t\t\t: undefined;\n\n\t// Extract Anthropic metadata\n\tconst thinkingContent =\n\t\ttypeof metadata.anthropic?.thinkingContent === 'string'\n\t\t\t? metadata.anthropic.thinkingContent\n\t\t\t: undefined;\n\n\tconst thinkingType =\n\t\tmetadata.anthropic?.thinkingType === 'thinking' ||\n\t\tmetadata.anthropic?.thinkingType === 'redacted_thinking'\n\t\t\t? metadata.anthropic.thinkingType\n\t\t\t: undefined;\n\n\tconst thinkingSignature =\n\t\ttypeof metadata.anthropic?.thinkingSignature === 'string'\n\t\t\t? metadata.anthropic.thinkingSignature\n\t\t\t: undefined;\n\n\treturn {\n\t\tthoughtSignature,\n\t\tthinkingContent,\n\t\tthinkingType,\n\t\tthinkingSignature,\n\t};\n}\n\n/**\n * Builds Anthropic-specific content blocks for thinking mode.\n * Creates an array with thinking block followed by tool_use block.\n *\n * IMPORTANT: The thinking block must come before tool_use in the message.\n * When content is an array, LangChain ignores tool_calls field for Anthropic,\n * so tool_use blocks must be in the content array.\n *\n * @param thinkingContent - The thinking content from Anthropic\n * @param thinkingType - Type of thinking block (thinking or redacted_thinking)\n * @param thinkingSignature - Optional signature for thinking block\n * @param toolInput - The tool input data\n * @param toolId - The tool call ID\n * @param toolName - The tool name\n * @returns Array of content blocks with thinking and tool_use\n */\nfunction buildAnthropicContentBlocks(\n\tthinkingContent: string,\n\tthinkingType: 'thinking' | 'redacted_thinking',\n\tthinkingSignature: string | undefined,\n\ttoolInput: IDataObject,\n\ttoolId: string,\n\ttoolName: string,\n): Array<ThinkingContentBlock | RedactedThinkingContentBlock | ToolUseContentBlock> {\n\t// Create thinking block with correct field names for Anthropic API\n\tconst thinkingBlock: ThinkingContentBlock | RedactedThinkingContentBlock =\n\t\tthinkingType === 'thinking'\n\t\t\t? {\n\t\t\t\t\ttype: 'thinking',\n\t\t\t\t\tthinking: thinkingContent,\n\t\t\t\t\tsignature: thinkingSignature ?? '', // Use original signature if available\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\ttype: 'redacted_thinking',\n\t\t\t\t\tdata: thinkingContent,\n\t\t\t\t};\n\n\t// Create tool_use block (required for Anthropic when using structured content)\n\tconst toolInputData = toolInput.input;\n\tconst toolUseBlock: ToolUseContentBlock = {\n\t\ttype: 'tool_use',\n\t\tid: toolId,\n\t\tname: toolName,\n\t\tinput:\n\t\t\ttoolInputData && typeof toolInputData === 'object'\n\t\t\t\t? (toolInputData as Record<string, unknown>)\n\t\t\t\t: {},\n\t};\n\n\treturn [thinkingBlock, toolUseBlock];\n}\n\n/**\n * Builds message content for AI message, handling provider-specific formats.\n * For Anthropic thinking mode, creates content blocks with thinking and tool_use.\n * For other providers, creates simple string content.\n *\n * @param providerMetadata - Provider-specific metadata\n * @param toolInput - The tool input data\n * @param toolId - The tool call ID\n * @param toolName - The tool name\n * @param nodeName - The node name for fallback string content\n * @returns Message content (string or content blocks array)\n */\nfunction buildMessageContent(\n\tproviderMetadata: ProviderMetadata,\n\ttoolInput: IDataObject,\n\ttoolId: string,\n\ttoolName: string,\n\tnodeName: string,\n): string | Array<ThinkingContentBlock | RedactedThinkingContentBlock | ToolUseContentBlock> {\n\tconst { thinkingContent, thinkingType, thinkingSignature } = providerMetadata;\n\n\t// Anthropic thinking mode: build content blocks\n\tif (thinkingContent && thinkingType) {\n\t\treturn buildAnthropicContentBlocks(\n\t\t\tthinkingContent,\n\t\t\tthinkingType,\n\t\t\tthinkingSignature,\n\t\t\ttoolInput,\n\t\t\ttoolId,\n\t\t\ttoolName,\n\t\t);\n\t}\n\n\t// Default: simple string content\n\treturn `Calling ${nodeName} with input: ${JSON.stringify(toolInput)}`;\n}\n\n/**\n * Rebuilds the agent steps from previous tool call responses.\n * This is used to continue agent execution after tool calls have been made.\n *\n * This is a generalized version that can be used across different agent types\n * (Tools Agent, OpenAI Functions Agent, etc.).\n *\n * @param response - The engine response containing tool call results\n * @param itemIndex - The current item index being processed\n * @returns Array of tool call data representing the agent steps\n */\nexport function buildSteps(\n\tresponse: EngineResponse<RequestResponseMetadata> | undefined,\n\titemIndex: number,\n): ToolCallData[] {\n\tconst steps: ToolCallData[] = [];\n\n\tif (response) {\n\t\tconst responses = response?.actionResponses ?? [];\n\n\t\tif (response.metadata?.previousRequests) {\n\t\t\tsteps.push.apply(steps, response.metadata.previousRequests);\n\t\t}\n\n\t\tfor (const tool of responses) {\n\t\t\tif (tool.action?.metadata?.itemIndex !== itemIndex) continue;\n\n\t\t\tconst toolInput: IDataObject = {\n\t\t\t\t...tool.action.input,\n\t\t\t\tid: tool.action.id,\n\t\t\t};\n\t\t\tif (!toolInput || !tool.data) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst step = steps.find((step) => step.action.toolCallId === toolInput.id);\n\t\t\tif (step) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Extract provider-specific metadata (Gemini, Anthropic, etc.)\n\t\t\tconst providerMetadata = extractProviderMetadata(tool.action.metadata);\n\n\t\t\t// Build tool ID and name for reuse\n\t\t\tconst toolId = typeof toolInput?.id === 'string' ? toolInput.id : 'reconstructed_call';\n\t\t\tconst toolName = nodeNameToToolName(tool.action.nodeName);\n\n\t\t\t// Build the tool call object with thought_signature if present (for Gemini)\n\t\t\tconst toolCall = {\n\t\t\t\tid: toolId,\n\t\t\t\tname: toolName,\n\t\t\t\targs: toolInput,\n\t\t\t\ttype: 'tool_call' as const,\n\t\t\t\tadditional_kwargs: {\n\t\t\t\t\t...(providerMetadata.thoughtSignature && {\n\t\t\t\t\t\tthought_signature: providerMetadata.thoughtSignature,\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t};\n\n\t\t\t// Build message content using provider-specific logic\n\t\t\tconst messageContent = buildMessageContent(\n\t\t\t\tproviderMetadata,\n\t\t\t\ttoolInput,\n\t\t\t\ttoolId,\n\t\t\t\ttoolName,\n\t\t\t\ttool.action.nodeName,\n\t\t\t);\n\n\t\t\tconst syntheticAIMessage = new AIMessage({\n\t\t\t\tcontent: messageContent,\n\t\t\t\t// Note: tool_calls is only used when content is a string\n\t\t\t\t// When content is an array (thinking mode), tool_use blocks are in the content array\n\t\t\t\t...(typeof messageContent === 'string' && { tool_calls: [toolCall] }),\n\t\t\t});\n\n\t\t\tconst toolInputForResult = toolInput.input;\n\t\t\tconst toolResult = {\n\t\t\t\taction: {\n\t\t\t\t\ttool: nodeNameToToolName(tool.action.nodeName),\n\t\t\t\t\ttoolInput:\n\t\t\t\t\t\ttoolInputForResult && typeof toolInputForResult === 'object'\n\t\t\t\t\t\t\t? (toolInputForResult as IDataObject)\n\t\t\t\t\t\t\t: {},\n\t\t\t\t\tlog: toolInput.log || syntheticAIMessage.content,\n\t\t\t\t\tmessageLog: [syntheticAIMessage],\n\t\t\t\t\ttoolCallId: toolInput?.id,\n\t\t\t\t\ttype: toolInput.type || 'tool_call',\n\t\t\t\t},\n\t\t\t\tobservation: JSON.stringify(tool.data?.data?.ai_tool?.[0]?.map((item) => item?.json) ?? ''),\n\t\t\t};\n\n\t\t\tsteps.push(toolResult);\n\t\t}\n\t}\n\treturn steps;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAA0B;AAC1B,0BAAmC;AAgCnC,SAAS,wBAAwB,UAAsD;AACtF,MAAI,CAAC,SAAU,QAAO,CAAC;AAGvB,QAAM,mBACL,OAAO,SAAS,QAAQ,qBAAqB,WAC1C,SAAS,OAAO,mBAChB;AAGJ,QAAM,kBACL,OAAO,SAAS,WAAW,oBAAoB,WAC5C,SAAS,UAAU,kBACnB;AAEJ,QAAM,eACL,SAAS,WAAW,iBAAiB,cACrC,SAAS,WAAW,iBAAiB,sBAClC,SAAS,UAAU,eACnB;AAEJ,QAAM,oBACL,OAAO,SAAS,WAAW,sBAAsB,WAC9C,SAAS,UAAU,oBACnB;AAEJ,SAAO;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AACD;AAkBA,SAAS,4B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mB,wBAAwB,KAAK,OAAO,QAAQ;AAGrE,YAAM,SAAS,OAAO,WAAW,OAAO,WAAW,UAAU,KAAK;AAClE,YAAM,eAAW,wCAAmB,KAAK,OAAO,QAAQ;AAGxD,YAAM,WAAW;AAAA,QAChB,IAAI;AAAA,QACJ,MAAM;AAAA,QACN,MAAM;AAAA,QACN,MAAM;AAAA,QACN,mBAAmB;AAAA,UAClB,GAAI,iBAAiB,oBAAoB;AAAA,YACxC,mBAAmB,iBAAiB;AAAA,UACrC;AAAA,QACD;AAAA,MACD;AAGA,YAAM,iBAAiB;AAAA,QACtB;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,KAAK,OAAO;AAAA,MACb;AAEA,YAAM,qBAAqB,IAAI,0BAAU;AAAA,QACxC,SAAS;AAAA;AAAA;AAAA,QAGT,GAAI,OAAO,mBAAmB,YAAY,EAAE,YAAY,CAAC,QAAQ,EAAE;AAAA,MACpE,CAAC;AAED,YAAM,qBAAqB,UAAU;AACrC,YAAM,aAAa;AAAA,QAClB,QAAQ;AAAA,UACP,UAAM,wCAAmB,KAAK,OAAO,QAAQ;AAAA,UAC7C,WACC,sBAAsB,OAAO,uBAAuB,WAChD,qBACD,CAAC;AAAA,UACL,KAAK,UAAU,OAAO,mBAAmB;AAAA,UACzC,YAAY,CAAC,kBAAkB;AAAA,UAC/B,YAAY,WAAW;AAAA,UACvB,MAAM,UAAU,QAAQ;AAAA,QACzB;AAAA,QACA,aAAa,KAAK,UAAU,KAAK,MAAM,MAAM,UAAU,CAAC,GAAG,IAAI,CAAC,SAAS,MAAM,IAAI,KAAK,EAAE;AAAA,MAC3F;AAEA,YAAM,KAAK,UAAU;AAAA,IACtB;AAAA,EACD;AACA,SAAO;AACR;","names":["step"]}
1
+ {"version":3,"sources":["../../../utils/agent-execution/buildSteps.ts"],"sourcesContent":["import { AIMessage } from '@langchain/core/messages';\nimport { nodeNameToToolName } from 'n8n-workflow';\nimport type { EngineResponse, IDataObject } from 'n8n-workflow';\n\nimport type {\n\tRequestResponseMetadata,\n\tToolCallData,\n\tThinkingContentBlock,\n\tRedactedThinkingContentBlock,\n\tToolUseContentBlock,\n} from './types';\n\n/**\n * Provider-specific metadata extracted from tool action metadata\n */\ninterface ProviderMetadata {\n\t/** Gemini thought_signature for extended thinking */\n\tthoughtSignature?: string;\n\t/** Anthropic thinking content */\n\tthinkingContent?: string;\n\t/** Anthropic thinking type (thinking or redacted_thinking) */\n\tthinkingType?: 'thinking' | 'redacted_thinking';\n\t/** Anthropic thinking signature */\n\tthinkingSignature?: string;\n}\n\n/**\n * Extracts provider-specific metadata from tool action metadata.\n * Validates and normalizes metadata from different LLM providers.\n *\n * @param metadata - The request/response metadata from tool action\n * @returns Extracted and validated provider metadata\n */\nfunction extractProviderMetadata(metadata?: RequestResponseMetadata): ProviderMetadata {\n\tif (!metadata) return {};\n\n\t// Extract Google/Gemini metadata\n\tconst thoughtSignature =\n\t\ttypeof metadata.google?.thoughtSignature === 'string'\n\t\t\t? metadata.google.thoughtSignature\n\t\t\t: undefined;\n\n\t// Extract Anthropic metadata\n\tconst thinkingContent =\n\t\ttypeof metadata.anthropic?.thinkingContent === 'string'\n\t\t\t? metadata.anthropic.thinkingContent\n\t\t\t: undefined;\n\n\tconst thinkingType =\n\t\tmetadata.anthropic?.thinkingType === 'thinking' ||\n\t\tmetadata.anthropic?.thinkingType === 'redacted_thinking'\n\t\t\t? metadata.anthropic.thinkingType\n\t\t\t: undefined;\n\n\tconst thinkingSignature =\n\t\ttypeof metadata.anthropic?.thinkingSignature === 'string'\n\t\t\t? metadata.anthropic.thinkingSignature\n\t\t\t: undefined;\n\n\treturn {\n\t\tthoughtSignature,\n\t\tthinkingContent,\n\t\tthinkingType,\n\t\tthinkingSignature,\n\t};\n}\n\n/**\n * Builds Anthropic-specific content blocks for thinking mode.\n * Creates an array with thinking block followed by tool_use block.\n *\n * IMPORTANT: The thinking block must come before tool_use in the message.\n * When content is an array, LangChain ignores tool_calls field for Anthropic,\n * so tool_use blocks must be in the content array.\n *\n * @param thinkingContent - The thinking content from Anthropic\n * @param thinkingType - Type of thinking block (thinking or redacted_thinking)\n * @param thinkingSignature - Optional signature for thinking block\n * @param toolInput - The tool input data\n * @param toolId - The tool call ID\n * @param toolName - The tool name\n * @returns Array of content blocks with thinking and tool_use\n */\nfunction buildAnthropicContentBlocks(\n\tthinkingContent: string,\n\tthinkingType: 'thinking' | 'redacted_thinking',\n\tthinkingSignature: string | undefined,\n\ttoolInput: IDataObject,\n\ttoolId: string,\n\ttoolName: string,\n): Array<ThinkingContentBlock | RedactedThinkingContentBlock | ToolUseContentBlock> {\n\t// Create thinking block with correct field names for Anthropic API\n\tconst thinkingBlock: ThinkingContentBlock | RedactedThinkingContentBlock =\n\t\tthinkingType === 'thinking'\n\t\t\t? {\n\t\t\t\t\ttype: 'thinking',\n\t\t\t\t\tthinking: thinkingContent,\n\t\t\t\t\tsignature: thinkingSignature ?? '', // Use original signature if available\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\ttype: 'redacted_thinking',\n\t\t\t\t\tdata: thinkingContent,\n\t\t\t\t};\n\n\t// Create tool_use block (required for Anthropic when using structured content)\n\tconst toolInputData = toolInput.input;\n\tconst toolUseBlock: ToolUseContentBlock = {\n\t\ttype: 'tool_use',\n\t\tid: toolId,\n\t\tname: toolName,\n\t\tinput:\n\t\t\ttoolInputData && typeof toolInputData === 'object'\n\t\t\t\t? (toolInputData as Record<string, unknown>)\n\t\t\t\t: {},\n\t};\n\n\treturn [thinkingBlock, toolUseBlock];\n}\n\n/**\n * Builds message content for AI message, handling provider-specific formats.\n * For Anthropic thinking mode, creates content blocks with thinking and tool_use.\n * For other providers, creates simple string content.\n *\n * @param providerMetadata - Provider-specific metadata\n * @param toolInput - The tool input data\n * @param toolId - The tool call ID\n * @param toolName - The tool name\n * @param nodeName - The node name for fallback string content\n * @returns Message content (string or content blocks array)\n */\nfunction buildMessageContent(\n\tproviderMetadata: ProviderMetadata,\n\ttoolInput: IDataObject,\n\ttoolId: string,\n\ttoolName: string,\n\tnodeName: string,\n): string | Array<ThinkingContentBlock | RedactedThinkingContentBlock | ToolUseContentBlock> {\n\tconst { thinkingContent, thinkingType, thinkingSignature } = providerMetadata;\n\n\t// Anthropic thinking mode: build content blocks\n\tif (thinkingContent && thinkingType) {\n\t\treturn buildAnthropicContentBlocks(\n\t\t\tthinkingContent,\n\t\t\tthinkingType,\n\t\t\tthinkingSignature,\n\t\t\ttoolInput,\n\t\t\ttoolId,\n\t\t\ttoolName,\n\t\t);\n\t}\n\n\t// Default: simple string content\n\treturn `Calling ${nodeName} with input: ${JSON.stringify(toolInput)}`;\n}\n\n/**\n * Rebuilds the agent steps from previous tool call responses.\n * This is used to continue agent execution after tool calls have been made.\n *\n * This is a generalized version that can be used across different agent types\n * (Tools Agent, OpenAI Functions Agent, etc.).\n *\n * @param response - The engine response containing tool call results\n * @param itemIndex - The current item index being processed\n * @returns Array of tool call data representing the agent steps\n */\nexport function buildSteps(\n\tresponse: EngineResponse<RequestResponseMetadata> | undefined,\n\titemIndex: number,\n): ToolCallData[] {\n\tconst steps: ToolCallData[] = [];\n\n\tif (response) {\n\t\tconst responses = response?.actionResponses ?? [];\n\n\t\tif (response.metadata?.previousRequests) {\n\t\t\tsteps.push.apply(steps, response.metadata.previousRequests);\n\t\t}\n\n\t\tfor (const tool of responses) {\n\t\t\tif (tool.action?.metadata?.itemIndex !== itemIndex) continue;\n\n\t\t\tconst toolInput: IDataObject = {\n\t\t\t\t...tool.action.input,\n\t\t\t\tid: tool.action.id,\n\t\t\t};\n\t\t\tif (!toolInput || !tool.data) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst step = steps.find((step) => step.action.toolCallId === toolInput.id);\n\t\t\tif (step) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Extract provider-specific metadata (Gemini, Anthropic, etc.)\n\t\t\tconst providerMetadata = extractProviderMetadata(tool.action.metadata);\n\n\t\t\t// Build tool ID and name for reuse\n\t\t\tconst toolId = typeof toolInput?.id === 'string' ? toolInput.id : 'reconstructed_call';\n\t\t\tconst toolName = nodeNameToToolName(tool.action.nodeName);\n\n\t\t\t// Build the tool call object with thought_signature if present (for Gemini)\n\t\t\tconst toolCall = {\n\t\t\t\tid: toolId,\n\t\t\t\tname: toolName,\n\t\t\t\targs: toolInput,\n\t\t\t\ttype: 'tool_call' as const,\n\t\t\t\tadditional_kwargs: {\n\t\t\t\t\t...(providerMetadata.thoughtSignature && {\n\t\t\t\t\t\tthought_signature: providerMetadata.thoughtSignature,\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t};\n\n\t\t\t// Build message content using provider-specific logic\n\t\t\tconst messageContent = buildMessageContent(\n\t\t\t\tproviderMetadata,\n\t\t\t\ttoolInput,\n\t\t\t\ttoolId,\n\t\t\t\ttoolName,\n\t\t\t\ttool.action.nodeName,\n\t\t\t);\n\n\t\t\tconst syntheticAIMessage = new AIMessage({\n\t\t\t\tcontent: messageContent,\n\t\t\t\t// Note: tool_calls is only used when content is a string\n\t\t\t\t// When content is an array (thinking mode), tool_use blocks are in the content array\n\t\t\t\t...(typeof messageContent === 'string' && { tool_calls: [toolCall] }),\n\t\t\t});\n\n\t\t\tconst toolInputForResult = toolInput.input;\n\n\t\t\t// Build observation from tool result data or error information\n\t\t\t// When tool execution fails, ai_tool may be missing but error info should be preserved\n\t\t\tconst aiToolData = tool.data?.data?.ai_tool?.[0]?.map((item) => item?.json);\n\t\t\tlet observation: string;\n\t\t\tif (aiToolData && aiToolData.length > 0) {\n\t\t\t\tobservation = JSON.stringify(aiToolData);\n\t\t\t} else if (tool.data?.error) {\n\t\t\t\t// Include error information in observation so the agent can see what went wrong\n\t\t\t\t// tool.data is ITaskData which has error?: ExecutionError\n\t\t\t\tconst errorInfo = {\n\t\t\t\t\terror: tool.data.error.message ?? 'Unknown error',\n\t\t\t\t\t...(tool.data.error.name && { errorType: tool.data.error.name }),\n\t\t\t\t};\n\t\t\t\tobservation = JSON.stringify(errorInfo);\n\t\t\t} else {\n\t\t\t\tobservation = JSON.stringify('');\n\t\t\t}\n\n\t\t\tconst toolResult = {\n\t\t\t\taction: {\n\t\t\t\t\ttool: nodeNameToToolName(tool.action.nodeName),\n\t\t\t\t\ttoolInput:\n\t\t\t\t\t\ttoolInputForResult && typeof toolInputForResult === 'object'\n\t\t\t\t\t\t\t? (toolInputForResult as IDataObject)\n\t\t\t\t\t\t\t: {},\n\t\t\t\t\tlog: toolInput.log || syntheticAIMessage.content,\n\t\t\t\t\tmessageLog: [syntheticAIMessage],\n\t\t\t\t\ttoolCallId: toolInput?.id,\n\t\t\t\t\ttype: toolInput.type || 'tool_call',\n\t\t\t\t},\n\t\t\t\tobservation,\n\t\t\t};\n\n\t\t\tsteps.push(toolResult);\n\t\t}\n\t}\n\treturn steps;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAA0B;AAC1B,0BAAmC;AAgCnC,SAAS,wBAAwB,UAAsD;AACtF,MAAI,CAAC,SAAU,QAAO,CAAC;AAGvB,QAAM,mBACL,OAAO,SAAS,QAAQ,qBAAqB,WAC1C,SAAS,OAAO,mBAChB;AAGJ,QAAM,kBACL,OAAO,SAAS,WAAW,oBAAoB,WAC5C,SAAS,UAAU,kBACnB;AAEJ,QAAM,eACL,SAAS,WAAW,iBAAiB,cACrC,SAAS,WAAW,iBAAiB,sBAClC,SAAS,UAAU,eACnB;AAEJ,QAAM,oBACL,OAAO,SAAS,WAAW,sBAAsB,WAC9C,SAAS,UAAU,oBACnB;AAEJ,SAAO;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD;AACD;AAkBA,SAAS,4BACR,iBACA,cACA,mBACA,WACA,QACA,UACmF;AAEnF,QAAM,gBACL,iBAAiB,aACd;AAAA,IACA,MAAM;AAAA,IACN,UAAU;AAAA,IACV,WAAW,qBAAqB;AAAA;AAAA,EACjC,IACC;AAAA,IACA,MAAM;AAAA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ACD;AACA,SAAO;AACR;","names":["step"]}
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var embeddingInputValidation_exports = {};
20
+ __export(embeddingInputValidation_exports, {
21
+ validateEmbedDocumentsInput: () => validateEmbedDocumentsInput,
22
+ validateEmbedQueryInput: () => validateEmbedQueryInput
23
+ });
24
+ module.exports = __toCommonJS(embeddingInputValidation_exports);
25
+ var import_n8n_workflow = require("n8n-workflow");
26
+ function validateEmbedQueryInput(query, node) {
27
+ if (typeof query !== "string" || query === "") {
28
+ throw new import_n8n_workflow.NodeOperationError(node, "Cannot embed empty or undefined text", {
29
+ description: "The text provided for embedding is empty or undefined. This can happen when: the input expression evaluates to undefined, the AI agent calls a tool without proper arguments, or a required field is missing."
30
+ });
31
+ }
32
+ return query;
33
+ }
34
+ function validateEmbedDocumentsInput(documents, node) {
35
+ if (!Array.isArray(documents)) {
36
+ throw new import_n8n_workflow.NodeOperationError(node, "Documents must be an array", {
37
+ description: "Expected an array of strings to embed."
38
+ });
39
+ }
40
+ const invalidIndex = documents.findIndex(
41
+ (doc) => doc === void 0 || doc === null || doc === ""
42
+ );
43
+ if (invalidIndex !== -1) {
44
+ throw new import_n8n_workflow.NodeOperationError(node, `Invalid document at index ${invalidIndex}`, {
45
+ description: `Document at index ${invalidIndex} is empty or undefined. All documents must be non-empty strings.`
46
+ });
47
+ }
48
+ return documents;
49
+ }
50
+ // Annotate the CommonJS export names for ESM import in node:
51
+ 0 && (module.exports = {
52
+ validateEmbedDocumentsInput,
53
+ validateEmbedQueryInput
54
+ });
55
+ //# sourceMappingURL=embeddingInputValidation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../utils/embeddings/embeddingInputValidation.ts"],"sourcesContent":["import type { INode } from 'n8n-workflow';\nimport { NodeOperationError } from 'n8n-workflow';\n\n/**\n * Validates query input for embedQuery operations.\n * Throws NodeOperationError if query is invalid (undefined, null, or empty string).\n *\n * @param query - The query to validate\n * @param node - The node for error context\n * @returns The validated query string\n * @throws NodeOperationError if query is invalid\n */\nexport function validateEmbedQueryInput(query: unknown, node: INode): string {\n\tif (typeof query !== 'string' || query === '') {\n\t\tthrow new NodeOperationError(node, 'Cannot embed empty or undefined text', {\n\t\t\tdescription:\n\t\t\t\t'The text provided for embedding is empty or undefined. This can happen when: the input expression evaluates to undefined, the AI agent calls a tool without proper arguments, or a required field is missing.',\n\t\t});\n\t}\n\treturn query;\n}\n\n/**\n * Validates documents input for embedDocuments operations.\n * Throws NodeOperationError if documents array is invalid or contains invalid entries.\n *\n * @param documents - The documents array to validate\n * @param node - The node for error context\n * @returns The validated documents array\n * @throws NodeOperationError if documents is not an array or contains invalid entries\n */\nexport function validateEmbedDocumentsInput(documents: unknown, node: INode): string[] {\n\tif (!Array.isArray(documents)) {\n\t\tthrow new NodeOperationError(node, 'Documents must be an array', {\n\t\t\tdescription: 'Expected an array of strings to embed.',\n\t\t});\n\t}\n\n\tconst invalidIndex = documents.findIndex(\n\t\t(doc) => doc === undefined || doc === null || doc === '',\n\t);\n\n\tif (invalidIndex !== -1) {\n\t\tthrow new NodeOperationError(node, `Invalid document at index ${invalidIndex}`, {\n\t\t\tdescription: `Document at index ${invalidIndex} is empty or undefined. All documents must be non-empty strings.`,\n\t\t});\n\t}\n\n\treturn documents;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,0BAAmC;AAW5B,SAAS,wBAAwB,OAAgB,MAAqB;AAC5E,MAAI,OAAO,UAAU,YAAY,UAAU,IAAI;AAC9C,UAAM,IAAI,uCAAmB,MAAM,wCAAwC;AAAA,MAC1E,aACC;AAAA,IACF,CAAC;AAAA,EACF;AACA,SAAO;AACR;AAWO,SAAS,4BAA4B,WAAoB,MAAuB;AACtF,MAAI,CAAC,MAAM,QAAQ,SAAS,GAAG;AAC9B,UAAM,IAAI,uCAAmB,MAAM,8BAA8B;AAAA,MAChE,aAAa;AAAA,IACd,CAAC;AAAA,EACF;AAEA,QAAM,eAAe,UAAU;AAAA,IAC9B,CAAC,QAAQ,QAAQ,UAAa,QAAQ,QAAQ,QAAQ;AAAA,EACvD;AAEA,MAAI,iBAAiB,IAAI;AACxB,UAAM,IAAI,uCAAmB,MAAM,6BAA6B,YAAY,IAAI;AAAA,MAC/E,aAAa,qBAAqB,YAAY;AAAA,IAC/C,CAAC;AAAA,EACF;AAEA,SAAO;AACR;","names":[]}
@@ -30,6 +30,7 @@ var import_vectorstores = require("@langchain/core/vectorstores");
30
30
  var import_textsplitters = require("@langchain/textsplitters");
31
31
  var import_openai = require("@langchain/openai");
32
32
  var import_n8n_workflow = require("n8n-workflow");
33
+ var import_embeddingInputValidation = require("./embeddings/embeddingInputValidation");
33
34
  var import_helpers = require("./helpers");
34
35
  var import_N8nBinaryLoader = require("./N8nBinaryLoader");
35
36
  var import_N8nJsonLoader = require("./N8nJsonLoader");
@@ -197,16 +198,20 @@ function logWrapper(originalInstance, executeFunctions) {
197
198
  if (originalInstance instanceof import_embeddings.Embeddings || originalInstance instanceof import_openai.OpenAIEmbeddings || originalInstance instanceof import_openai.AzureOpenAIEmbeddings) {
198
199
  if (prop === "embedDocuments" && "embedDocuments" in target) {
199
200
  return async (documents) => {
201
+ const validatedDocuments = (0, import_embeddingInputValidation.validateEmbedDocumentsInput)(
202
+ documents,
203
+ executeFunctions.getNode()
204
+ );
200
205
  connectionType = import_n8n_workflow.NodeConnectionTypes.AiEmbedding;
201
206
  const { index } = executeFunctions.addInputData(connectionType, [
202
- [{ json: { documents } }]
207
+ [{ json: { documents: validatedDocuments } }]
203
208
  ]);
204
209
  const response = await callMethodAsync.call(target, {
205
210
  executeFunctions,
206
211
  connectionType,
207
212
  currentNodeRunIndex: index,
208
213
  method: target[prop],
209
- arguments: [documents]
214
+ arguments: [validatedDocuments]
210
215
  });
211
216
  (0, import_helpers.logAiEvent)(executeFunctions, "ai-document-embedded");
212
217
  executeFunctions.addOutputData(connectionType, index, [[{ json: { response } }]]);
@@ -215,16 +220,17 @@ function logWrapper(originalInstance, executeFunctions) {
215
220
  }
216
221
  if (prop === "embedQuery" && "embedQuery" in target) {
217
222
  return async (query) => {
223
+ const validatedQuery = (0, import_embeddingInputValidation.validateEmbedQueryInput)(query, executeFunctions.getNode());
218
224
  connectionType = import_n8n_workflow.NodeConnectionTypes.AiEmbedding;
219
225
  const { index } = executeFunctions.addInputData(connectionType, [
220
- [{ json: { query } }]
226
+ [{ json: { query: validatedQuery } }]
221
227
  ]);
222
228
  const response = await callMethodAsync.call(target, {
223
229
  executeFunctions,
224
230
  connectionType,
225
231
  currentNodeRunIndex: index,
226
232
  method: target[prop],
227
- arguments: [query]
233
+ arguments: [validatedQuery]
228
234
  });
229
235
  (0, import_helpers.logAiEvent)(executeFunctions, "ai-query-embedded");
230
236
  executeFunctions.addOutputData(connectionType, index, [[{ json: { response } }]]);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../utils/logWrapper.ts"],"sourcesContent":["import type { BaseChatMemory } from '@langchain/community/memory/chat_memory';\nimport type { BaseCallbackConfig, Callbacks } from '@langchain/core/callbacks/manager';\nimport type { BaseChatMessageHistory } from '@langchain/core/chat_history';\nimport type { Document } from '@langchain/core/documents';\nimport { Embeddings } from '@langchain/core/embeddings';\nimport type { InputValues, MemoryVariables, OutputValues } from '@langchain/core/memory';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport { BaseRetriever } from '@langchain/core/retrievers';\nimport { BaseDocumentCompressor } from '@langchain/core/retrievers/document_compressors';\nimport type { StructuredTool, Tool } from '@langchain/core/tools';\nimport { VectorStore } from '@langchain/core/vectorstores';\nimport { TextSplitter } from '@langchain/textsplitters';\nimport type { BaseDocumentLoader } from '@langchain/classic/dist/document_loaders/base';\nimport { OpenAIEmbeddings, AzureOpenAIEmbeddings } from '@langchain/openai';\nimport type {\n\tIDataObject,\n\tIExecuteFunctions,\n\tINodeExecutionData,\n\tISupplyDataFunctions,\n\tITaskMetadata,\n\tNodeConnectionType,\n} from 'n8n-workflow';\nimport {\n\tNodeOperationError,\n\tNodeConnectionTypes,\n\tparseErrorMetadata,\n\tdeepCopy,\n} from 'n8n-workflow';\n\nimport { logAiEvent, isToolsInstance, isBaseChatMemory, isBaseChatMessageHistory } from './helpers';\nimport { N8nBinaryLoader } from './N8nBinaryLoader';\nimport { N8nJsonLoader } from './N8nJsonLoader';\n\nexport async function callMethodAsync<T>(\n\tthis: T,\n\tparameters: {\n\t\texecuteFunctions: IExecuteFunctions | ISupplyDataFunctions;\n\t\tconnectionType: NodeConnectionType;\n\t\tcurrentNodeRunIndex: number;\n\t\tmethod: (...args: any[]) => Promise<unknown>;\n\t\targuments: unknown[];\n\t},\n): Promise<unknown> {\n\ttry {\n\t\treturn await parameters.method.call(this, ...parameters.arguments);\n\t} catch (e) {\n\t\tconst connectedNode = parameters.executeFunctions.getNode();\n\n\t\tconst error = new NodeOperationError(connectedNode, e, {\n\t\t\tfunctionality: 'configuration-node',\n\t\t});\n\n\t\tconst metadata = parseErrorMetadata(error);\n\t\tparameters.executeFunctions.addOutputData(\n\t\t\tparameters.connectionType,\n\t\t\tparameters.currentNodeRunIndex,\n\t\t\terror,\n\t\t\tmetadata,\n\t\t);\n\n\t\tif (error.message) {\n\t\t\tif (!error.description) {\n\t\t\t\terror.description = error.message;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\tthrow new NodeOperationError(\n\t\t\tconnectedNode,\n\t\t\t`Error on node \"${connectedNode.name}\" which is connected via input \"${parameters.connectionType}\"`,\n\t\t\t{ functionality: 'configuration-node' },\n\t\t);\n\t}\n}\n\nexport function callMethodSync<T>(\n\tthis: T,\n\tparameters: {\n\t\texecuteFunctions: IExecuteFunctions;\n\t\tconnectionType: NodeConnectionType;\n\t\tcurrentNodeRunIndex: number;\n\t\tmethod: (...args: any[]) => T;\n\t\targuments: unknown[];\n\t},\n): unknown {\n\ttry {\n\t\treturn parameters.method.call(this, ...parameters.arguments);\n\t} catch (e) {\n\t\tconst connectedNode = parameters.executeFunctions.getNode();\n\t\tconst error = new NodeOperationError(connectedNode, e);\n\t\tparameters.executeFunctions.addOutputData(\n\t\t\tparameters.connectionType,\n\t\t\tparameters.currentNodeRunIndex,\n\t\t\terror,\n\t\t);\n\n\t\tthrow new NodeOperationError(\n\t\t\tconnectedNode,\n\t\t\t`Error on node \"${connectedNode.name}\" which is connected via input \"${parameters.connectionType}\"`,\n\t\t\t{ functionality: 'configuration-node' },\n\t\t);\n\t}\n}\n\nexport function logWrapper<\n\tT extends\n\t\t| Tool\n\t\t| StructuredTool\n\t\t| BaseChatMemory\n\t\t| BaseChatMessageHistory\n\t\t| BaseRetriever\n\t\t| BaseDocumentCompressor\n\t\t| Embeddings\n\t\t| OpenAIEmbeddings\n\t\t| AzureOpenAIEmbeddings\n\t\t| Document[]\n\t\t| Document\n\t\t| BaseDocumentLoader\n\t\t| TextSplitter\n\t\t| VectorStore\n\t\t| N8nBinaryLoader\n\t\t| N8nJsonLoader,\n>(originalInstance: T, executeFunctions: IExecuteFunctions | ISupplyDataFunctions): T {\n\treturn new Proxy(originalInstance, {\n\t\tget: (target, prop) => {\n\t\t\tlet connectionType: NodeConnectionType | undefined;\n\t\t\t// ========== BaseChatMemory ==========\n\t\t\tif (isBaseChatMemory(originalInstance)) {\n\t\t\t\tif (prop === 'loadMemoryVariables' && 'loadMemoryVariables' in target) {\n\t\t\t\t\treturn async (values: InputValues): Promise<MemoryVariables> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiMemory;\n\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { action: 'loadMemoryVariables', values } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [values],\n\t\t\t\t\t\t})) as MemoryVariables;\n\n\t\t\t\t\t\tconst chatHistory = (response?.chat_history as BaseMessage[]) ?? response;\n\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [\n\t\t\t\t\t\t\t[{ json: { action: 'loadMemoryVariables', chatHistory } }],\n\t\t\t\t\t\t]);\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t} else if (prop === 'saveContext' && 'saveContext' in target) {\n\t\t\t\t\treturn async (input: InputValues, output: OutputValues): Promise<MemoryVariables> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiMemory;\n\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { action: 'saveContext', input, output } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [input, output],\n\t\t\t\t\t\t})) as MemoryVariables;\n\n\t\t\t\t\t\tconst chatHistory = await target.chatHistory.getMessages();\n\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [\n\t\t\t\t\t\t\t[{ json: { action: 'saveContext', chatHistory } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ========== BaseChatMessageHistory ==========\n\t\t\tif (isBaseChatMessageHistory(originalInstance)) {\n\t\t\t\tif (prop === 'getMessages' && 'getMessages' in target) {\n\t\t\t\t\treturn async (): Promise<BaseMessage[]> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiMemory;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { action: 'getMessages' } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [],\n\t\t\t\t\t\t})) as BaseMessage[];\n\n\t\t\t\t\t\tconst payload = { action: 'getMessages', response };\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: payload }]]);\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-messages-retrieved-from-memory', { response });\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t} else if (prop === 'addMessage' && 'addMessage' in target) {\n\t\t\t\t\treturn async (message: BaseMessage): Promise<void> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiMemory;\n\t\t\t\t\t\tconst payload = { action: 'addMessage', message };\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [[{ json: payload }]]);\n\n\t\t\t\t\t\tawait callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [message],\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-message-added-to-memory', { message });\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: payload }]]);\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ========== BaseRetriever ==========\n\t\t\tif (originalInstance instanceof BaseRetriever) {\n\t\t\t\tif (prop === 'getRelevantDocuments' && 'getRelevantDocuments' in target) {\n\t\t\t\t\treturn async (\n\t\t\t\t\t\tquery: string,\n\t\t\t\t\t\tconfig?: Callbacks | BaseCallbackConfig,\n\t\t\t\t\t): Promise<Document[]> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiRetriever;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { query, config } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [query, config],\n\t\t\t\t\t\t})) as Array<Document<Record<string, any>>>;\n\n\t\t\t\t\t\tconst executionId: string | undefined = response[0]?.metadata?.executionId as string;\n\t\t\t\t\t\tconst workflowId: string | undefined = response[0]?.metadata?.workflowId as string;\n\n\t\t\t\t\t\tconst metadata: ITaskMetadata = {};\n\t\t\t\t\t\tif (executionId && workflowId) {\n\t\t\t\t\t\t\tmetadata.subExecution = {\n\t\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\t\tworkflowId,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-documents-retrieved', { query });\n\t\t\t\t\t\texecuteFunctions.addOutputData(\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tindex,\n\t\t\t\t\t\t\t[[{ json: { response } }]],\n\t\t\t\t\t\t\tmetadata,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ========== Embeddings ==========\n\t\t\tif (\n\t\t\t\toriginalInstance instanceof Embeddings ||\n\t\t\t\toriginalInstance instanceof OpenAIEmbeddings ||\n\t\t\t\toriginalInstance instanceof AzureOpenAIEmbeddings\n\t\t\t) {\n\t\t\t\t// Docs -> Embeddings\n\t\t\t\tif (prop === 'embedDocuments' && 'embedDocuments' in target) {\n\t\t\t\t\treturn async (documents: string[]): Promise<number[][]> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiEmbedding;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { documents } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [documents],\n\t\t\t\t\t\t})) as number[][];\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-document-embedded');\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: { response } }]]);\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\t// Query -> Embeddings\n\t\t\t\tif (prop === 'embedQuery' && 'embedQuery' in target) {\n\t\t\t\t\treturn async (query: string): Promise<number[]> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiEmbedding;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { query } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [query],\n\t\t\t\t\t\t})) as number[];\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-query-embedded');\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: { response } }]]);\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ========== Rerankers ==========\n\t\t\tif (originalInstance instanceof BaseDocumentCompressor) {\n\t\t\t\tif (prop === 'compressDocuments' && 'compressDocuments' in target) {\n\t\t\t\t\treturn async (documents: Document[], query: string): Promise<Document[]> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiReranker;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { query, documents } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\t// compressDocuments mutates the original object\n\t\t\t\t\t\t\t// messing up the input data logging\n\t\t\t\t\t\t\targuments: [deepCopy(documents), query],\n\t\t\t\t\t\t})) as Document[];\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-document-reranked', { query });\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: { response } }]]);\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ========== N8n Loaders Process All ==========\n\t\t\tif (\n\t\t\t\toriginalInstance instanceof N8nJsonLoader ||\n\t\t\t\toriginalInstance instanceof N8nBinaryLoader\n\t\t\t) {\n\t\t\t\t// Process All\n\t\t\t\tif (prop === 'processAll' && 'processAll' in target) {\n\t\t\t\t\treturn async (items: INodeExecutionData[]): Promise<number[]> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiDocument;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [items]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [items],\n\t\t\t\t\t\t})) as number[];\n\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: { response } }]]);\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// Process Each\n\t\t\t\tif (prop === 'processItem' && 'processItem' in target) {\n\t\t\t\t\treturn async (item: INodeExecutionData, itemIndex: number): Promise<number[]> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiDocument;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [[item]]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [item, itemIndex],\n\t\t\t\t\t\t})) as number[];\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-document-processed');\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [\n\t\t\t\t\t\t\t[{ json: { response }, pairedItem: { item: itemIndex } }],\n\t\t\t\t\t\t]);\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ========== TextSplitter ==========\n\t\t\tif (originalInstance instanceof TextSplitter) {\n\t\t\t\tif (prop === 'splitText' && 'splitText' in target) {\n\t\t\t\t\treturn async (text: string): Promise<string[]> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiTextSplitter;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { textSplitter: text } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [text],\n\t\t\t\t\t\t})) as string[];\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-text-split');\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: { response } }]]);\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ========== Tool ==========\n\t\t\tif (isToolsInstance(originalInstance)) {\n\t\t\t\tif (prop === '_call' && '_call' in target) {\n\t\t\t\t\treturn async (query: string): Promise<string> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiTool;\n\t\t\t\t\t\tconst inputData: IDataObject = { query };\n\n\t\t\t\t\t\tif (target.metadata?.isFromToolkit) {\n\t\t\t\t\t\t\tinputData.tool = {\n\t\t\t\t\t\t\t\tname: target.name,\n\t\t\t\t\t\t\t\tdescription: target.description,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: inputData }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [query],\n\t\t\t\t\t\t})) as string;\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-tool-called', { ...inputData, response });\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: { response } }]]);\n\n\t\t\t\t\t\tif (typeof response === 'string') return response;\n\t\t\t\t\t\treturn JSON.stringify(response);\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ========== VectorStore ==========\n\t\t\tif (originalInstance instanceof VectorStore) {\n\t\t\t\tif (prop === 'similaritySearch' && 'similaritySearch' in target) {\n\t\t\t\t\treturn async (\n\t\t\t\t\t\tquery: string,\n\t\t\t\t\t\tk?: number,\n\t\t\t\t\t\tfilter?: BiquadFilterType,\n\t\t\t\t\t\t_callbacks?: Callbacks,\n\t\t\t\t\t): Promise<Document[]> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiVectorStore;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { query, k, filter } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [query, k, filter, _callbacks],\n\t\t\t\t\t\t})) as Array<Document<Record<string, any>>>;\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-vector-store-searched', { query });\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: { response } }]]);\n\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-return\n\t\t\treturn (target as any)[prop];\n\t\t},\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,wBAA2B;AAG3B,wBAA8B;AAC9B,kCAAuC;AAEvC,0BAA4B;AAC5B,2BAA6B;AAE7B,oBAAwD;AASxD,0BAKO;AAEP,qBAAwF;AACxF,6BAAgC;AAChC,2BAA8B;AAE9B,eAAsB,gBAErB,YAOmB;AACnB,MAAI;AACH,WAAO,MAAM,WAAW,OAAO,KAAK,MAAM,GAAG,WAAW,SAAS;AAAA,EAClE,SAAS,GAAG;AACX,UAAM,gBAAgB,WAAW,iBAAiB,QAAQ;AAE1D,UAAM,QAAQ,IAAI,uCAAmB,eAAe,GAAG;AAAA,MACtD,eAAe;AAAA,IAChB,CAAC;AAED,UAAM,eAAW,wCAAmB,KAAK;AACzC,eAAW,iBAAiB;AAAA,MAC3B,WAAW;AAAA,MACX,WAAW;AAAA,MACX;AAAA,MACA;AAAA,IACD;AAEA,QAAI,MAAM,SAAS;AAClB,UAAI,CAAC,MAAM,aAAa;AACvB,cAAM,cAAc,MAAM;AAAA,MAC3B;AACA,YAAM;AAAA,IACP;AAEA,UAAM,IAAI;AAAA,MACT;AAAA,MACA,kBAAkB,cAAc,IAAI,mCAAmC,WAAW,cAAc;AAAA,MAChG,EAAE,eAAe,qBAAqB;AAAA,IACvC;AAAA,EACD;AACD;AAEO,SAAS,eAEf,YAOU;AACV,MAAI;AACH,WAAO,WAAW,O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AC,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC;AAEhF,mBAAO;AAAA,UACR;AAAA,QACD;AAAA,MACD;AAGA,aAAQ,OAAe,IAAI;AAAA,IAC5B;AAAA,EACD,CAAC;AACF;","names":[]}
1
+ {"version":3,"sources":["../../utils/logWrapper.ts"],"sourcesContent":["import type { BaseChatMemory } from '@langchain/community/memory/chat_memory';\nimport type { BaseCallbackConfig, Callbacks } from '@langchain/core/callbacks/manager';\nimport type { BaseChatMessageHistory } from '@langchain/core/chat_history';\nimport type { Document } from '@langchain/core/documents';\nimport { Embeddings } from '@langchain/core/embeddings';\nimport type { InputValues, MemoryVariables, OutputValues } from '@langchain/core/memory';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport { BaseRetriever } from '@langchain/core/retrievers';\nimport { BaseDocumentCompressor } from '@langchain/core/retrievers/document_compressors';\nimport type { StructuredTool, Tool } from '@langchain/core/tools';\nimport { VectorStore } from '@langchain/core/vectorstores';\nimport { TextSplitter } from '@langchain/textsplitters';\nimport type { BaseDocumentLoader } from '@langchain/classic/dist/document_loaders/base';\nimport { OpenAIEmbeddings, AzureOpenAIEmbeddings } from '@langchain/openai';\nimport type {\n\tIDataObject,\n\tIExecuteFunctions,\n\tINodeExecutionData,\n\tISupplyDataFunctions,\n\tITaskMetadata,\n\tNodeConnectionType,\n} from 'n8n-workflow';\nimport {\n\tNodeOperationError,\n\tNodeConnectionTypes,\n\tparseErrorMetadata,\n\tdeepCopy,\n} from 'n8n-workflow';\n\nimport {\n\tvalidateEmbedQueryInput,\n\tvalidateEmbedDocumentsInput,\n} from './embeddings/embeddingInputValidation';\nimport { logAiEvent, isToolsInstance, isBaseChatMemory, isBaseChatMessageHistory } from './helpers';\nimport { N8nBinaryLoader } from './N8nBinaryLoader';\nimport { N8nJsonLoader } from './N8nJsonLoader';\n\nexport async function callMethodAsync<T>(\n\tthis: T,\n\tparameters: {\n\t\texecuteFunctions: IExecuteFunctions | ISupplyDataFunctions;\n\t\tconnectionType: NodeConnectionType;\n\t\tcurrentNodeRunIndex: number;\n\t\tmethod: (...args: any[]) => Promise<unknown>;\n\t\targuments: unknown[];\n\t},\n): Promise<unknown> {\n\ttry {\n\t\treturn await parameters.method.call(this, ...parameters.arguments);\n\t} catch (e) {\n\t\tconst connectedNode = parameters.executeFunctions.getNode();\n\n\t\tconst error = new NodeOperationError(connectedNode, e, {\n\t\t\tfunctionality: 'configuration-node',\n\t\t});\n\n\t\tconst metadata = parseErrorMetadata(error);\n\t\tparameters.executeFunctions.addOutputData(\n\t\t\tparameters.connectionType,\n\t\t\tparameters.currentNodeRunIndex,\n\t\t\terror,\n\t\t\tmetadata,\n\t\t);\n\n\t\tif (error.message) {\n\t\t\tif (!error.description) {\n\t\t\t\terror.description = error.message;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\tthrow new NodeOperationError(\n\t\t\tconnectedNode,\n\t\t\t`Error on node \"${connectedNode.name}\" which is connected via input \"${parameters.connectionType}\"`,\n\t\t\t{ functionality: 'configuration-node' },\n\t\t);\n\t}\n}\n\nexport function callMethodSync<T>(\n\tthis: T,\n\tparameters: {\n\t\texecuteFunctions: IExecuteFunctions;\n\t\tconnectionType: NodeConnectionType;\n\t\tcurrentNodeRunIndex: number;\n\t\tmethod: (...args: any[]) => T;\n\t\targuments: unknown[];\n\t},\n): unknown {\n\ttry {\n\t\treturn parameters.method.call(this, ...parameters.arguments);\n\t} catch (e) {\n\t\tconst connectedNode = parameters.executeFunctions.getNode();\n\t\tconst error = new NodeOperationError(connectedNode, e);\n\t\tparameters.executeFunctions.addOutputData(\n\t\t\tparameters.connectionType,\n\t\t\tparameters.currentNodeRunIndex,\n\t\t\terror,\n\t\t);\n\n\t\tthrow new NodeOperationError(\n\t\t\tconnectedNode,\n\t\t\t`Error on node \"${connectedNode.name}\" which is connected via input \"${parameters.connectionType}\"`,\n\t\t\t{ functionality: 'configuration-node' },\n\t\t);\n\t}\n}\n\nexport function logWrapper<\n\tT extends\n\t\t| Tool\n\t\t| StructuredTool\n\t\t| BaseChatMemory\n\t\t| BaseChatMessageHistory\n\t\t| BaseRetriever\n\t\t| BaseDocumentCompressor\n\t\t| Embeddings\n\t\t| OpenAIEmbeddings\n\t\t| AzureOpenAIEmbeddings\n\t\t| Document[]\n\t\t| Document\n\t\t| BaseDocumentLoader\n\t\t| TextSplitter\n\t\t| VectorStore\n\t\t| N8nBinaryLoader\n\t\t| N8nJsonLoader,\n>(originalInstance: T, executeFunctions: IExecuteFunctions | ISupplyDataFunctions): T {\n\treturn new Proxy(originalInstance, {\n\t\tget: (target, prop) => {\n\t\t\tlet connectionType: NodeConnectionType | undefined;\n\t\t\t// ========== BaseChatMemory ==========\n\t\t\tif (isBaseChatMemory(originalInstance)) {\n\t\t\t\tif (prop === 'loadMemoryVariables' && 'loadMemoryVariables' in target) {\n\t\t\t\t\treturn async (values: InputValues): Promise<MemoryVariables> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiMemory;\n\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { action: 'loadMemoryVariables', values } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [values],\n\t\t\t\t\t\t})) as MemoryVariables;\n\n\t\t\t\t\t\tconst chatHistory = (response?.chat_history as BaseMessage[]) ?? response;\n\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [\n\t\t\t\t\t\t\t[{ json: { action: 'loadMemoryVariables', chatHistory } }],\n\t\t\t\t\t\t]);\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t} else if (prop === 'saveContext' && 'saveContext' in target) {\n\t\t\t\t\treturn async (input: InputValues, output: OutputValues): Promise<MemoryVariables> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiMemory;\n\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { action: 'saveContext', input, output } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [input, output],\n\t\t\t\t\t\t})) as MemoryVariables;\n\n\t\t\t\t\t\tconst chatHistory = await target.chatHistory.getMessages();\n\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [\n\t\t\t\t\t\t\t[{ json: { action: 'saveContext', chatHistory } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ========== BaseChatMessageHistory ==========\n\t\t\tif (isBaseChatMessageHistory(originalInstance)) {\n\t\t\t\tif (prop === 'getMessages' && 'getMessages' in target) {\n\t\t\t\t\treturn async (): Promise<BaseMessage[]> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiMemory;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { action: 'getMessages' } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [],\n\t\t\t\t\t\t})) as BaseMessage[];\n\n\t\t\t\t\t\tconst payload = { action: 'getMessages', response };\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: payload }]]);\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-messages-retrieved-from-memory', { response });\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t} else if (prop === 'addMessage' && 'addMessage' in target) {\n\t\t\t\t\treturn async (message: BaseMessage): Promise<void> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiMemory;\n\t\t\t\t\t\tconst payload = { action: 'addMessage', message };\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [[{ json: payload }]]);\n\n\t\t\t\t\t\tawait callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [message],\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-message-added-to-memory', { message });\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: payload }]]);\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ========== BaseRetriever ==========\n\t\t\tif (originalInstance instanceof BaseRetriever) {\n\t\t\t\tif (prop === 'getRelevantDocuments' && 'getRelevantDocuments' in target) {\n\t\t\t\t\treturn async (\n\t\t\t\t\t\tquery: string,\n\t\t\t\t\t\tconfig?: Callbacks | BaseCallbackConfig,\n\t\t\t\t\t): Promise<Document[]> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiRetriever;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { query, config } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [query, config],\n\t\t\t\t\t\t})) as Array<Document<Record<string, any>>>;\n\n\t\t\t\t\t\tconst executionId: string | undefined = response[0]?.metadata?.executionId as string;\n\t\t\t\t\t\tconst workflowId: string | undefined = response[0]?.metadata?.workflowId as string;\n\n\t\t\t\t\t\tconst metadata: ITaskMetadata = {};\n\t\t\t\t\t\tif (executionId && workflowId) {\n\t\t\t\t\t\t\tmetadata.subExecution = {\n\t\t\t\t\t\t\t\texecutionId,\n\t\t\t\t\t\t\t\tworkflowId,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-documents-retrieved', { query });\n\t\t\t\t\t\texecuteFunctions.addOutputData(\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tindex,\n\t\t\t\t\t\t\t[[{ json: { response } }]],\n\t\t\t\t\t\t\tmetadata,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ========== Embeddings ==========\n\t\t\tif (\n\t\t\t\toriginalInstance instanceof Embeddings ||\n\t\t\t\toriginalInstance instanceof OpenAIEmbeddings ||\n\t\t\t\toriginalInstance instanceof AzureOpenAIEmbeddings\n\t\t\t) {\n\t\t\t\t// Docs -> Embeddings\n\t\t\t\tif (prop === 'embedDocuments' && 'embedDocuments' in target) {\n\t\t\t\t\treturn async (documents: string[]): Promise<number[][]> => {\n\t\t\t\t\t\t// Validate documents input before embedding\n\t\t\t\t\t\tconst validatedDocuments = validateEmbedDocumentsInput(\n\t\t\t\t\t\t\tdocuments,\n\t\t\t\t\t\t\texecuteFunctions.getNode(),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiEmbedding;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { documents: validatedDocuments } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [validatedDocuments],\n\t\t\t\t\t\t})) as number[][];\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-document-embedded');\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: { response } }]]);\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\t// Query -> Embeddings\n\t\t\t\tif (prop === 'embedQuery' && 'embedQuery' in target) {\n\t\t\t\t\treturn async (query: string): Promise<number[]> => {\n\t\t\t\t\t\t// Validate query input before embedding\n\t\t\t\t\t\tconst validatedQuery = validateEmbedQueryInput(query, executeFunctions.getNode());\n\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiEmbedding;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { query: validatedQuery } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [validatedQuery],\n\t\t\t\t\t\t})) as number[];\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-query-embedded');\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: { response } }]]);\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ========== Rerankers ==========\n\t\t\tif (originalInstance instanceof BaseDocumentCompressor) {\n\t\t\t\tif (prop === 'compressDocuments' && 'compressDocuments' in target) {\n\t\t\t\t\treturn async (documents: Document[], query: string): Promise<Document[]> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiReranker;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { query, documents } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\t// compressDocuments mutates the original object\n\t\t\t\t\t\t\t// messing up the input data logging\n\t\t\t\t\t\t\targuments: [deepCopy(documents), query],\n\t\t\t\t\t\t})) as Document[];\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-document-reranked', { query });\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: { response } }]]);\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ========== N8n Loaders Process All ==========\n\t\t\tif (\n\t\t\t\toriginalInstance instanceof N8nJsonLoader ||\n\t\t\t\toriginalInstance instanceof N8nBinaryLoader\n\t\t\t) {\n\t\t\t\t// Process All\n\t\t\t\tif (prop === 'processAll' && 'processAll' in target) {\n\t\t\t\t\treturn async (items: INodeExecutionData[]): Promise<number[]> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiDocument;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [items]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [items],\n\t\t\t\t\t\t})) as number[];\n\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: { response } }]]);\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// Process Each\n\t\t\t\tif (prop === 'processItem' && 'processItem' in target) {\n\t\t\t\t\treturn async (item: INodeExecutionData, itemIndex: number): Promise<number[]> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiDocument;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [[item]]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [item, itemIndex],\n\t\t\t\t\t\t})) as number[];\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-document-processed');\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [\n\t\t\t\t\t\t\t[{ json: { response }, pairedItem: { item: itemIndex } }],\n\t\t\t\t\t\t]);\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ========== TextSplitter ==========\n\t\t\tif (originalInstance instanceof TextSplitter) {\n\t\t\t\tif (prop === 'splitText' && 'splitText' in target) {\n\t\t\t\t\treturn async (text: string): Promise<string[]> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiTextSplitter;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { textSplitter: text } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [text],\n\t\t\t\t\t\t})) as string[];\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-text-split');\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: { response } }]]);\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ========== Tool ==========\n\t\t\tif (isToolsInstance(originalInstance)) {\n\t\t\t\tif (prop === '_call' && '_call' in target) {\n\t\t\t\t\treturn async (query: string): Promise<string> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiTool;\n\t\t\t\t\t\tconst inputData: IDataObject = { query };\n\n\t\t\t\t\t\tif (target.metadata?.isFromToolkit) {\n\t\t\t\t\t\t\tinputData.tool = {\n\t\t\t\t\t\t\t\tname: target.name,\n\t\t\t\t\t\t\t\tdescription: target.description,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: inputData }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [query],\n\t\t\t\t\t\t})) as string;\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-tool-called', { ...inputData, response });\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: { response } }]]);\n\n\t\t\t\t\t\tif (typeof response === 'string') return response;\n\t\t\t\t\t\treturn JSON.stringify(response);\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ========== VectorStore ==========\n\t\t\tif (originalInstance instanceof VectorStore) {\n\t\t\t\tif (prop === 'similaritySearch' && 'similaritySearch' in target) {\n\t\t\t\t\treturn async (\n\t\t\t\t\t\tquery: string,\n\t\t\t\t\t\tk?: number,\n\t\t\t\t\t\tfilter?: BiquadFilterType,\n\t\t\t\t\t\t_callbacks?: Callbacks,\n\t\t\t\t\t): Promise<Document[]> => {\n\t\t\t\t\t\tconnectionType = NodeConnectionTypes.AiVectorStore;\n\t\t\t\t\t\tconst { index } = executeFunctions.addInputData(connectionType, [\n\t\t\t\t\t\t\t[{ json: { query, k, filter } }],\n\t\t\t\t\t\t]);\n\n\t\t\t\t\t\tconst response = (await callMethodAsync.call(target, {\n\t\t\t\t\t\t\texecuteFunctions,\n\t\t\t\t\t\t\tconnectionType,\n\t\t\t\t\t\t\tcurrentNodeRunIndex: index,\n\t\t\t\t\t\t\tmethod: target[prop] as (...args: any[]) => Promise<unknown>,\n\t\t\t\t\t\t\targuments: [query, k, filter, _callbacks],\n\t\t\t\t\t\t})) as Array<Document<Record<string, any>>>;\n\n\t\t\t\t\t\tlogAiEvent(executeFunctions, 'ai-vector-store-searched', { query });\n\t\t\t\t\t\texecuteFunctions.addOutputData(connectionType, index, [[{ json: { response } }]]);\n\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-return\n\t\t\treturn (target as any)[prop];\n\t\t},\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,wBAA2B;AAG3B,wBAA8B;AAC9B,kCAAuC;AAEvC,0BAA4B;AAC5B,2BAA6B;AAE7B,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