@n8n/n8n-nodes-langchain 1.116.1 → 1.117.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.
@@ -209,7 +209,7 @@ function buildSteps(response, itemIndex) {
209
209
  toolCallId: toolInput?.id,
210
210
  type: toolInput.type || "tool_call"
211
211
  },
212
- observation: JSON.stringify(tool.data)
212
+ observation: JSON.stringify(tool.data?.data?.ai_tool?.[0]?.[0]?.json ?? "")
213
213
  };
214
214
  steps.push(toolResult);
215
215
  }
@@ -308,10 +308,17 @@ async function toolsAgentExecute(response) {
308
308
  input
309
309
  );
310
310
  if (result.toolCalls && result.toolCalls.length > 0) {
311
+ const currentIteration = (response?.metadata?.iterationCount ?? 0) + 1;
312
+ if (options.maxIterations && currentIteration > options.maxIterations) {
313
+ throw new import_n8n_workflow.NodeOperationError(this.getNode(), "Maximum iterations reached");
314
+ }
311
315
  const actions = await createEngineRequests(result.toolCalls, itemIndex, tools);
312
316
  return {
313
317
  actions,
314
- metadata: { previousRequests: buildSteps(response, itemIndex) }
318
+ metadata: {
319
+ previousRequests: buildSteps(response, itemIndex),
320
+ iterationCount: currentIteration
321
+ }
315
322
  };
316
323
  }
317
324
  return result;
@@ -341,10 +348,17 @@ async function toolsAgentExecute(response) {
341
348
  }
342
349
  return result;
343
350
  }
351
+ const currentIteration = (response?.metadata?.iterationCount ?? 0) + 1;
352
+ if (options.maxIterations && currentIteration > options.maxIterations) {
353
+ throw new import_n8n_workflow.NodeOperationError(this.getNode(), "Maximum iterations reached");
354
+ }
344
355
  const actions = await createEngineRequests(modelResponse, itemIndex, tools);
345
356
  return {
346
357
  actions,
347
- metadata: { previousRequests: buildSteps(response, itemIndex) }
358
+ metadata: {
359
+ previousRequests: buildSteps(response, itemIndex),
360
+ iterationCount: currentIteration
361
+ }
348
362
  };
349
363
  }
350
364
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../nodes/agents/Agent/agents/ToolsAgent/V3/execute.ts"],"sourcesContent":["import type { StreamEvent } from '@langchain/core/dist/tracers/event_stream';\nimport type { IterableReadableStream } from '@langchain/core/dist/utils/stream';\nimport type { BaseChatModel } from '@langchain/core/language_models/chat_models';\nimport type { AIMessageChunk, BaseMessage, MessageContentText } from '@langchain/core/messages';\nimport { AIMessage, trimMessages } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { ChatPromptTemplate } from '@langchain/core/prompts';\nimport { RunnableSequence } from '@langchain/core/runnables';\nimport { type AgentRunnableSequence, createToolCallingAgent } from 'langchain/agents';\nimport type { BaseChatMemory } from 'langchain/memory';\nimport type { DynamicStructuredTool, Tool } from 'langchain/tools';\nimport omit from 'lodash/omit';\nimport {\n\tjsonParse,\n\tNodeConnectionTypes,\n\tnodeNameToToolName,\n\tNodeOperationError,\n\tsleep,\n} from 'n8n-workflow';\nimport type {\n\tEngineRequest,\n\tGenericValue,\n\tIDataObject,\n\tIExecuteFunctions,\n\tINodeExecutionData,\n\tISupplyDataFunctions,\n\tEngineResponse,\n} from 'n8n-workflow';\nimport assert from 'node:assert';\n\nimport { getPromptInputByType } from '@utils/helpers';\nimport {\n\tgetOptionalOutputParser,\n\ttype N8nOutputParser,\n} from '@utils/output_parsers/N8nOutputParser';\n\nimport {\n\tfixEmptyContentMessage,\n\tgetAgentStepsParser,\n\tgetChatModel,\n\tgetOptionalMemory,\n\tgetTools,\n\tprepareMessages,\n\tpreparePrompt,\n} from '../common';\nimport { SYSTEM_MESSAGE } from '../prompt';\n\ntype ToolCallRequest = {\n\ttool: string;\n\ttoolInput: Record<string, unknown>;\n\ttoolCallId: string;\n\ttype?: string;\n\tlog?: string;\n\tmessageLog?: unknown[];\n};\n\nasync function createEngineRequests(\n\ttoolCalls: ToolCallRequest[],\n\titemIndex: number,\n\ttools: Array<DynamicStructuredTool | Tool>,\n) {\n\treturn toolCalls.map((toolCall) => {\n\t\t// First try to get from metadata (for toolkit tools)\n\t\tconst foundTool = tools.find((tool) => tool.name === toolCall.tool);\n\n\t\tif (!foundTool) return;\n\n\t\tconst nodeName = foundTool.metadata?.sourceNodeName;\n\n\t\t// For toolkit tools, include the tool name so the node knows which tool to execute\n\t\tconst input = foundTool.metadata?.isFromToolkit\n\t\t\t? { ...toolCall.toolInput, tool: toolCall.tool }\n\t\t\t: toolCall.toolInput;\n\n\t\treturn {\n\t\t\tnodeName,\n\t\t\tinput,\n\t\t\ttype: NodeConnectionTypes.AiTool,\n\t\t\tid: toolCall.toolCallId,\n\t\t\tmetadata: {\n\t\t\t\titemIndex,\n\t\t\t},\n\t\t};\n\t});\n}\n\n/**\n * Creates an agent executor with the given configuration\n */\nfunction createAgentSequence(\n\tmodel: BaseChatModel,\n\ttools: Array<DynamicStructuredTool | Tool>,\n\tprompt: ChatPromptTemplate,\n\t_options: { maxIterations?: number; returnIntermediateSteps?: boolean },\n\toutputParser?: N8nOutputParser,\n\tmemory?: BaseChatMemory,\n\tfallbackModel?: BaseChatModel | null,\n) {\n\tconst agent = createToolCallingAgent({\n\t\tllm: model,\n\t\ttools,\n\t\tprompt,\n\t\tstreamRunnable: false,\n\t});\n\n\tlet fallbackAgent: AgentRunnableSequence | undefined;\n\tif (fallbackModel) {\n\t\tfallbackAgent = createToolCallingAgent({\n\t\t\tllm: fallbackModel,\n\t\t\ttools,\n\t\t\tprompt,\n\t\t\tstreamRunnable: false,\n\t\t});\n\t}\n\tconst runnableAgent = RunnableSequence.from([\n\t\tfallbackAgent ? agent.withFallbacks([fallbackAgent]) : agent,\n\t\tgetAgentStepsParser(outputParser, memory),\n\t\tfixEmptyContentMessage,\n\t]) as AgentRunnableSequence;\n\n\trunnableAgent.singleAction = true;\n\trunnableAgent.streamRunnable = false;\n\n\treturn runnableAgent;\n}\n\ntype IntermediateStep = {\n\taction: {\n\t\ttool: string;\n\t\ttoolInput: Record<string, unknown>;\n\t\tlog: string;\n\t\tmessageLog: unknown[];\n\t\ttoolCallId: string;\n\t\ttype: string;\n\t};\n\tobservation?: string;\n};\n\ntype AgentResult = {\n\toutput: string;\n\tintermediateSteps?: IntermediateStep[];\n\ttoolCalls?: ToolCallRequest[];\n};\n\nasync function processEventStream(\n\tctx: IExecuteFunctions,\n\teventStream: IterableReadableStream<StreamEvent>,\n\titemIndex: number,\n\treturnIntermediateSteps: boolean = false,\n\tmemory?: BaseChatMemory,\n\tinput?: string,\n): Promise<AgentResult> {\n\tconst agentResult: AgentResult = {\n\t\toutput: '',\n\t};\n\n\tif (returnIntermediateSteps) {\n\t\tagentResult.intermediateSteps = [];\n\t}\n\n\tconst toolCalls: ToolCallRequest[] = [];\n\n\tctx.sendChunk('begin', itemIndex);\n\tfor await (const event of eventStream) {\n\t\t// Stream chat model tokens as they come in\n\t\tswitch (event.event) {\n\t\t\tcase 'on_chat_model_stream':\n\t\t\t\tconst chunk = event.data?.chunk as AIMessageChunk;\n\t\t\t\tif (chunk?.content) {\n\t\t\t\t\tconst chunkContent = chunk.content;\n\t\t\t\t\tlet chunkText = '';\n\t\t\t\t\tif (Array.isArray(chunkContent)) {\n\t\t\t\t\t\tfor (const message of chunkContent) {\n\t\t\t\t\t\t\tif (message?.type === 'text') {\n\t\t\t\t\t\t\t\tchunkText += (message as MessageContentText)?.text;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (typeof chunkContent === 'string') {\n\t\t\t\t\t\tchunkText = chunkContent;\n\t\t\t\t\t}\n\t\t\t\t\tctx.sendChunk('item', itemIndex, chunkText);\n\n\t\t\t\t\tagentResult.output += chunkText;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'on_chat_model_end':\n\t\t\t\t// Capture full LLM response with tool calls for intermediate steps\n\t\t\t\tif (event.data) {\n\t\t\t\t\tconst chatModelData = event.data as {\n\t\t\t\t\t\toutput?: { tool_calls?: ToolCall[]; content?: string };\n\t\t\t\t\t};\n\t\t\t\t\tconst output = chatModelData.output;\n\n\t\t\t\t\t// Check if this LLM response contains tool calls\n\t\t\t\t\tif (output?.tool_calls && output.tool_calls.length > 0) {\n\t\t\t\t\t\t// Collect tool calls for request building\n\t\t\t\t\t\tfor (const toolCall of output.tool_calls) {\n\t\t\t\t\t\t\ttoolCalls.push({\n\t\t\t\t\t\t\t\ttool: toolCall.name,\n\t\t\t\t\t\t\t\ttoolInput: toolCall.args,\n\t\t\t\t\t\t\t\ttoolCallId: toolCall.id || 'unknown',\n\t\t\t\t\t\t\t\ttype: toolCall.type || 'tool_call',\n\t\t\t\t\t\t\t\tlog:\n\t\t\t\t\t\t\t\t\toutput.content ||\n\t\t\t\t\t\t\t\t\t`Calling ${toolCall.name} with input: ${JSON.stringify(toolCall.args)}`,\n\t\t\t\t\t\t\t\tmessageLog: [output],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Also add to intermediate steps if needed\n\t\t\t\t\t\tif (returnIntermediateSteps) {\n\t\t\t\t\t\t\tfor (const toolCall of output.tool_calls) {\n\t\t\t\t\t\t\t\tagentResult.intermediateSteps!.push({\n\t\t\t\t\t\t\t\t\taction: {\n\t\t\t\t\t\t\t\t\t\ttool: toolCall.name,\n\t\t\t\t\t\t\t\t\t\ttoolInput: toolCall.args,\n\t\t\t\t\t\t\t\t\t\tlog:\n\t\t\t\t\t\t\t\t\t\t\toutput.content ||\n\t\t\t\t\t\t\t\t\t\t\t`Calling ${toolCall.name} with input: ${JSON.stringify(toolCall.args)}`,\n\t\t\t\t\t\t\t\t\t\tmessageLog: [output], // Include the full LLM response\n\t\t\t\t\t\t\t\t\t\ttoolCallId: toolCall.id || 'unknown',\n\t\t\t\t\t\t\t\t\t\ttype: toolCall.type || 'tool_call',\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'on_tool_end':\n\t\t\t\t// Capture tool execution results and match with action\n\t\t\t\tif (returnIntermediateSteps && event.data && agentResult.intermediateSteps!.length > 0) {\n\t\t\t\t\tconst toolData = event.data as { output?: string };\n\t\t\t\t\t// Find the matching intermediate step for this tool call\n\t\t\t\t\tconst matchingStep = agentResult.intermediateSteps!.find(\n\t\t\t\t\t\t(step) => !step.observation && step.action.tool === event.name,\n\t\t\t\t\t);\n\t\t\t\t\tif (matchingStep) {\n\t\t\t\t\t\tmatchingStep.observation = toolData.output || '';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tctx.sendChunk('end', itemIndex);\n\n\t// Save conversation to memory if memory is connected\n\tif (memory && input && agentResult.output) {\n\t\tawait memory.saveContext({ input }, { output: agentResult.output });\n\t}\n\n\t// Include collected tool calls in the result\n\tif (toolCalls.length > 0) {\n\t\tagentResult.toolCalls = toolCalls;\n\t}\n\n\treturn agentResult;\n}\n\nexport type RequestResponseMetadata = {\n\titemIndex?: number;\n\tpreviousRequests: ToolCallData[];\n};\n\ntype ToolCallData = {\n\taction: {\n\t\ttool: string;\n\t\ttoolInput: Record<string, unknown>;\n\t\tlog: string | number | true | object;\n\t\ttoolCallId: IDataObject | GenericValue | GenericValue[] | IDataObject[];\n\t\ttype: string | number | true | object;\n\t};\n\tobservation: string;\n};\n\nfunction 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(...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\t\t\t// Create a synthetic AI message for the messageLog\n\t\t\t// This represents the AI's decision to call the tool\n\t\t\tconst syntheticAIMessage = new AIMessage({\n\t\t\t\tcontent: `Calling ${tool.action.nodeName} with input: ${JSON.stringify(toolInput)}`,\n\t\t\t\ttool_calls: [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: (toolInput?.id as string) ?? 'reconstructed_call',\n\t\t\t\t\t\tname: nodeNameToToolName(tool.action.nodeName),\n\t\t\t\t\t\targs: toolInput,\n\t\t\t\t\t\ttype: 'tool_call',\n\t\t\t\t\t},\n\t\t\t\t],\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: (toolInput.input as IDataObject) || {},\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),\n\t\t\t};\n\n\t\t\tsteps.push(toolResult);\n\t\t}\n\t}\n\treturn steps;\n}\n\n/* -----------------------------------------------------------\n Main Executor Function\n----------------------------------------------------------- */\n/**\n * The main executor method for the Tools Agent.\n *\n * This function retrieves necessary components (model, memory, tools), prepares the prompt,\n * creates the agent, and processes each input item. The error handling for each item is also\n * managed here based on the node's continueOnFail setting.\n *\n * @param this Execute context. SupplyDataContext is passed when agent is as a tool\n *\n * @returns The array of execution data for all processed items\n */\nexport async function toolsAgentExecute(\n\tthis: IExecuteFunctions | ISupplyDataFunctions,\n\tresponse?: EngineResponse<RequestResponseMetadata>,\n): Promise<INodeExecutionData[][] | EngineRequest<RequestResponseMetadata>> {\n\tthis.logger.debug('Executing Tools Agent V3');\n\n\tconst returnData: INodeExecutionData[] = [];\n\tlet request: EngineRequest<RequestResponseMetadata> | undefined = undefined;\n\n\tconst items = this.getInputData();\n\tconst batchSize = this.getNodeParameter('options.batching.batchSize', 0, 1) as number;\n\tconst delayBetweenBatches = this.getNodeParameter(\n\t\t'options.batching.delayBetweenBatches',\n\t\t0,\n\t\t0,\n\t) as number;\n\tconst needsFallback = this.getNodeParameter('needsFallback', 0, false) as boolean;\n\tconst memory = await getOptionalMemory(this);\n\tconst model = await getChatModel(this, 0);\n\tassert(model, 'Please connect a model to the Chat Model input');\n\tconst fallbackModel = needsFallback ? await getChatModel(this, 1) : null;\n\n\tif (needsFallback && !fallbackModel) {\n\t\tthrow new NodeOperationError(\n\t\t\tthis.getNode(),\n\t\t\t'Please connect a model to the Fallback Model input or disable the fallback option',\n\t\t);\n\t}\n\n\tfor (let i = 0; i < items.length; i += batchSize) {\n\t\tconst batch = items.slice(i, i + batchSize);\n\t\tconst batchPromises = batch.map(async (_item, batchItemIndex) => {\n\t\t\tconst itemIndex = i + batchItemIndex;\n\n\t\t\tif (response && response?.metadata?.itemIndex === itemIndex) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst steps = buildSteps(response, itemIndex);\n\n\t\t\tconst input = getPromptInputByType({\n\t\t\t\tctx: this,\n\t\t\t\ti: itemIndex,\n\t\t\t\tinputKey: 'text',\n\t\t\t\tpromptTypeKey: 'promptType',\n\t\t\t});\n\t\t\tif (input === undefined) {\n\t\t\t\tthrow new NodeOperationError(this.getNode(), 'The \"text\" parameter is empty.');\n\t\t\t}\n\t\t\tconst outputParser = await getOptionalOutputParser(this, itemIndex);\n\t\t\tconst tools = await getTools(this, outputParser);\n\t\t\tconst options = this.getNodeParameter('options', itemIndex) as {\n\t\t\t\tsystemMessage?: string;\n\t\t\t\tmaxIterations?: number;\n\t\t\t\treturnIntermediateSteps?: boolean;\n\t\t\t\tpassthroughBinaryImages?: boolean;\n\t\t\t\tenableStreaming?: boolean;\n\t\t\t\tmaxTokensFromMemory?: number;\n\t\t\t};\n\n\t\t\tif (options.enableStreaming === undefined) {\n\t\t\t\toptions.enableStreaming = true;\n\t\t\t}\n\n\t\t\t// Prepare the prompt messages and prompt template.\n\t\t\tconst messages = await prepareMessages(this, itemIndex, {\n\t\t\t\tsystemMessage: options.systemMessage,\n\t\t\t\tpassthroughBinaryImages: options.passthroughBinaryImages ?? true,\n\t\t\t\toutputParser,\n\t\t\t});\n\t\t\tconst prompt: ChatPromptTemplate = preparePrompt(messages);\n\n\t\t\t// Create executors for primary and fallback models\n\t\t\tconst executor = createAgentSequence(\n\t\t\t\tmodel,\n\t\t\t\ttools,\n\t\t\t\tprompt,\n\t\t\t\toptions,\n\t\t\t\toutputParser,\n\t\t\t\tmemory,\n\t\t\t\tfallbackModel,\n\t\t\t);\n\t\t\t// Invoke with fallback logic\n\t\t\tconst invokeParams = {\n\t\t\t\tsteps,\n\t\t\t\tinput,\n\t\t\t\tsystem_message: options.systemMessage ?? SYSTEM_MESSAGE,\n\t\t\t\tformatting_instructions:\n\t\t\t\t\t'IMPORTANT: For your response to user, you MUST use the `format_final_json_response` tool with your complete answer formatted according to the required schema. Do not attempt to format the JSON manually - always use this tool. Your response will be rejected if it is not properly formatted through this tool. Only use this tool once you are ready to provide your final answer.',\n\t\t\t};\n\t\t\tconst executeOptions = { signal: this.getExecutionCancelSignal() };\n\n\t\t\t// Check if streaming is actually available\n\t\t\tconst isStreamingAvailable = 'isStreaming' in this ? this.isStreaming?.() : undefined;\n\n\t\t\tif (\n\t\t\t\t'isStreaming' in this &&\n\t\t\t\toptions.enableStreaming &&\n\t\t\t\tisStreamingAvailable &&\n\t\t\t\tthis.getNode().typeVersion >= 2.1\n\t\t\t) {\n\t\t\t\tlet chatHistory: BaseMessage[] | undefined = undefined;\n\t\t\t\tif (memory) {\n\t\t\t\t\t// Load memory variables to respect context window length\n\t\t\t\t\tchatHistory = await loadChatHistory(memory, model, options.maxTokensFromMemory);\n\t\t\t\t}\n\t\t\t\tconst eventStream = executor.streamEvents(\n\t\t\t\t\t{\n\t\t\t\t\t\t...invokeParams,\n\t\t\t\t\t\tchat_history: chatHistory,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tversion: 'v2',\n\t\t\t\t\t\t...executeOptions,\n\t\t\t\t\t},\n\t\t\t\t);\n\n\t\t\t\tconst result = await processEventStream(\n\t\t\t\t\tthis,\n\t\t\t\t\teventStream,\n\t\t\t\t\titemIndex,\n\t\t\t\t\toptions.returnIntermediateSteps,\n\t\t\t\t\tmemory,\n\t\t\t\t\tinput,\n\t\t\t\t);\n\n\t\t\t\t// If result contains tool calls, build the request object like the normal flow\n\t\t\t\tif (result.toolCalls && result.toolCalls.length > 0) {\n\t\t\t\t\tconst actions = await createEngineRequests(result.toolCalls, itemIndex, tools);\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tactions,\n\t\t\t\t\t\tmetadata: { previousRequests: buildSteps(response, itemIndex) },\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t} else {\n\t\t\t\t// Handle regular execution\n\t\t\t\tlet chatHistory: BaseMessage[] | undefined = undefined;\n\t\t\t\tif (memory) {\n\t\t\t\t\t// Load memory variables to respect context window length\n\t\t\t\t\tchatHistory = await loadChatHistory(memory, model, options.maxTokensFromMemory);\n\t\t\t\t}\n\t\t\t\tconst modelResponse = await executor.invoke({\n\t\t\t\t\t...invokeParams,\n\t\t\t\t\tchat_history: chatHistory,\n\t\t\t\t});\n\n\t\t\t\tif ('returnValues' in modelResponse) {\n\t\t\t\t\t// Save conversation to memory including any tool call context\n\t\t\t\t\tif (memory && input && modelResponse.returnValues.output) {\n\t\t\t\t\t\t// If there were tool calls in this conversation, include them in the context\n\t\t\t\t\t\tlet fullOutput = modelResponse.returnValues.output as string;\n\n\t\t\t\t\t\tif (steps.length > 0) {\n\t\t\t\t\t\t\t// Include tool call information in the conversation context\n\t\t\t\t\t\t\tconst toolContext = steps\n\t\t\t\t\t\t\t\t.map(\n\t\t\t\t\t\t\t\t\t(step) =>\n\t\t\t\t\t\t\t\t\t\t`Tool: ${step.action.tool}, Input: ${JSON.stringify(step.action.toolInput)}, Result: ${step.observation}`,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t.join('; ');\n\t\t\t\t\t\t\tfullOutput = `[Used tools: ${toolContext}] ${fullOutput}`;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tawait memory.saveContext({ input }, { output: fullOutput });\n\t\t\t\t\t}\n\t\t\t\t\t// Include intermediate steps if requested\n\t\t\t\t\tconst result = { ...modelResponse.returnValues };\n\t\t\t\t\tif (options.returnIntermediateSteps && steps.length > 0) {\n\t\t\t\t\t\tresult.intermediateSteps = steps;\n\t\t\t\t\t}\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\t// If response contains tool calls, we need to return this in the right format\n\t\t\t\tconst actions = await createEngineRequests(modelResponse, itemIndex, tools);\n\n\t\t\t\treturn {\n\t\t\t\t\tactions,\n\t\t\t\t\tmetadata: { previousRequests: buildSteps(response, itemIndex) },\n\t\t\t\t};\n\t\t\t}\n\t\t});\n\n\t\tconst batchResults = await Promise.allSettled(batchPromises);\n\t\t// This is only used to check if the output parser is connected\n\t\t// so we can parse the output if needed. Actual output parsing is done in the loop above\n\t\tconst outputParser = await getOptionalOutputParser(this, 0);\n\t\tbatchResults.forEach((result, index) => {\n\t\t\tconst itemIndex = i + index;\n\t\t\tif (result.status === 'rejected') {\n\t\t\t\tconst error = result.reason as Error;\n\t\t\t\tif (this.continueOnFail()) {\n\t\t\t\t\treturnData.push({\n\t\t\t\t\t\tjson: { error: error.message },\n\t\t\t\t\t\tpairedItem: { item: itemIndex },\n\t\t\t\t\t} as INodeExecutionData);\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new NodeOperationError(this.getNode(), error);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst response = result.value;\n\n\t\t\tif ('actions' in response) {\n\t\t\t\tif (!request) {\n\t\t\t\t\trequest = {\n\t\t\t\t\t\tactions: response.actions,\n\t\t\t\t\t\tmetadata: response.metadata,\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\trequest.actions.push(...response.actions);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// If memory and outputParser are connected, parse the output.\n\t\t\tif (memory && outputParser) {\n\t\t\t\tconst parsedOutput = jsonParse<{ output: Record<string, unknown> }>(\n\t\t\t\t\tresponse.output as string,\n\t\t\t\t);\n\t\t\t\tresponse.output = parsedOutput?.output ?? parsedOutput;\n\t\t\t}\n\n\t\t\t// Omit internal keys before returning the result.\n\t\t\tconst itemResult: INodeExecutionData = {\n\t\t\t\tjson: omit(\n\t\t\t\t\tresponse,\n\t\t\t\t\t'system_message',\n\t\t\t\t\t'formatting_instructions',\n\t\t\t\t\t'input',\n\t\t\t\t\t'chat_history',\n\t\t\t\t\t'agent_scratchpad',\n\t\t\t\t),\n\t\t\t\tpairedItem: { item: itemIndex },\n\t\t\t};\n\n\t\t\treturnData.push(itemResult);\n\t\t});\n\n\t\tif (i + batchSize < items.length && delayBetweenBatches > 0) {\n\t\t\tawait sleep(delayBetweenBatches);\n\t\t}\n\t}\n\t// Check if we have any Request objects (tool calls)\n\tif (request) {\n\t\treturn request;\n\t}\n\n\t// Otherwise return execution data\n\treturn [returnData];\n}\nasync function loadChatHistory(\n\tmemory: BaseChatMemory,\n\tmodel: BaseChatModel,\n\tmaxTokensFromMemory?: number,\n): Promise<BaseMessage[]> {\n\tconst memoryVariables = await memory.loadMemoryVariables({});\n\tlet chatHistory = memoryVariables['chat_history'] as BaseMessage[];\n\n\tif (maxTokensFromMemory) {\n\t\tchatHistory = await trimMessages(chatHistory, {\n\t\t\tstrategy: 'last',\n\t\t\tmaxTokens: maxTokensFromMemory,\n\t\t\ttokenCounter: model,\n\t\t\tincludeSystem: true,\n\t\t\tstartOn: 'human',\n\t\t\tallowPart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AACA;AAAA,MACD;AAGA,UAAI,UAAU,cAAc;AAC3B,cAAM,mBAAe;AAAA,UACpBA,UAAS;AAAA,QACV;AACA,QAAAA,UAAS,SAAS,cAAc,UAAU;AAAA,MAC3C;AAGA,YAAM,aAAiC;AAAA,QACtC,UAAM,YAAAC;AAAA,UACLD;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACD;AAAA,QACA,YAAY,EAAE,MAAM,UAAU;AAAA,MAC/B;AAEA,iBAAW,KAAK,UAAU;AAAA,IAC3B,CAAC;AAED,QAAI,IAAI,YAAY,MAAM,UAAU,sBAAsB,GAAG;AAC5D,gBAAM,2BAAM,mBAAmB;AAAA,IAChC;AAAA,EACD;AAEA,MAAI,SAAS;AACZ,WAAO;AAAA,EACR;AAGA,SAAO,CAAC,UAAU;AACnB;AACA,eAAe,gBACd,QACA,OACA,qBACyB;AACzB,QAAM,kBAAkB,MAAM,OAAO,oBAAoB,CAAC,CAAC;AAC3D,MAAI,cAAc,gBAAgB,cAAc;AAEhD,MAAI,qBAAqB;AACxB,kBAAc,UAAM,8BAAa,aAAa;AAAA,MAC7C,UAAU;AAAA,MACV,WAAW;AAAA,MACX,cAAc;AAAA,MACd,eAAe;AAAA,MACf,SAAS;AAAA,MACT,cAAc;AAAA,IACf,CAAC;AAAA,EACF;AAEA,SAAO;AACR;","names":["step","assert","outputParser","response","omit"]}
1
+ {"version":3,"sources":["../../../../../../../nodes/agents/Agent/agents/ToolsAgent/V3/execute.ts"],"sourcesContent":["import type { StreamEvent } from '@langchain/core/dist/tracers/event_stream';\nimport type { IterableReadableStream } from '@langchain/core/dist/utils/stream';\nimport type { BaseChatModel } from '@langchain/core/language_models/chat_models';\nimport type { AIMessageChunk, BaseMessage, MessageContentText } from '@langchain/core/messages';\nimport { AIMessage, trimMessages } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { ChatPromptTemplate } from '@langchain/core/prompts';\nimport { RunnableSequence } from '@langchain/core/runnables';\nimport { type AgentRunnableSequence, createToolCallingAgent } from 'langchain/agents';\nimport type { BaseChatMemory } from 'langchain/memory';\nimport type { DynamicStructuredTool, Tool } from 'langchain/tools';\nimport omit from 'lodash/omit';\nimport {\n\tjsonParse,\n\tNodeConnectionTypes,\n\tnodeNameToToolName,\n\tNodeOperationError,\n\tsleep,\n} from 'n8n-workflow';\nimport type {\n\tEngineRequest,\n\tGenericValue,\n\tIDataObject,\n\tIExecuteFunctions,\n\tINodeExecutionData,\n\tISupplyDataFunctions,\n\tEngineResponse,\n} from 'n8n-workflow';\nimport assert from 'node:assert';\n\nimport { getPromptInputByType } from '@utils/helpers';\nimport {\n\tgetOptionalOutputParser,\n\ttype N8nOutputParser,\n} from '@utils/output_parsers/N8nOutputParser';\n\nimport {\n\tfixEmptyContentMessage,\n\tgetAgentStepsParser,\n\tgetChatModel,\n\tgetOptionalMemory,\n\tgetTools,\n\tprepareMessages,\n\tpreparePrompt,\n} from '../common';\nimport { SYSTEM_MESSAGE } from '../prompt';\n\ntype ToolCallRequest = {\n\ttool: string;\n\ttoolInput: Record<string, unknown>;\n\ttoolCallId: string;\n\ttype?: string;\n\tlog?: string;\n\tmessageLog?: unknown[];\n};\n\nasync function createEngineRequests(\n\ttoolCalls: ToolCallRequest[],\n\titemIndex: number,\n\ttools: Array<DynamicStructuredTool | Tool>,\n) {\n\treturn toolCalls.map((toolCall) => {\n\t\t// First try to get from metadata (for toolkit tools)\n\t\tconst foundTool = tools.find((tool) => tool.name === toolCall.tool);\n\n\t\tif (!foundTool) return;\n\n\t\tconst nodeName = foundTool.metadata?.sourceNodeName;\n\n\t\t// For toolkit tools, include the tool name so the node knows which tool to execute\n\t\tconst input = foundTool.metadata?.isFromToolkit\n\t\t\t? { ...toolCall.toolInput, tool: toolCall.tool }\n\t\t\t: toolCall.toolInput;\n\n\t\treturn {\n\t\t\tnodeName,\n\t\t\tinput,\n\t\t\ttype: NodeConnectionTypes.AiTool,\n\t\t\tid: toolCall.toolCallId,\n\t\t\tmetadata: {\n\t\t\t\titemIndex,\n\t\t\t},\n\t\t};\n\t});\n}\n\n/**\n * Creates an agent executor with the given configuration\n */\nfunction createAgentSequence(\n\tmodel: BaseChatModel,\n\ttools: Array<DynamicStructuredTool | Tool>,\n\tprompt: ChatPromptTemplate,\n\t_options: { maxIterations?: number; returnIntermediateSteps?: boolean },\n\toutputParser?: N8nOutputParser,\n\tmemory?: BaseChatMemory,\n\tfallbackModel?: BaseChatModel | null,\n) {\n\tconst agent = createToolCallingAgent({\n\t\tllm: model,\n\t\ttools,\n\t\tprompt,\n\t\tstreamRunnable: false,\n\t});\n\n\tlet fallbackAgent: AgentRunnableSequence | undefined;\n\tif (fallbackModel) {\n\t\tfallbackAgent = createToolCallingAgent({\n\t\t\tllm: fallbackModel,\n\t\t\ttools,\n\t\t\tprompt,\n\t\t\tstreamRunnable: false,\n\t\t});\n\t}\n\tconst runnableAgent = RunnableSequence.from([\n\t\tfallbackAgent ? agent.withFallbacks([fallbackAgent]) : agent,\n\t\tgetAgentStepsParser(outputParser, memory),\n\t\tfixEmptyContentMessage,\n\t]) as AgentRunnableSequence;\n\n\trunnableAgent.singleAction = true;\n\trunnableAgent.streamRunnable = false;\n\n\treturn runnableAgent;\n}\n\ntype IntermediateStep = {\n\taction: {\n\t\ttool: string;\n\t\ttoolInput: Record<string, unknown>;\n\t\tlog: string;\n\t\tmessageLog: unknown[];\n\t\ttoolCallId: string;\n\t\ttype: string;\n\t};\n\tobservation?: string;\n};\n\ntype AgentResult = {\n\toutput: string;\n\tintermediateSteps?: IntermediateStep[];\n\ttoolCalls?: ToolCallRequest[];\n};\n\nasync function processEventStream(\n\tctx: IExecuteFunctions,\n\teventStream: IterableReadableStream<StreamEvent>,\n\titemIndex: number,\n\treturnIntermediateSteps: boolean = false,\n\tmemory?: BaseChatMemory,\n\tinput?: string,\n): Promise<AgentResult> {\n\tconst agentResult: AgentResult = {\n\t\toutput: '',\n\t};\n\n\tif (returnIntermediateSteps) {\n\t\tagentResult.intermediateSteps = [];\n\t}\n\n\tconst toolCalls: ToolCallRequest[] = [];\n\n\tctx.sendChunk('begin', itemIndex);\n\tfor await (const event of eventStream) {\n\t\t// Stream chat model tokens as they come in\n\t\tswitch (event.event) {\n\t\t\tcase 'on_chat_model_stream':\n\t\t\t\tconst chunk = event.data?.chunk as AIMessageChunk;\n\t\t\t\tif (chunk?.content) {\n\t\t\t\t\tconst chunkContent = chunk.content;\n\t\t\t\t\tlet chunkText = '';\n\t\t\t\t\tif (Array.isArray(chunkContent)) {\n\t\t\t\t\t\tfor (const message of chunkContent) {\n\t\t\t\t\t\t\tif (message?.type === 'text') {\n\t\t\t\t\t\t\t\tchunkText += (message as MessageContentText)?.text;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (typeof chunkContent === 'string') {\n\t\t\t\t\t\tchunkText = chunkContent;\n\t\t\t\t\t}\n\t\t\t\t\tctx.sendChunk('item', itemIndex, chunkText);\n\n\t\t\t\t\tagentResult.output += chunkText;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'on_chat_model_end':\n\t\t\t\t// Capture full LLM response with tool calls for intermediate steps\n\t\t\t\tif (event.data) {\n\t\t\t\t\tconst chatModelData = event.data as {\n\t\t\t\t\t\toutput?: { tool_calls?: ToolCall[]; content?: string };\n\t\t\t\t\t};\n\t\t\t\t\tconst output = chatModelData.output;\n\n\t\t\t\t\t// Check if this LLM response contains tool calls\n\t\t\t\t\tif (output?.tool_calls && output.tool_calls.length > 0) {\n\t\t\t\t\t\t// Collect tool calls for request building\n\t\t\t\t\t\tfor (const toolCall of output.tool_calls) {\n\t\t\t\t\t\t\ttoolCalls.push({\n\t\t\t\t\t\t\t\ttool: toolCall.name,\n\t\t\t\t\t\t\t\ttoolInput: toolCall.args,\n\t\t\t\t\t\t\t\ttoolCallId: toolCall.id || 'unknown',\n\t\t\t\t\t\t\t\ttype: toolCall.type || 'tool_call',\n\t\t\t\t\t\t\t\tlog:\n\t\t\t\t\t\t\t\t\toutput.content ||\n\t\t\t\t\t\t\t\t\t`Calling ${toolCall.name} with input: ${JSON.stringify(toolCall.args)}`,\n\t\t\t\t\t\t\t\tmessageLog: [output],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Also add to intermediate steps if needed\n\t\t\t\t\t\tif (returnIntermediateSteps) {\n\t\t\t\t\t\t\tfor (const toolCall of output.tool_calls) {\n\t\t\t\t\t\t\t\tagentResult.intermediateSteps!.push({\n\t\t\t\t\t\t\t\t\taction: {\n\t\t\t\t\t\t\t\t\t\ttool: toolCall.name,\n\t\t\t\t\t\t\t\t\t\ttoolInput: toolCall.args,\n\t\t\t\t\t\t\t\t\t\tlog:\n\t\t\t\t\t\t\t\t\t\t\toutput.content ||\n\t\t\t\t\t\t\t\t\t\t\t`Calling ${toolCall.name} with input: ${JSON.stringify(toolCall.args)}`,\n\t\t\t\t\t\t\t\t\t\tmessageLog: [output], // Include the full LLM response\n\t\t\t\t\t\t\t\t\t\ttoolCallId: toolCall.id || 'unknown',\n\t\t\t\t\t\t\t\t\t\ttype: toolCall.type || 'tool_call',\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'on_tool_end':\n\t\t\t\t// Capture tool execution results and match with action\n\t\t\t\tif (returnIntermediateSteps && event.data && agentResult.intermediateSteps!.length > 0) {\n\t\t\t\t\tconst toolData = event.data as { output?: string };\n\t\t\t\t\t// Find the matching intermediate step for this tool call\n\t\t\t\t\tconst matchingStep = agentResult.intermediateSteps!.find(\n\t\t\t\t\t\t(step) => !step.observation && step.action.tool === event.name,\n\t\t\t\t\t);\n\t\t\t\t\tif (matchingStep) {\n\t\t\t\t\t\tmatchingStep.observation = toolData.output || '';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tctx.sendChunk('end', itemIndex);\n\n\t// Save conversation to memory if memory is connected\n\tif (memory && input && agentResult.output) {\n\t\tawait memory.saveContext({ input }, { output: agentResult.output });\n\t}\n\n\t// Include collected tool calls in the result\n\tif (toolCalls.length > 0) {\n\t\tagentResult.toolCalls = toolCalls;\n\t}\n\n\treturn agentResult;\n}\n\nexport type RequestResponseMetadata = {\n\titemIndex?: number;\n\tpreviousRequests: ToolCallData[];\n\titerationCount?: number;\n};\n\ntype ToolCallData = {\n\taction: {\n\t\ttool: string;\n\t\ttoolInput: Record<string, unknown>;\n\t\tlog: string | number | true | object;\n\t\ttoolCallId: IDataObject | GenericValue | GenericValue[] | IDataObject[];\n\t\ttype: string | number | true | object;\n\t};\n\tobservation: string;\n};\n\nfunction 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(...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\t\t\t// Create a synthetic AI message for the messageLog\n\t\t\t// This represents the AI's decision to call the tool\n\t\t\tconst syntheticAIMessage = new AIMessage({\n\t\t\t\tcontent: `Calling ${tool.action.nodeName} with input: ${JSON.stringify(toolInput)}`,\n\t\t\t\ttool_calls: [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: (toolInput?.id as string) ?? 'reconstructed_call',\n\t\t\t\t\t\tname: nodeNameToToolName(tool.action.nodeName),\n\t\t\t\t\t\targs: toolInput,\n\t\t\t\t\t\ttype: 'tool_call',\n\t\t\t\t\t},\n\t\t\t\t],\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: (toolInput.input as IDataObject) || {},\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]?.[0]?.json ?? ''),\n\t\t\t};\n\n\t\t\tsteps.push(toolResult);\n\t\t}\n\t}\n\treturn steps;\n}\n\n/* -----------------------------------------------------------\n Main Executor Function\n----------------------------------------------------------- */\n/**\n * The main executor method for the Tools Agent.\n *\n * This function retrieves necessary components (model, memory, tools), prepares the prompt,\n * creates the agent, and processes each input item. The error handling for each item is also\n * managed here based on the node's continueOnFail setting.\n *\n * @param this Execute context. SupplyDataContext is passed when agent is as a tool\n *\n * @returns The array of execution data for all processed items\n */\nexport async function toolsAgentExecute(\n\tthis: IExecuteFunctions | ISupplyDataFunctions,\n\tresponse?: EngineResponse<RequestResponseMetadata>,\n): Promise<INodeExecutionData[][] | EngineRequest<RequestResponseMetadata>> {\n\tthis.logger.debug('Executing Tools Agent V3');\n\n\tconst returnData: INodeExecutionData[] = [];\n\tlet request: EngineRequest<RequestResponseMetadata> | undefined = undefined;\n\n\tconst items = this.getInputData();\n\tconst batchSize = this.getNodeParameter('options.batching.batchSize', 0, 1) as number;\n\tconst delayBetweenBatches = this.getNodeParameter(\n\t\t'options.batching.delayBetweenBatches',\n\t\t0,\n\t\t0,\n\t) as number;\n\tconst needsFallback = this.getNodeParameter('needsFallback', 0, false) as boolean;\n\tconst memory = await getOptionalMemory(this);\n\tconst model = await getChatModel(this, 0);\n\tassert(model, 'Please connect a model to the Chat Model input');\n\tconst fallbackModel = needsFallback ? await getChatModel(this, 1) : null;\n\n\tif (needsFallback && !fallbackModel) {\n\t\tthrow new NodeOperationError(\n\t\t\tthis.getNode(),\n\t\t\t'Please connect a model to the Fallback Model input or disable the fallback option',\n\t\t);\n\t}\n\n\tfor (let i = 0; i < items.length; i += batchSize) {\n\t\tconst batch = items.slice(i, i + batchSize);\n\t\tconst batchPromises = batch.map(async (_item, batchItemIndex) => {\n\t\t\tconst itemIndex = i + batchItemIndex;\n\n\t\t\tif (response && response?.metadata?.itemIndex === itemIndex) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst steps = buildSteps(response, itemIndex);\n\n\t\t\tconst input = getPromptInputByType({\n\t\t\t\tctx: this,\n\t\t\t\ti: itemIndex,\n\t\t\t\tinputKey: 'text',\n\t\t\t\tpromptTypeKey: 'promptType',\n\t\t\t});\n\t\t\tif (input === undefined) {\n\t\t\t\tthrow new NodeOperationError(this.getNode(), 'The \"text\" parameter is empty.');\n\t\t\t}\n\t\t\tconst outputParser = await getOptionalOutputParser(this, itemIndex);\n\t\t\tconst tools = await getTools(this, outputParser);\n\t\t\tconst options = this.getNodeParameter('options', itemIndex) as {\n\t\t\t\tsystemMessage?: string;\n\t\t\t\tmaxIterations?: number;\n\t\t\t\treturnIntermediateSteps?: boolean;\n\t\t\t\tpassthroughBinaryImages?: boolean;\n\t\t\t\tenableStreaming?: boolean;\n\t\t\t\tmaxTokensFromMemory?: number;\n\t\t\t};\n\n\t\t\tif (options.enableStreaming === undefined) {\n\t\t\t\toptions.enableStreaming = true;\n\t\t\t}\n\n\t\t\t// Prepare the prompt messages and prompt template.\n\t\t\tconst messages = await prepareMessages(this, itemIndex, {\n\t\t\t\tsystemMessage: options.systemMessage,\n\t\t\t\tpassthroughBinaryImages: options.passthroughBinaryImages ?? true,\n\t\t\t\toutputParser,\n\t\t\t});\n\t\t\tconst prompt: ChatPromptTemplate = preparePrompt(messages);\n\n\t\t\t// Create executors for primary and fallback models\n\t\t\tconst executor = createAgentSequence(\n\t\t\t\tmodel,\n\t\t\t\ttools,\n\t\t\t\tprompt,\n\t\t\t\toptions,\n\t\t\t\toutputParser,\n\t\t\t\tmemory,\n\t\t\t\tfallbackModel,\n\t\t\t);\n\t\t\t// Invoke with fallback logic\n\t\t\tconst invokeParams = {\n\t\t\t\tsteps,\n\t\t\t\tinput,\n\t\t\t\tsystem_message: options.systemMessage ?? SYSTEM_MESSAGE,\n\t\t\t\tformatting_instructions:\n\t\t\t\t\t'IMPORTANT: For your response to user, you MUST use the `format_final_json_response` tool with your complete answer formatted according to the required schema. Do not attempt to format the JSON manually - always use this tool. Your response will be rejected if it is not properly formatted through this tool. Only use this tool once you are ready to provide your final answer.',\n\t\t\t};\n\t\t\tconst executeOptions = { signal: this.getExecutionCancelSignal() };\n\n\t\t\t// Check if streaming is actually available\n\t\t\tconst isStreamingAvailable = 'isStreaming' in this ? this.isStreaming?.() : undefined;\n\n\t\t\tif (\n\t\t\t\t'isStreaming' in this &&\n\t\t\t\toptions.enableStreaming &&\n\t\t\t\tisStreamingAvailable &&\n\t\t\t\tthis.getNode().typeVersion >= 2.1\n\t\t\t) {\n\t\t\t\tlet chatHistory: BaseMessage[] | undefined = undefined;\n\t\t\t\tif (memory) {\n\t\t\t\t\t// Load memory variables to respect context window length\n\t\t\t\t\tchatHistory = await loadChatHistory(memory, model, options.maxTokensFromMemory);\n\t\t\t\t}\n\t\t\t\tconst eventStream = executor.streamEvents(\n\t\t\t\t\t{\n\t\t\t\t\t\t...invokeParams,\n\t\t\t\t\t\tchat_history: chatHistory,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tversion: 'v2',\n\t\t\t\t\t\t...executeOptions,\n\t\t\t\t\t},\n\t\t\t\t);\n\n\t\t\t\tconst result = await processEventStream(\n\t\t\t\t\tthis,\n\t\t\t\t\teventStream,\n\t\t\t\t\titemIndex,\n\t\t\t\t\toptions.returnIntermediateSteps,\n\t\t\t\t\tmemory,\n\t\t\t\t\tinput,\n\t\t\t\t);\n\n\t\t\t\t// If result contains tool calls, build the request object like the normal flow\n\t\t\t\tif (result.toolCalls && result.toolCalls.length > 0) {\n\t\t\t\t\tconst currentIteration = (response?.metadata?.iterationCount ?? 0) + 1;\n\n\t\t\t\t\t// Check if we've exceeded maxIterations\n\t\t\t\t\tif (options.maxIterations && currentIteration > options.maxIterations) {\n\t\t\t\t\t\tthrow new NodeOperationError(this.getNode(), 'Maximum iterations reached');\n\t\t\t\t\t}\n\n\t\t\t\t\tconst actions = await createEngineRequests(result.toolCalls, itemIndex, tools);\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tactions,\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\tpreviousRequests: buildSteps(response, itemIndex),\n\t\t\t\t\t\t\titerationCount: currentIteration,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t} else {\n\t\t\t\t// Handle regular execution\n\t\t\t\tlet chatHistory: BaseMessage[] | undefined = undefined;\n\t\t\t\tif (memory) {\n\t\t\t\t\t// Load memory variables to respect context window length\n\t\t\t\t\tchatHistory = await loadChatHistory(memory, model, options.maxTokensFromMemory);\n\t\t\t\t}\n\t\t\t\tconst modelResponse = await executor.invoke({\n\t\t\t\t\t...invokeParams,\n\t\t\t\t\tchat_history: chatHistory,\n\t\t\t\t});\n\n\t\t\t\tif ('returnValues' in modelResponse) {\n\t\t\t\t\t// Save conversation to memory including any tool call context\n\t\t\t\t\tif (memory && input && modelResponse.returnValues.output) {\n\t\t\t\t\t\t// If there were tool calls in this conversation, include them in the context\n\t\t\t\t\t\tlet fullOutput = modelResponse.returnValues.output as string;\n\n\t\t\t\t\t\tif (steps.length > 0) {\n\t\t\t\t\t\t\t// Include tool call information in the conversation context\n\t\t\t\t\t\t\tconst toolContext = steps\n\t\t\t\t\t\t\t\t.map(\n\t\t\t\t\t\t\t\t\t(step) =>\n\t\t\t\t\t\t\t\t\t\t`Tool: ${step.action.tool}, Input: ${JSON.stringify(step.action.toolInput)}, Result: ${step.observation}`,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t.join('; ');\n\t\t\t\t\t\t\tfullOutput = `[Used tools: ${toolContext}] ${fullOutput}`;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tawait memory.saveContext({ input }, { output: fullOutput });\n\t\t\t\t\t}\n\t\t\t\t\t// Include intermediate steps if requested\n\t\t\t\t\tconst result = { ...modelResponse.returnValues };\n\t\t\t\t\tif (options.returnIntermediateSteps && steps.length > 0) {\n\t\t\t\t\t\tresult.intermediateSteps = steps;\n\t\t\t\t\t}\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tconst currentIteration = (response?.metadata?.iterationCount ?? 0) + 1;\n\n\t\t\t\t// Check if we've exceeded maxIterations\n\t\t\t\tif (options.maxIterations && currentIteration > options.maxIterations) {\n\t\t\t\t\tthrow new NodeOperationError(this.getNode(), 'Maximum iterations reached');\n\t\t\t\t}\n\n\t\t\t\tconst actions = await createEngineRequests(modelResponse, itemIndex, tools);\n\n\t\t\t\treturn {\n\t\t\t\t\tactions,\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tpreviousRequests: buildSteps(response, itemIndex),\n\t\t\t\t\t\titerationCount: currentIteration,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t});\n\n\t\tconst batchResults = await Promise.allSettled(batchPromises);\n\t\t// This is only used to check if the output parser is connected\n\t\t// so we can parse the output if needed. Actual output parsing is done in the loop above\n\t\tconst outputParser = await getOptionalOutputParser(this, 0);\n\t\tbatchResults.forEach((result, index) => {\n\t\t\tconst itemIndex = i + index;\n\t\t\tif (result.status === 'rejected') {\n\t\t\t\tconst error = result.reason as Error;\n\t\t\t\tif (this.continueOnFail()) {\n\t\t\t\t\treturnData.push({\n\t\t\t\t\t\tjson: { error: error.message },\n\t\t\t\t\t\tpairedItem: { item: itemIndex },\n\t\t\t\t\t} as INodeExecutionData);\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new NodeOperationError(this.getNode(), error);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst response = result.value;\n\n\t\t\tif ('actions' in response) {\n\t\t\t\tif (!request) {\n\t\t\t\t\trequest = {\n\t\t\t\t\t\tactions: response.actions,\n\t\t\t\t\t\tmetadata: response.metadata,\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\trequest.actions.push(...response.actions);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// If memory and outputParser are connected, parse the output.\n\t\t\tif (memory && outputParser) {\n\t\t\t\tconst parsedOutput = jsonParse<{ output: Record<string, unknown> }>(\n\t\t\t\t\tresponse.output as string,\n\t\t\t\t);\n\t\t\t\tresponse.output = parsedOutput?.output ?? parsedOutput;\n\t\t\t}\n\n\t\t\t// Omit internal keys before returning the result.\n\t\t\tconst itemResult: INodeExecutionData = {\n\t\t\t\tjson: omit(\n\t\t\t\t\tresponse,\n\t\t\t\t\t'system_message',\n\t\t\t\t\t'formatting_instructions',\n\t\t\t\t\t'input',\n\t\t\t\t\t'chat_history',\n\t\t\t\t\t'agent_scratchpad',\n\t\t\t\t),\n\t\t\t\tpairedItem: { item: itemIndex },\n\t\t\t};\n\n\t\t\treturnData.push(itemResult);\n\t\t});\n\n\t\tif (i + batchSize < items.length && delayBetweenBatches > 0) {\n\t\t\tawait sleep(delayBetweenBatches);\n\t\t}\n\t}\n\t// Check if we have any Request objects (tool calls)\n\tif (request) {\n\t\treturn request;\n\t}\n\n\t// Otherwise return execution data\n\treturn [returnData];\n}\nasync function loadChatHistory(\n\tmemory: BaseChatMemory,\n\tmodel: BaseChatModel,\n\tmaxTokensFromMemory?: number,\n): Promise<BaseMessage[]> {\n\tconst memoryVariables = await memory.loadMemoryVariables({});\n\tlet chatHistory = memoryVariables['chat_history'] as BaseMessage[];\n\n\tif (maxTokensFromMemory) {\n\t\tchatHistory = await trimMessages(chatHistory, {\n\t\t\tstrategy: 'last',\n\t\t\tmaxTokens: maxTokensFromMemory,\n\t\t\ttokenCounter: model,\n\t\t\tincludeSystem: true,\n\t\t\tstartOn: 'human',\n\t\t\tallowPartial: true,\n\t\t});\n\t}\n\n\treturn chatHistory;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,sBAAwC;AAGxC,uBAAiC;AACjC,oBAAmE;AAGnE,kBAAiB;AACjB,0BAMO;AAUP,yBAAmB;AAEnB,qBAAqC;AACrC,6BAGO;AAEP,oBAQO;AACP,oBAA+B;AAW/B,eAAe,qBACd,WACA,WACA,OACC;AACD,SAAO,UAAU,IAAI,CAAC,aAAa;AAElC,UAAM,YAAY,MAAM,KAAK,CAAC,SAAS,KAAK,SAAS,SAAS,IAAI;AAElE,QAAI,CAAC,UAAW;AAEhB,UAAM,WAAW,UAAU,UAAU;AAGrC,UAAM,QAAQ,UAAU,UAAU,gBAC/B,EAAE,GAAG,SAAS,WAAW,MAAM,SAAS,KAAK,IAC7C,SAAS;AAEZ,WAAO;AAAA,MACN;AAAA,MACA;AAAA,MACA,MAAM,wCAAoB;AAAA,MAC1B,IAAI,SAAS;AAAA,MACb,UAAU;AAAA,QACT;AAAA,MACD;AAAA,IACD;AAAA,EACD,CAAC;AACF;AAKA,SAAS,oBACR,OACA,OACA,QACA,UACA,cACA,QACA,eACC;AACD,QAAM,YAAQ,sCAAuB;AAAA,IACpC,KAAK;AAAA,IACL;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,EACjB,CAAC;AAED,MAAI;AACJ,MAAI,eAAe;AAClB,wBAAgB,sCAAuB;AAAA,MACtC,KAAK;AAAA,MACL;AAAA,MACA;AAAA,MACA,gBAAgB;AAAA,IACjB,CAAC;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,QACA,OACA,qBACyB;AACzB,QAAM,kBAAkB,MAAM,OAAO,oBAAoB,CAAC,CAAC;AAC3D,MAAI,cAAc,gBAAgB,cAAc;AAEhD,MAAI,qBAAqB;AACxB,kBAAc,UAAM,8BAAa,aAAa;AAAA,MAC7C,UAAU;AAAA,MACV,WAAW;AAAA,MACX,cAAc;AAAA,MACd,eAAe;AAAA,MACf,SAAS;AAAA,MACT,cAAc;AAAA,IACf,CAAC;AAAA,EACF;AAEA,SAAO;AACR;","names":["step","assert","outputParser","response","omit"]}
@@ -159,8 +159,8 @@ class LmChatAnthropic {
159
159
  type: "resourceLocator",
160
160
  default: {
161
161
  mode: "list",
162
- value: "claude-sonnet-4-20250514",
163
- cachedResultName: "Claude 4 Sonnet"
162
+ value: "claude-sonnet-4-5-20250929",
163
+ cachedResultName: "Claude Sonnet 4.5"
164
164
  },
165
165
  required: true,
166
166
  modes: [
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../nodes/llms/LMChatAnthropic/LmChatAnthropic.node.ts"],"sourcesContent":["import { ChatAnthropic } from '@langchain/anthropic';\nimport type { LLMResult } from '@langchain/core/outputs';\nimport { getProxyAgent } from '@utils/httpProxyAgent';\nimport { getConnectionHintNoticeField } from '@utils/sharedFields';\nimport {\n\tNodeConnectionTypes,\n\ttype INodePropertyOptions,\n\ttype INodeProperties,\n\ttype ISupplyDataFunctions,\n\ttype INodeType,\n\ttype INodeTypeDescription,\n\ttype SupplyData,\n} from 'n8n-workflow';\n\nimport { makeN8nLlmFailedAttemptHandler } from '../n8nLlmFailedAttemptHandler';\nimport { N8nLlmTracing } from '../N8nLlmTracing';\nimport { searchModels } from './methods/searchModels';\n\nconst modelField: INodeProperties = {\n\tdisplayName: 'Model',\n\tname: 'model',\n\ttype: 'options',\n\t// eslint-disable-next-line n8n-nodes-base/node-param-options-type-unsorted-items\n\toptions: [\n\t\t{\n\t\t\tname: 'Claude 3.5 Sonnet(20241022)',\n\t\t\tvalue: 'claude-3-5-sonnet-20241022',\n\t\t},\n\t\t{\n\t\t\tname: 'Claude 3 Opus(20240229)',\n\t\t\tvalue: 'claude-3-opus-20240229',\n\t\t},\n\t\t{\n\t\t\tname: 'Claude 3.5 Sonnet(20240620)',\n\t\t\tvalue: 'claude-3-5-sonnet-20240620',\n\t\t},\n\t\t{\n\t\t\tname: 'Claude 3 Sonnet(20240229)',\n\t\t\tvalue: 'claude-3-sonnet-20240229',\n\t\t},\n\t\t{\n\t\t\tname: 'Claude 3.5 Haiku(20241022)',\n\t\t\tvalue: 'claude-3-5-haiku-20241022',\n\t\t},\n\t\t{\n\t\t\tname: 'Claude 3 Haiku(20240307)',\n\t\t\tvalue: 'claude-3-haiku-20240307',\n\t\t},\n\t\t{\n\t\t\tname: 'LEGACY: Claude 2',\n\t\t\tvalue: 'claude-2',\n\t\t},\n\t\t{\n\t\t\tname: 'LEGACY: Claude 2.1',\n\t\t\tvalue: 'claude-2.1',\n\t\t},\n\t\t{\n\t\t\tname: 'LEGACY: Claude Instant 1.2',\n\t\t\tvalue: 'claude-instant-1.2',\n\t\t},\n\t\t{\n\t\t\tname: 'LEGACY: Claude Instant 1',\n\t\t\tvalue: 'claude-instant-1',\n\t\t},\n\t],\n\tdescription:\n\t\t'The model which will generate the completion. <a href=\"https://docs.anthropic.com/claude/docs/models-overview\">Learn more</a>.',\n\tdefault: 'claude-2',\n};\n\nconst MIN_THINKING_BUDGET = 1024;\nconst DEFAULT_MAX_TOKENS = 4096;\nexport class LmChatAnthropic implements INodeType {\n\tmethods = {\n\t\tlistSearch: {\n\t\t\tsearchModels,\n\t\t},\n\t};\n\n\tdescription: INodeTypeDescription = {\n\t\tdisplayName: 'Anthropic Chat Model',\n\n\t\tname: 'lmChatAnthropic',\n\t\ticon: 'file:anthropic.svg',\n\t\tgroup: ['transform'],\n\t\tversion: [1, 1.1, 1.2, 1.3],\n\t\tdefaultVersion: 1.3,\n\t\tdescription: 'Language Model Anthropic',\n\t\tdefaults: {\n\t\t\tname: 'Anthropic Chat Model',\n\t\t},\n\t\tcodex: {\n\t\t\tcategories: ['AI'],\n\t\t\tsubcategories: {\n\t\t\t\tAI: ['Language Models', 'Root Nodes'],\n\t\t\t\t'Language Models': ['Chat Models (Recommended)'],\n\t\t\t},\n\t\t\tresources: {\n\t\t\t\tprimaryDocumentation: [\n\t\t\t\t\t{\n\t\t\t\t\t\turl: 'https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.lmchatanthropic/',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\talias: ['claude', 'sonnet', 'opus'],\n\t\t},\n\n\t\tinputs: [],\n\n\t\toutputs: [NodeConnectionTypes.AiLanguageModel],\n\t\toutputNames: ['Model'],\n\t\tcredentials: [\n\t\t\t{\n\t\t\t\tname: 'anthropicApi',\n\t\t\t\trequired: true,\n\t\t\t},\n\t\t],\n\t\tproperties: [\n\t\t\tgetConnectionHintNoticeField([NodeConnectionTypes.AiChain, NodeConnectionTypes.AiChain]),\n\t\t\t{\n\t\t\t\t...modelField,\n\t\t\t\tdisplayOptions: {\n\t\t\t\t\tshow: {\n\t\t\t\t\t\t'@version': [1],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t...modelField,\n\t\t\t\tdefault: 'claude-3-sonnet-20240229',\n\t\t\t\tdisplayOptions: {\n\t\t\t\t\tshow: {\n\t\t\t\t\t\t'@version': [1.1],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t...modelField,\n\t\t\t\tdefault: 'claude-3-5-sonnet-20240620',\n\t\t\t\toptions: (modelField.options ?? []).filter(\n\t\t\t\t\t(o): o is INodePropertyOptions => 'name' in o && !o.name.toString().startsWith('LEGACY'),\n\t\t\t\t),\n\t\t\t\tdisplayOptions: {\n\t\t\t\t\tshow: {\n\t\t\t\t\t\t'@version': [{ _cnd: { lte: 1.2 } }],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tdisplayName: 'Model',\n\t\t\t\tname: 'model',\n\t\t\t\ttype: 'resourceLocator',\n\t\t\t\tdefault: {\n\t\t\t\t\tmode: 'list',\n\t\t\t\t\tvalue: 'claude-sonnet-4-20250514',\n\t\t\t\t\tcachedResultName: 'Claude 4 Sonnet',\n\t\t\t\t},\n\t\t\t\trequired: true,\n\t\t\t\tmodes: [\n\t\t\t\t\t{\n\t\t\t\t\t\tdisplayName: 'From List',\n\t\t\t\t\t\tname: 'list',\n\t\t\t\t\t\ttype: 'list',\n\t\t\t\t\t\tplaceholder: 'Select a model...',\n\t\t\t\t\t\ttypeOptions: {\n\t\t\t\t\t\t\tsearchListMethod: 'searchModels',\n\t\t\t\t\t\t\tsearchable: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tdisplayName: 'ID',\n\t\t\t\t\t\tname: 'id',\n\t\t\t\t\t\ttype: 'string',\n\t\t\t\t\t\tplaceholder: 'Claude Sonnet',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdescription:\n\t\t\t\t\t'The model. Choose from the list, or specify an ID. <a href=\"https://docs.anthropic.com/claude/docs/models-overview\">Learn more</a>.',\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\t{\n\t\t\t\tdisplayName: 'Options',\n\t\t\t\tname: 'options',\n\t\t\t\tplaceholder: 'Add Option',\n\t\t\t\tdescription: 'Additional options to add',\n\t\t\t\ttype: 'collection',\n\t\t\t\tdefault: {},\n\t\t\t\toptions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tdisplayName: 'Maximum Number of Tokens',\n\t\t\t\t\t\tname: 'maxTokensToSample',\n\t\t\t\t\t\tdefault: DEFAULT_MAX_TOKENS,\n\t\t\t\t\t\tdescription: 'The maximum number of tokens to generate in the completion',\n\t\t\t\t\t\ttype: 'number',\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tdisplayName: 'Sampling Temperature',\n\t\t\t\t\t\tname: 'temperature',\n\t\t\t\t\t\tdefault: 0.7,\n\t\t\t\t\t\ttypeOptions: { maxValue: 1, minValue: 0, numberPrecision: 1 },\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t'Controls randomness: Lowering results in less random completions. As the temperature approaches zero, the model will become deterministic and repetitive.',\n\t\t\t\t\t\ttype: 'number',\n\t\t\t\t\t\tdisplayOptions: {\n\t\t\t\t\t\t\thide: {\n\t\t\t\t\t\t\t\tthinking: [true],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tdisplayName: 'Top K',\n\t\t\t\t\t\tname: 'topK',\n\t\t\t\t\t\tdefault: -1,\n\t\t\t\t\t\ttypeOptions: { maxValue: 1, minValue: -1, numberPrecision: 1 },\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t'Used to remove \"long tail\" low probability responses. Defaults to -1, which disables it.',\n\t\t\t\t\t\ttype: 'number',\n\t\t\t\t\t\tdisplayOptions: {\n\t\t\t\t\t\t\thide: {\n\t\t\t\t\t\t\t\tthinking: [true],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tdisplayName: 'Top P',\n\t\t\t\t\t\tname: 'topP',\n\t\t\t\t\t\tdefault: 1,\n\t\t\t\t\t\ttypeOptions: { maxValue: 1, minValue: 0, numberPrecision: 1 },\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t'Controls diversity via nucleus sampling: 0.5 means half of all likelihood-weighted options are considered. We generally recommend altering this or temperature but not both.',\n\t\t\t\t\t\ttype: 'number',\n\t\t\t\t\t\tdisplayOptions: {\n\t\t\t\t\t\t\thide: {\n\t\t\t\t\t\t\t\tthinking: [true],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tdisplayName: 'Enable Thinking',\n\t\t\t\t\t\tname: 'thinking',\n\t\t\t\t\t\ttype: 'boolean',\n\t\t\t\t\t\tdefault: false,\n\t\t\t\t\t\tdescription: 'Whether to enable thinking mode for the model',\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tdisplayName: 'Thinking Budget (Tokens)',\n\t\t\t\t\t\tname: 'thinkingBudget',\n\t\t\t\t\t\ttype: 'number',\n\t\t\t\t\t\tdefault: MIN_THINKING_BUDGET,\n\t\t\t\t\t\tdescription: 'The maximum number of tokens to use for thinking',\n\t\t\t\t\t\tdisplayOptions: {\n\t\t\t\t\t\t\tshow: {\n\t\t\t\t\t\t\t\tthinking: [true],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t],\n\t};\n\n\tasync supplyData(this: ISupplyDataFunctions, itemIndex: number): Promise<SupplyData> {\n\t\tconst credentials = await this.getCredentials<{\n\t\t\turl?: string;\n\t\t\tapiKey?: string;\n\t\t\theader?: boolean;\n\t\t\theaderName?: string;\n\t\t\theaderValue?: string;\n\t\t}>('anthropicApi');\n\t\tconst baseURL = credentials.url ?? 'https://api.anthropic.com';\n\t\tconst version = this.getNode().typeVersion;\n\t\tconst modelName =\n\t\t\tversion >= 1.3\n\t\t\t\t? (this.getNodeParameter('model.value', itemIndex) as string)\n\t\t\t\t: (this.getNodeParameter('model', itemIndex) as string);\n\n\t\tconst options = this.getNodeParameter('options', itemIndex, {}) as {\n\t\t\tmaxTokensToSample?: number;\n\t\t\ttemperature: number;\n\t\t\ttopK?: number;\n\t\t\ttopP?: number;\n\t\t\tthinking?: boolean;\n\t\t\tthinkingBudget?: number;\n\t\t};\n\t\tlet invocationKwargs = {};\n\n\t\tconst tokensUsageParser = (result: LLMResult) => {\n\t\t\tconst usage = (result?.llmOutput?.usage as {\n\t\t\t\tinput_tokens: number;\n\t\t\t\toutput_tokens: number;\n\t\t\t}) ?? {\n\t\t\t\tinput_tokens: 0,\n\t\t\t\toutput_tokens: 0,\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tcompletionTokens: usage.output_tokens,\n\t\t\t\tpromptTokens: usage.input_tokens,\n\t\t\t\ttotalTokens: usage.input_tokens + usage.output_tokens,\n\t\t\t};\n\t\t};\n\n\t\tif (options.thinking) {\n\t\t\tinvocationKwargs = {\n\t\t\t\tthinking: {\n\t\t\t\t\ttype: 'enabled',\n\t\t\t\t\t// If thinking is enabled, we need to set a budget.\n\t\t\t\t\t// We fallback to 1024 as that is the minimum\n\t\t\t\t\tbudget_tokens: options.thinkingBudget ?? MIN_THINKING_BUDGET,\n\t\t\t\t},\n\t\t\t\t// The default Langchain max_tokens is -1 (no limit) but Anthropic requires a number\n\t\t\t\t// higher than budget_tokens\n\t\t\t\tmax_tokens: options.maxTokensToSample ?? DEFAULT_MAX_TOKENS,\n\t\t\t\t// These need to be unset when thinking is enabled.\n\t\t\t\t// Because the invocationKwargs will override the model options\n\t\t\t\t// we can pass options to the model and then override them here\n\t\t\t\ttop_k: undefined,\n\t\t\t\ttop_p: undefined,\n\t\t\t\ttemperature: undefined,\n\t\t\t};\n\t\t}\n\n\t\tconst clientOptions: {\n\t\t\tfetchOptions?: { dispatcher: any };\n\t\t\tdefaultHeaders?: Record<string, string>;\n\t\t} = {\n\t\t\tfetchOptions: {\n\t\t\t\tdispatcher: getProxyAgent(baseURL),\n\t\t\t},\n\t\t};\n\n\t\tif (\n\t\t\tcredentials.header &&\n\t\t\ttypeof credentials.headerName === 'string' &&\n\t\t\tcredentials.headerName &&\n\t\t\ttypeof credentials.headerValue === 'string'\n\t\t) {\n\t\t\tclientOptions.defaultHeaders = {\n\t\t\t\t[credentials.headerName]: credentials.headerValue,\n\t\t\t};\n\t\t}\n\n\t\tconst model = new ChatAnthropic({\n\t\t\tanthropicApiKey: credentials.apiKey,\n\t\t\tmodel: modelName,\n\t\t\tanthropicApiUrl: baseURL,\n\t\t\tmaxTokens: options.maxTokensToSample,\n\t\t\ttemperature: options.temperature,\n\t\t\ttopK: options.topK,\n\t\t\ttopP: options.topP,\n\t\t\tcallbacks: [new N8nLlmTracing(this, { tokensUsageParser })],\n\t\t\tonFailedAttempt: makeN8nLlmFailedAttemptHandler(this),\n\t\t\tinvocationKwargs,\n\t\t\tclientOptions,\n\t\t});\n\n\t\t// Some Anthropic models do not support Langchain default of -1 for topP so we need to unset it\n\t\tif (options.topP === undefined) {\n\t\t\tdelete model.topP;\n\t\t}\n\n\t\t// If topP is set to a value and temperature is not, unset default Langchain temperature\n\t\tif (options.topP !== undefined && options.temperature === undefined) {\n\t\t\tdelete model.temperature;\n\t\t}\n\n\t\treturn {\n\t\t\tresponse: model,\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAA8B;AAE9B,4BAA8B;AAC9B,0BAA6C;AAC7C,0BAQO;AAEP,wCAA+C;AAC/C,2BAA8B;AAC9B,0BAA6B;AAE7B,MAAM,aAA8B;AAAA,EACnC,aAAa;AAAA,EACb,MAAM;AAAA,EACN,MAAM;AAAA;AAAA,EAEN,SAAS;AAAA,IACR;AAAA,MACC,MAAM;AAAA,MACN,OAAO;AAAA,IACR;AAAA,IACA;AAAA,MACC,MAAM;AAAA,MACN,OAAO;AAAA,IACR;AAAA,IACA;AAAA,MACC,MAAM;AAAA,MACN,OAAO;AAAA,IACR;AAAA,IACA;AAAA,MACC,MAAM;AAAA,MACN,OAAO;AAAA,IACR;AAAA,IACA;AAAA,MACC,MAAM;AAAA,MACN,OAAO;AAAA,IACR;AAAA,IACA;AAAA,MACC,MAAM;AAAA,MACN,OAAO;AAAA,IACR;AAAA,IACA;AAAA,MACC,MAAM;AAAA,MACN,OAAO;AAAA,IACR;AAAA,IACA;AAAA,MACC,MAAM;AAAA,MAC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AAA,MACd,WAAW,CAAC,IAAI,mCAAc,MAAM,EAAE,kBAAkB,CAAC,CAAC;AAAA,MAC1D,qBAAiB,kEAA+B,IAAI;AAAA,MACpD;AAAA,MACA;AAAA,IACD,CAAC;AAGD,QAAI,QAAQ,SAAS,QAAW;AAC/B,aAAO,MAAM;AAAA,IACd;AAGA,QAAI,QAAQ,SAAS,UAAa,QAAQ,gBAAgB,QAAW;AACpE,aAAO,MAAM;AAAA,IACd;AAEA,WAAO;AAAA,MACN,UAAU;AAAA,IACX;AAAA,EACD;AACD;","names":[]}
1
+ {"version":3,"sources":["../../../../nodes/llms/LMChatAnthropic/LmChatAnthropic.node.ts"],"sourcesContent":["import { ChatAnthropic } from '@langchain/anthropic';\nimport type { LLMResult } from '@langchain/core/outputs';\nimport { getProxyAgent } from '@utils/httpProxyAgent';\nimport { getConnectionHintNoticeField } from '@utils/sharedFields';\nimport {\n\tNodeConnectionTypes,\n\ttype INodePropertyOptions,\n\ttype INodeProperties,\n\ttype ISupplyDataFunctions,\n\ttype INodeType,\n\ttype INodeTypeDescription,\n\ttype SupplyData,\n} from 'n8n-workflow';\n\nimport { makeN8nLlmFailedAttemptHandler } from '../n8nLlmFailedAttemptHandler';\nimport { N8nLlmTracing } from '../N8nLlmTracing';\nimport { searchModels } from './methods/searchModels';\n\nconst modelField: INodeProperties = {\n\tdisplayName: 'Model',\n\tname: 'model',\n\ttype: 'options',\n\t// eslint-disable-next-line n8n-nodes-base/node-param-options-type-unsorted-items\n\toptions: [\n\t\t{\n\t\t\tname: 'Claude 3.5 Sonnet(20241022)',\n\t\t\tvalue: 'claude-3-5-sonnet-20241022',\n\t\t},\n\t\t{\n\t\t\tname: 'Claude 3 Opus(20240229)',\n\t\t\tvalue: 'claude-3-opus-20240229',\n\t\t},\n\t\t{\n\t\t\tname: 'Claude 3.5 Sonnet(20240620)',\n\t\t\tvalue: 'claude-3-5-sonnet-20240620',\n\t\t},\n\t\t{\n\t\t\tname: 'Claude 3 Sonnet(20240229)',\n\t\t\tvalue: 'claude-3-sonnet-20240229',\n\t\t},\n\t\t{\n\t\t\tname: 'Claude 3.5 Haiku(20241022)',\n\t\t\tvalue: 'claude-3-5-haiku-20241022',\n\t\t},\n\t\t{\n\t\t\tname: 'Claude 3 Haiku(20240307)',\n\t\t\tvalue: 'claude-3-haiku-20240307',\n\t\t},\n\t\t{\n\t\t\tname: 'LEGACY: Claude 2',\n\t\t\tvalue: 'claude-2',\n\t\t},\n\t\t{\n\t\t\tname: 'LEGACY: Claude 2.1',\n\t\t\tvalue: 'claude-2.1',\n\t\t},\n\t\t{\n\t\t\tname: 'LEGACY: Claude Instant 1.2',\n\t\t\tvalue: 'claude-instant-1.2',\n\t\t},\n\t\t{\n\t\t\tname: 'LEGACY: Claude Instant 1',\n\t\t\tvalue: 'claude-instant-1',\n\t\t},\n\t],\n\tdescription:\n\t\t'The model which will generate the completion. <a href=\"https://docs.anthropic.com/claude/docs/models-overview\">Learn more</a>.',\n\tdefault: 'claude-2',\n};\n\nconst MIN_THINKING_BUDGET = 1024;\nconst DEFAULT_MAX_TOKENS = 4096;\nexport class LmChatAnthropic implements INodeType {\n\tmethods = {\n\t\tlistSearch: {\n\t\t\tsearchModels,\n\t\t},\n\t};\n\n\tdescription: INodeTypeDescription = {\n\t\tdisplayName: 'Anthropic Chat Model',\n\n\t\tname: 'lmChatAnthropic',\n\t\ticon: 'file:anthropic.svg',\n\t\tgroup: ['transform'],\n\t\tversion: [1, 1.1, 1.2, 1.3],\n\t\tdefaultVersion: 1.3,\n\t\tdescription: 'Language Model Anthropic',\n\t\tdefaults: {\n\t\t\tname: 'Anthropic Chat Model',\n\t\t},\n\t\tcodex: {\n\t\t\tcategories: ['AI'],\n\t\t\tsubcategories: {\n\t\t\t\tAI: ['Language Models', 'Root Nodes'],\n\t\t\t\t'Language Models': ['Chat Models (Recommended)'],\n\t\t\t},\n\t\t\tresources: {\n\t\t\t\tprimaryDocumentation: [\n\t\t\t\t\t{\n\t\t\t\t\t\turl: 'https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.lmchatanthropic/',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\talias: ['claude', 'sonnet', 'opus'],\n\t\t},\n\n\t\tinputs: [],\n\n\t\toutputs: [NodeConnectionTypes.AiLanguageModel],\n\t\toutputNames: ['Model'],\n\t\tcredentials: [\n\t\t\t{\n\t\t\t\tname: 'anthropicApi',\n\t\t\t\trequired: true,\n\t\t\t},\n\t\t],\n\t\tproperties: [\n\t\t\tgetConnectionHintNoticeField([NodeConnectionTypes.AiChain, NodeConnectionTypes.AiChain]),\n\t\t\t{\n\t\t\t\t...modelField,\n\t\t\t\tdisplayOptions: {\n\t\t\t\t\tshow: {\n\t\t\t\t\t\t'@version': [1],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t...modelField,\n\t\t\t\tdefault: 'claude-3-sonnet-20240229',\n\t\t\t\tdisplayOptions: {\n\t\t\t\t\tshow: {\n\t\t\t\t\t\t'@version': [1.1],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t...modelField,\n\t\t\t\tdefault: 'claude-3-5-sonnet-20240620',\n\t\t\t\toptions: (modelField.options ?? []).filter(\n\t\t\t\t\t(o): o is INodePropertyOptions => 'name' in o && !o.name.toString().startsWith('LEGACY'),\n\t\t\t\t),\n\t\t\t\tdisplayOptions: {\n\t\t\t\t\tshow: {\n\t\t\t\t\t\t'@version': [{ _cnd: { lte: 1.2 } }],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tdisplayName: 'Model',\n\t\t\t\tname: 'model',\n\t\t\t\ttype: 'resourceLocator',\n\t\t\t\tdefault: {\n\t\t\t\t\tmode: 'list',\n\t\t\t\t\tvalue: 'claude-sonnet-4-5-20250929',\n\t\t\t\t\tcachedResultName: 'Claude Sonnet 4.5',\n\t\t\t\t},\n\t\t\t\trequired: true,\n\t\t\t\tmodes: [\n\t\t\t\t\t{\n\t\t\t\t\t\tdisplayName: 'From List',\n\t\t\t\t\t\tname: 'list',\n\t\t\t\t\t\ttype: 'list',\n\t\t\t\t\t\tplaceholder: 'Select a model...',\n\t\t\t\t\t\ttypeOptions: {\n\t\t\t\t\t\t\tsearchListMethod: 'searchModels',\n\t\t\t\t\t\t\tsearchable: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tdisplayName: 'ID',\n\t\t\t\t\t\tname: 'id',\n\t\t\t\t\t\ttype: 'string',\n\t\t\t\t\t\tplaceholder: 'Claude Sonnet',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdescription:\n\t\t\t\t\t'The model. Choose from the list, or specify an ID. <a href=\"https://docs.anthropic.com/claude/docs/models-overview\">Learn more</a>.',\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\t{\n\t\t\t\tdisplayName: 'Options',\n\t\t\t\tname: 'options',\n\t\t\t\tplaceholder: 'Add Option',\n\t\t\t\tdescription: 'Additional options to add',\n\t\t\t\ttype: 'collection',\n\t\t\t\tdefault: {},\n\t\t\t\toptions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tdisplayName: 'Maximum Number of Tokens',\n\t\t\t\t\t\tname: 'maxTokensToSample',\n\t\t\t\t\t\tdefault: DEFAULT_MAX_TOKENS,\n\t\t\t\t\t\tdescription: 'The maximum number of tokens to generate in the completion',\n\t\t\t\t\t\ttype: 'number',\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tdisplayName: 'Sampling Temperature',\n\t\t\t\t\t\tname: 'temperature',\n\t\t\t\t\t\tdefault: 0.7,\n\t\t\t\t\t\ttypeOptions: { maxValue: 1, minValue: 0, numberPrecision: 1 },\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t'Controls randomness: Lowering results in less random completions. As the temperature approaches zero, the model will become deterministic and repetitive.',\n\t\t\t\t\t\ttype: 'number',\n\t\t\t\t\t\tdisplayOptions: {\n\t\t\t\t\t\t\thide: {\n\t\t\t\t\t\t\t\tthinking: [true],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tdisplayName: 'Top K',\n\t\t\t\t\t\tname: 'topK',\n\t\t\t\t\t\tdefault: -1,\n\t\t\t\t\t\ttypeOptions: { maxValue: 1, minValue: -1, numberPrecision: 1 },\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t'Used to remove \"long tail\" low probability responses. Defaults to -1, which disables it.',\n\t\t\t\t\t\ttype: 'number',\n\t\t\t\t\t\tdisplayOptions: {\n\t\t\t\t\t\t\thide: {\n\t\t\t\t\t\t\t\tthinking: [true],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tdisplayName: 'Top P',\n\t\t\t\t\t\tname: 'topP',\n\t\t\t\t\t\tdefault: 1,\n\t\t\t\t\t\ttypeOptions: { maxValue: 1, minValue: 0, numberPrecision: 1 },\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t'Controls diversity via nucleus sampling: 0.5 means half of all likelihood-weighted options are considered. We generally recommend altering this or temperature but not both.',\n\t\t\t\t\t\ttype: 'number',\n\t\t\t\t\t\tdisplayOptions: {\n\t\t\t\t\t\t\thide: {\n\t\t\t\t\t\t\t\tthinking: [true],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tdisplayName: 'Enable Thinking',\n\t\t\t\t\t\tname: 'thinking',\n\t\t\t\t\t\ttype: 'boolean',\n\t\t\t\t\t\tdefault: false,\n\t\t\t\t\t\tdescription: 'Whether to enable thinking mode for the model',\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tdisplayName: 'Thinking Budget (Tokens)',\n\t\t\t\t\t\tname: 'thinkingBudget',\n\t\t\t\t\t\ttype: 'number',\n\t\t\t\t\t\tdefault: MIN_THINKING_BUDGET,\n\t\t\t\t\t\tdescription: 'The maximum number of tokens to use for thinking',\n\t\t\t\t\t\tdisplayOptions: {\n\t\t\t\t\t\t\tshow: {\n\t\t\t\t\t\t\t\tthinking: [true],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t],\n\t};\n\n\tasync supplyData(this: ISupplyDataFunctions, itemIndex: number): Promise<SupplyData> {\n\t\tconst credentials = await this.getCredentials<{\n\t\t\turl?: string;\n\t\t\tapiKey?: string;\n\t\t\theader?: boolean;\n\t\t\theaderName?: string;\n\t\t\theaderValue?: string;\n\t\t}>('anthropicApi');\n\t\tconst baseURL = credentials.url ?? 'https://api.anthropic.com';\n\t\tconst version = this.getNode().typeVersion;\n\t\tconst modelName =\n\t\t\tversion >= 1.3\n\t\t\t\t? (this.getNodeParameter('model.value', itemIndex) as string)\n\t\t\t\t: (this.getNodeParameter('model', itemIndex) as string);\n\n\t\tconst options = this.getNodeParameter('options', itemIndex, {}) as {\n\t\t\tmaxTokensToSample?: number;\n\t\t\ttemperature: number;\n\t\t\ttopK?: number;\n\t\t\ttopP?: number;\n\t\t\tthinking?: boolean;\n\t\t\tthinkingBudget?: number;\n\t\t};\n\t\tlet invocationKwargs = {};\n\n\t\tconst tokensUsageParser = (result: LLMResult) => {\n\t\t\tconst usage = (result?.llmOutput?.usage as {\n\t\t\t\tinput_tokens: number;\n\t\t\t\toutput_tokens: number;\n\t\t\t}) ?? {\n\t\t\t\tinput_tokens: 0,\n\t\t\t\toutput_tokens: 0,\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tcompletionTokens: usage.output_tokens,\n\t\t\t\tpromptTokens: usage.input_tokens,\n\t\t\t\ttotalTokens: usage.input_tokens + usage.output_tokens,\n\t\t\t};\n\t\t};\n\n\t\tif (options.thinking) {\n\t\t\tinvocationKwargs = {\n\t\t\t\tthinking: {\n\t\t\t\t\ttype: 'enabled',\n\t\t\t\t\t// If thinking is enabled, we need to set a budget.\n\t\t\t\t\t// We fallback to 1024 as that is the minimum\n\t\t\t\t\tbudget_tokens: options.thinkingBudget ?? MIN_THINKING_BUDGET,\n\t\t\t\t},\n\t\t\t\t// The default Langchain max_tokens is -1 (no limit) but Anthropic requires a number\n\t\t\t\t// higher than budget_tokens\n\t\t\t\tmax_tokens: options.maxTokensToSample ?? DEFAULT_MAX_TOKENS,\n\t\t\t\t// These need to be unset when thinking is enabled.\n\t\t\t\t// Because the invocationKwargs will override the model options\n\t\t\t\t// we can pass options to the model and then override them here\n\t\t\t\ttop_k: undefined,\n\t\t\t\ttop_p: undefined,\n\t\t\t\ttemperature: undefined,\n\t\t\t};\n\t\t}\n\n\t\tconst clientOptions: {\n\t\t\tfetchOptions?: { dispatcher: any };\n\t\t\tdefaultHeaders?: Record<string, string>;\n\t\t} = {\n\t\t\tfetchOptions: {\n\t\t\t\tdispatcher: getProxyAgent(baseURL),\n\t\t\t},\n\t\t};\n\n\t\tif (\n\t\t\tcredentials.header &&\n\t\t\ttypeof credentials.headerName === 'string' &&\n\t\t\tcredentials.headerName &&\n\t\t\ttypeof credentials.headerValue === 'string'\n\t\t) {\n\t\t\tclientOptions.defaultHeaders = {\n\t\t\t\t[credentials.headerName]: credentials.headerValue,\n\t\t\t};\n\t\t}\n\n\t\tconst model = new ChatAnthropic({\n\t\t\tanthropicApiKey: credentials.apiKey,\n\t\t\tmodel: modelName,\n\t\t\tanthropicApiUrl: baseURL,\n\t\t\tmaxTokens: options.maxTokensToSample,\n\t\t\ttemperature: options.temperature,\n\t\t\ttopK: options.topK,\n\t\t\ttopP: options.topP,\n\t\t\tcallbacks: [new N8nLlmTracing(this, { tokensUsageParser })],\n\t\t\tonFailedAttempt: makeN8nLlmFailedAttemptHandler(this),\n\t\t\tinvocationKwargs,\n\t\t\tclientOptions,\n\t\t});\n\n\t\t// Some Anthropic models do not support Langchain default of -1 for topP so we need to unset it\n\t\tif (options.topP === undefined) {\n\t\t\tdelete model.topP;\n\t\t}\n\n\t\t// If topP is set to a value and temperature is not, unset default Langchain temperature\n\t\tif (options.topP !== undefined && options.temperature === undefined) {\n\t\t\tdelete model.temperature;\n\t\t}\n\n\t\treturn {\n\t\t\tresponse: model,\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAA8B;AAE9B,4BAA8B;AAC9B,0BAA6C;AAC7C,0BAQO;AAEP,wCAA+C;AAC/C,2BAA8B;AAC9B,0BAA6B;AAE7B,MAAM,aAA8B;AAAA,EACnC,aAAa;AAAA,EACb,MAAM;AAAA,EACN,MAAM;AAAA;AAAA,EAEN,SAAS;AAAA,IACR;AAAA,MACC,MAAM;AAAA,MACN,OAAO;AAAA,IACR;AAAA,IACA;AAAA,MACC,MAAM;AAAA,MACN,OAAO;AAAA,IACR;AAAA,IACA;AAAA,MACC,MAAM;AAAA,MACN,OAAO;AAAA,IACR;AAAA,IACA;AAAA,MACC,MAAM;AAAA,MACN,OAAO;AAAA,IACR;AAAA,IACA;AAAA,MACC,MAAM;AAAA,MACN,OAAO;AAAA,IACR;AAAA,IACA;AAAA,MACC,MAAM;AAAA,MACN,OAAO;AAAA,IACR;AAAA,IACA;AAAA,MACC,MAAM;AAAA,MACN,OAAO;AAAA,IACR;AAAA,IACA;AAAA,MACC,MAAM;AAAA,MACN,OAAO;AAAA,IACR;AAAA,IACA;AAAA,MACC,MAAM;AAAA,MACN,OAAO;AAAA,IACR;AAAA,IACA;AAAA,MACC,MAAM;AAAA,MACN,OAAO;AAAA,IACR;AAAA,EACD;AAAA,EACA,aACC;AAAA,EACD,SAAS;AACV;AAEA,MAAM,sBAAsB;AAC5B,MAAM,qBAAq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AAQ,SAAS,UAAa,QAAQ,gBAAgB,QAAW;AACpE,aAAO,MAAM;AAAA,IACd;AAEA,WAAO;AAAA,MACN,UAAU;AAAA,IACX;AAAA,EACD;AACD;","names":[]}
@@ -46,7 +46,7 @@ async function searchModels(filter) {
46
46
  });
47
47
  const { data: models = [] } = await openai.models.list();
48
48
  const url = baseURL && new URL(baseURL);
49
- const isCustomAPI = !!(url && url.hostname !== "api.openai.com");
49
+ const isCustomAPI = !!(url && !["api.openai.com", "ai-assistant.n8n.io"].includes(url.hostname));
50
50
  const filteredModels = models.filter((model) => {
51
51
  const includeModel = (0, import_modelFiltering.shouldIncludeModel)(model.id, isCustomAPI);
52
52
  if (!filter) return includeModel;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../nodes/llms/LMChatOpenAi/methods/loadModels.ts"],"sourcesContent":["import type { ILoadOptionsFunctions, INodeListSearchResult } from 'n8n-workflow';\nimport OpenAI from 'openai';\n\nimport { shouldIncludeModel } from '../../../vendors/OpenAi/helpers/modelFiltering';\nimport { getProxyAgent } from '@utils/httpProxyAgent';\n\nexport async function searchModels(\n\tthis: ILoadOptionsFunctions,\n\tfilter?: string,\n): Promise<INodeListSearchResult> {\n\tconst credentials = await this.getCredentials('openAiApi');\n\tconst baseURL =\n\t\t(this.getNodeParameter('options.baseURL', '') as string) ||\n\t\t(credentials.url as string) ||\n\t\t'https://api.openai.com/v1';\n\n\tconst openai = new OpenAI({\n\t\tbaseURL,\n\t\tapiKey: credentials.apiKey as string,\n\t\tfetchOptions: {\n\t\t\tdispatcher: getProxyAgent(baseURL),\n\t\t},\n\t});\n\tconst { data: models = [] } = await openai.models.list();\n\n\tconst url = baseURL && new URL(baseURL);\n\tconst isCustomAPI = !!(url && url.hostname !== 'api.openai.com');\n\n\tconst filteredModels = models.filter((model: { id: string }) => {\n\t\tconst includeModel = shouldIncludeModel(model.id, isCustomAPI);\n\n\t\tif (!filter) return includeModel;\n\n\t\treturn includeModel && model.id.toLowerCase().includes(filter.toLowerCase());\n\t});\n\n\tfilteredModels.sort((a, b) => a.id.localeCompare(b.id));\n\n\treturn {\n\t\tresults: filteredModels.map((model: { id: string }) => ({\n\t\t\tname: model.id,\n\t\t\tvalue: model.id,\n\t\t})),\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAAmB;AAEnB,4BAAmC;AACnC,4BAA8B;AAE9B,eAAsB,aAErB,QACiC;AACjC,QAAM,cAAc,MAAM,KAAK,eAAe,WAAW;AACzD,QAAM,UACJ,KAAK,iBAAiB,mBAAmB,EAAE,KAC3C,YAAY,OACb;AAED,QAAM,SAAS,IAAI,cAAAA,QAAO;AAAA,IACzB;AAAA,IACA,QAAQ,YAAY;AAAA,IACpB,cAAc;AAAA,MACb,gBAAY,qCAAc,OAAO;AAAA,IAClC;AAAA,EACD,CAAC;AACD,QAAM,EAAE,MAAM,SAAS,CAAC,EAAE,IAAI,MAAM,OAAO,OAAO,KAAK;AAEvD,QAAM,MAAM,WAAW,IAAI,IAAI,OAAO;AACtC,QAAM,cAAc,CAAC,EAAE,OAAO,IAAI,aAAa;AAE/C,QAAM,iBAAiB,OAAO,OAAO,CAAC,UAA0B;AAC/D,UAAM,mBAAe,0CAAmB,MAAM,IAAI,WAAW;AAE7D,QAAI,CAAC,OAAQ,QAAO;AAEpB,WAAO,gBAAgB,MAAM,GAAG,YAAY,EAAE,SAAS,OAAO,YAAY,CAAC;AAAA,EAC5E,CAAC;AAED,iBAAe,KAAK,CAAC,GAAG,MAAM,EAAE,GAAG,cAAc,EAAE,EAAE,CAAC;AAEtD,SAAO;AAAA,IACN,SAAS,eAAe,IAAI,CAAC,WAA2B;AAAA,MACvD,MAAM,MAAM;AAAA,MACZ,OAAO,MAAM;AAAA,IACd,EAAE;AAAA,EACH;AACD;","names":["OpenAI"]}
1
+ {"version":3,"sources":["../../../../../nodes/llms/LMChatOpenAi/methods/loadModels.ts"],"sourcesContent":["import type { ILoadOptionsFunctions, INodeListSearchResult } from 'n8n-workflow';\nimport OpenAI from 'openai';\n\nimport { shouldIncludeModel } from '../../../vendors/OpenAi/helpers/modelFiltering';\nimport { getProxyAgent } from '@utils/httpProxyAgent';\n\nexport async function searchModels(\n\tthis: ILoadOptionsFunctions,\n\tfilter?: string,\n): Promise<INodeListSearchResult> {\n\tconst credentials = await this.getCredentials('openAiApi');\n\tconst baseURL =\n\t\t(this.getNodeParameter('options.baseURL', '') as string) ||\n\t\t(credentials.url as string) ||\n\t\t'https://api.openai.com/v1';\n\n\tconst openai = new OpenAI({\n\t\tbaseURL,\n\t\tapiKey: credentials.apiKey as string,\n\t\tfetchOptions: {\n\t\t\tdispatcher: getProxyAgent(baseURL),\n\t\t},\n\t});\n\tconst { data: models = [] } = await openai.models.list();\n\n\tconst url = baseURL && new URL(baseURL);\n\tconst isCustomAPI = !!(url && !['api.openai.com', 'ai-assistant.n8n.io'].includes(url.hostname));\n\n\tconst filteredModels = models.filter((model: { id: string }) => {\n\t\tconst includeModel = shouldIncludeModel(model.id, isCustomAPI);\n\n\t\tif (!filter) return includeModel;\n\n\t\treturn includeModel && model.id.toLowerCase().includes(filter.toLowerCase());\n\t});\n\n\tfilteredModels.sort((a, b) => a.id.localeCompare(b.id));\n\n\treturn {\n\t\tresults: filteredModels.map((model: { id: string }) => ({\n\t\t\tname: model.id,\n\t\t\tvalue: model.id,\n\t\t})),\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAAmB;AAEnB,4BAAmC;AACnC,4BAA8B;AAE9B,eAAsB,aAErB,QACiC;AACjC,QAAM,cAAc,MAAM,KAAK,eAAe,WAAW;AACzD,QAAM,UACJ,KAAK,iBAAiB,mBAAmB,EAAE,KAC3C,YAAY,OACb;AAED,QAAM,SAAS,IAAI,cAAAA,QAAO;AAAA,IACzB;AAAA,IACA,QAAQ,YAAY;AAAA,IACpB,cAAc;AAAA,MACb,gBAAY,qCAAc,OAAO;AAAA,IAClC;AAAA,EACD,CAAC;AACD,QAAM,EAAE,MAAM,SAAS,CAAC,EAAE,IAAI,MAAM,OAAO,OAAO,KAAK;AAEvD,QAAM,MAAM,WAAW,IAAI,IAAI,OAAO;AACtC,QAAM,cAAc,CAAC,EAAE,OAAO,CAAC,CAAC,kBAAkB,qBAAqB,EAAE,SAAS,IAAI,QAAQ;AAE9F,QAAM,iBAAiB,OAAO,OAAO,CAAC,UAA0B;AAC/D,UAAM,mBAAe,0CAAmB,MAAM,IAAI,WAAW;AAE7D,QAAI,CAAC,OAAQ,QAAO;AAEpB,WAAO,gBAAgB,MAAM,GAAG,YAAY,EAAE,SAAS,OAAO,YAAY,CAAC;AAAA,EAC5E,CAAC;AAED,iBAAe,KAAK,CAAC,GAAG,MAAM,EAAE,GAAG,cAAc,EAAE,EAAE,CAAC;AAEtD,SAAO;AAAA,IACN,SAAS,eAAe,IAAI,CAAC,WAA2B;AAAA,MACvD,MAAM,MAAM;AAAA,MACZ,OAAO,MAAM;AAAA,IACd,EAAE;AAAA,EACH;AACD;","names":["OpenAI"]}
@@ -63,7 +63,14 @@ class ToolWorkflowV2 {
63
63
  continue;
64
64
  }
65
65
  const result = await tool.invoke(item.json);
66
- response.push(result);
66
+ if (Array.isArray(result)) {
67
+ response.push(...result);
68
+ } else {
69
+ response.push({
70
+ json: { response: result },
71
+ pairedItem: { item: itemIndex }
72
+ });
73
+ }
67
74
  }
68
75
  return [response];
69
76
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../nodes/tools/ToolWorkflow/v2/ToolWorkflowV2.node.ts"],"sourcesContent":["import type { DynamicStructuredTool, DynamicTool } from '@langchain/core/tools';\n\nimport type {\n\tINodeTypeBaseDescription,\n\tISupplyDataFunctions,\n\tSupplyData,\n\tINodeType,\n\tINodeTypeDescription,\n\tIExecuteFunctions,\n\tINodeExecutionData,\n} from 'n8n-workflow';\nimport { nodeNameToToolName } from 'n8n-workflow';\n\nimport { localResourceMapping } from './methods';\nimport { WorkflowToolService } from './utils/WorkflowToolService';\nimport { versionDescription } from './versionDescription';\n\nasync function getTool(\n\tctx: ISupplyDataFunctions | IExecuteFunctions,\n\tenableLogging: boolean,\n\titemIndex: number,\n): Promise<DynamicTool | DynamicStructuredTool> {\n\tconst node = ctx.getNode();\n\tconst { typeVersion } = node;\n\tconst returnAllItems = typeVersion > 2;\n\n\tconst workflowToolService = new WorkflowToolService(ctx, { returnAllItems });\n\tconst name =\n\t\ttypeVersion <= 2.1 ? (ctx.getNodeParameter('name', 0) as string) : nodeNameToToolName(node);\n\tconst description = ctx.getNodeParameter('description', 0) as string;\n\n\treturn await workflowToolService.createTool({\n\t\tctx,\n\t\tname,\n\t\tdescription,\n\t\titemIndex,\n\t\tmanualLogging: enableLogging,\n\t});\n}\n\nexport class ToolWorkflowV2 implements INodeType {\n\tdescription: INodeTypeDescription;\n\n\tconstructor(baseDescription: INodeTypeBaseDescription) {\n\t\tthis.description = {\n\t\t\t...baseDescription,\n\t\t\t...versionDescription,\n\t\t};\n\t}\n\n\tmethods = {\n\t\tlocalResourceMapping,\n\t};\n\n\tasync supplyData(this: ISupplyDataFunctions, itemIndex: number): Promise<SupplyData> {\n\t\treturn { response: await getTool(this, true, itemIndex) };\n\t}\n\n\tasync execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {\n\t\tconst items = this.getInputData();\n\n\t\tconst response: INodeExecutionData[] = [];\n\t\tfor (let itemIndex = 0; itemIndex < this.getInputData().length; itemIndex++) {\n\t\t\tconst item = items[itemIndex];\n\t\t\tconst tool = await getTool(this, false, itemIndex);\n\n\t\t\tif (item === undefined) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst result = await tool.invoke(item.json);\n\t\t\tresponse.push(result);\n\t\t}\n\n\t\treturn [response];\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,0BAAmC;AAEnC,qBAAqC;AACrC,iCAAoC;AACpC,gCAAmC;AAEnC,eAAe,QACd,KACA,eACA,WAC+C;AAC/C,QAAM,OAAO,IAAI,QAAQ;AACzB,QAAM,EAAE,YAAY,IAAI;AACxB,QAAM,iBAAiB,cAAc;AAErC,QAAM,sBAAsB,IAAI,+CAAoB,KAAK,EAAE,eAAe,CAAC;AAC3E,QAAM,OACL,eAAe,MAAO,IAAI,iBAAiB,QAAQ,CAAC,QAAe,wCAAmB,IAAI;AAC3F,QAAM,cAAc,IAAI,iBAAiB,eAAe,CAAC;AAEzD,SAAO,MAAM,oBAAoB,WAAW;AAAA,IAC3C;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,eAAe;AAAA,EAChB,CAAC;AACF;AAEO,MAAM,eAAoC;AAAA,EAGhD,YAAY,iBAA2C;AAOvD,mBAAU;AAAA,MACT;AAAA,IACD;AARC,SAAK,cAAc;AAAA,MAClB,GAAG;AAAA,MACH,GAAG;AAAA,IACJ;AAAA,EACD;AAAA,EAMA,MAAM,WAAuC,WAAwC;AACpF,WAAO,EAAE,UAAU,MAAM,QAAQ,MAAM,MAAM,SAAS,EAAE;AAAA,EACzD;AAAA,EAEA,MAAM,UAAkE;AACvE,UAAM,QAAQ,KAAK,aAAa;AAEhC,UAAM,WAAiC,CAAC;AACxC,aAAS,YAAY,GAAG,YAAY,KAAK,aAAa,EAAE,QAAQ,aAAa;AAC5E,YAAM,OAAO,MAAM,SAAS;AAC5B,YAAM,OAAO,MAAM,QAAQ,MAAM,OAAO,SAAS;AAEjD,UAAI,SAAS,QAAW;AACvB;AAAA,MACD;AACA,YAAM,SAAS,MAAM,KAAK,OAAO,KAAK,IAAI;AAC1C,eAAS,KAAK,MAAM;AAAA,IACrB;AAEA,WAAO,CAAC,QAAQ;AAAA,EACjB;AACD;","names":[]}
1
+ {"version":3,"sources":["../../../../../nodes/tools/ToolWorkflow/v2/ToolWorkflowV2.node.ts"],"sourcesContent":["import type { DynamicStructuredTool, DynamicTool } from '@langchain/core/tools';\n\nimport type {\n\tINodeTypeBaseDescription,\n\tISupplyDataFunctions,\n\tSupplyData,\n\tINodeType,\n\tINodeTypeDescription,\n\tIExecuteFunctions,\n\tINodeExecutionData,\n} from 'n8n-workflow';\nimport { nodeNameToToolName } from 'n8n-workflow';\n\nimport { localResourceMapping } from './methods';\nimport { WorkflowToolService } from './utils/WorkflowToolService';\nimport { versionDescription } from './versionDescription';\n\nasync function getTool(\n\tctx: ISupplyDataFunctions | IExecuteFunctions,\n\tenableLogging: boolean,\n\titemIndex: number,\n): Promise<DynamicTool | DynamicStructuredTool> {\n\tconst node = ctx.getNode();\n\tconst { typeVersion } = node;\n\tconst returnAllItems = typeVersion > 2;\n\n\tconst workflowToolService = new WorkflowToolService(ctx, { returnAllItems });\n\tconst name =\n\t\ttypeVersion <= 2.1 ? (ctx.getNodeParameter('name', 0) as string) : nodeNameToToolName(node);\n\tconst description = ctx.getNodeParameter('description', 0) as string;\n\n\treturn await workflowToolService.createTool({\n\t\tctx,\n\t\tname,\n\t\tdescription,\n\t\titemIndex,\n\t\tmanualLogging: enableLogging,\n\t});\n}\n\nexport class ToolWorkflowV2 implements INodeType {\n\tdescription: INodeTypeDescription;\n\n\tconstructor(baseDescription: INodeTypeBaseDescription) {\n\t\tthis.description = {\n\t\t\t...baseDescription,\n\t\t\t...versionDescription,\n\t\t};\n\t}\n\n\tmethods = {\n\t\tlocalResourceMapping,\n\t};\n\n\tasync supplyData(this: ISupplyDataFunctions, itemIndex: number): Promise<SupplyData> {\n\t\treturn { response: await getTool(this, true, itemIndex) };\n\t}\n\n\tasync execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {\n\t\tconst items = this.getInputData();\n\n\t\tconst response: INodeExecutionData[] = [];\n\t\tfor (let itemIndex = 0; itemIndex < this.getInputData().length; itemIndex++) {\n\t\t\tconst item = items[itemIndex];\n\t\t\tconst tool = await getTool(this, false, itemIndex);\n\n\t\t\tif (item === undefined) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst result = await tool.invoke(item.json);\n\n\t\t\t// When manualLogging is false, tool.invoke returns INodeExecutionData[]\n\t\t\t// We need to spread these into the response array\n\t\t\tif (Array.isArray(result)) {\n\t\t\t\tresponse.push(...result);\n\t\t\t} else {\n\t\t\t\t// Fallback for unexpected types (shouldn't happen with manualLogging=false)\n\t\t\t\tresponse.push({\n\t\t\t\t\tjson: { response: result },\n\t\t\t\t\tpairedItem: { item: itemIndex },\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn [response];\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,0BAAmC;AAEnC,qBAAqC;AACrC,iCAAoC;AACpC,gCAAmC;AAEnC,eAAe,QACd,KACA,eACA,WAC+C;AAC/C,QAAM,OAAO,IAAI,QAAQ;AACzB,QAAM,EAAE,YAAY,IAAI;AACxB,QAAM,iBAAiB,cAAc;AAErC,QAAM,sBAAsB,IAAI,+CAAoB,KAAK,EAAE,eAAe,CAAC;AAC3E,QAAM,OACL,eAAe,MAAO,IAAI,iBAAiB,QAAQ,CAAC,QAAe,wCAAmB,IAAI;AAC3F,QAAM,cAAc,IAAI,iBAAiB,eAAe,CAAC;AAEzD,SAAO,MAAM,oBAAoB,WAAW;AAAA,IAC3C;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,eAAe;AAAA,EAChB,CAAC;AACF;AAEO,MAAM,eAAoC;AAAA,EAGhD,YAAY,iBAA2C;AAOvD,mBAAU;AAAA,MACT;AAAA,IACD;AARC,SAAK,cAAc;AAAA,MAClB,GAAG;AAAA,MACH,GAAG;AAAA,IACJ;AAAA,EACD;AAAA,EAMA,MAAM,WAAuC,WAAwC;AACpF,WAAO,EAAE,UAAU,MAAM,QAAQ,MAAM,MAAM,SAAS,EAAE;AAAA,EACzD;AAAA,EAEA,MAAM,UAAkE;AACvE,UAAM,QAAQ,KAAK,aAAa;AAEhC,UAAM,WAAiC,CAAC;AACxC,aAAS,YAAY,GAAG,YAAY,KAAK,aAAa,EAAE,QAAQ,aAAa;AAC5E,YAAM,OAAO,MAAM,SAAS;AAC5B,YAAM,OAAO,MAAM,QAAQ,MAAM,OAAO,SAAS;AAEjD,UAAI,SAAS,QAAW;AACvB;AAAA,MACD;AACA,YAAM,SAAS,MAAM,KAAK,OAAO,KAAK,IAAI;AAI1C,UAAI,MAAM,QAAQ,MAAM,GAAG;AAC1B,iBAAS,KAAK,GAAG,MAAM;AAAA,MACxB,OAAO;AAEN,iBAAS,KAAK;AAAA,UACb,MAAM,EAAE,UAAU,OAAO;AAAA,UACzB,YAAY,EAAE,MAAM,UAAU;AAAA,QAC/B,CAAC;AAAA,MACF;AAAA,IACD;AAEA,WAAO,CAAC,QAAQ;AAAA,EACjB;AACD;","names":[]}
@@ -43,6 +43,7 @@ var import_mongodb2 = require("mongodb");
43
43
  var import_n8n_workflow = require("n8n-workflow");
44
44
  var import_sharedFields = require("../../../utils/sharedFields");
45
45
  var import_createVectorStoreNode = require("../shared/createVectorStoreNode/createVectorStoreNode");
46
+ var import_GenericFunctions = require("n8n-nodes-base/dist/nodes/MongoDb/GenericFunctions");
46
47
  const MONGODB_CREDENTIALS = "mongoDb";
47
48
  const MONGODB_COLLECTION_NAME = "mongoCollection";
48
49
  const VECTOR_INDEX_NAME = "vectorIndexName";
@@ -173,7 +174,8 @@ const mongoConfig = {
173
174
  };
174
175
  async function getMongoClient(context, version) {
175
176
  const credentials = await context.getCredentials(MONGODB_CREDENTIALS);
176
- const connectionString = credentials.connectionString;
177
+ const node = context.getNode();
178
+ const { connectionString } = (0, import_GenericFunctions.validateAndResolveMongoCredentials)(node, credentials);
177
179
  if (!mongoConfig.client || mongoConfig.connectionString !== connectionString || mongoConfig.nodeVersion !== version) {
178
180
  if (mongoConfig.client) {
179
181
  await mongoConfig.client.close();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../nodes/vector_store/VectorStoreMongoDBAtlas/VectorStoreMongoDBAtlas.node.ts"],"sourcesContent":["import type { EmbeddingsInterface } from '@langchain/core/embeddings';\nimport { MongoDBAtlasVectorSearch, type MongoDBAtlasVectorSearchLibArgs } from '@langchain/mongodb';\nimport { MongoClient } from 'mongodb';\nimport {\n\ttype IDataObject,\n\ttype ILoadOptionsFunctions,\n\tNodeOperationError,\n\ttype INodeProperties,\n\ttype IExecuteFunctions,\n\ttype ISupplyDataFunctions,\n} from 'n8n-workflow';\nimport { metadataFilterField } from '@utils/sharedFields';\n\nimport { createVectorStoreNode } from '../shared/createVectorStoreNode/createVectorStoreNode';\n\n/**\n * Constants for the name of the credentials and Node parameters.\n */\nexport const MONGODB_CREDENTIALS = 'mongoDb';\nexport const MONGODB_COLLECTION_NAME = 'mongoCollection';\nexport const VECTOR_INDEX_NAME = 'vectorIndexName';\nexport const EMBEDDING_NAME = 'embedding';\nexport const METADATA_FIELD_NAME = 'metadata_field';\nexport const PRE_FILTER_NAME = 'preFilter';\nexport const POST_FILTER_NAME = 'postFilterPipeline';\n\nconst mongoCollectionRLC: INodeProperties = {\n\tdisplayName: 'MongoDB Collection',\n\tname: MONGODB_COLLECTION_NAME,\n\ttype: 'resourceLocator',\n\tdefault: { mode: 'list', value: '' },\n\trequired: true,\n\tmodes: [\n\t\t{\n\t\t\tdisplayName: 'From List',\n\t\t\tname: 'list',\n\t\t\ttype: 'list',\n\t\t\ttypeOptions: {\n\t\t\t\tsearchListMethod: 'mongoCollectionSearch', // Method to fetch collections\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdisplayName: 'Name',\n\t\t\tname: 'name',\n\t\t\ttype: 'string',\n\t\t\tplaceholder: 'e.g. my_collection',\n\t\t},\n\t],\n};\n\nconst vectorIndexName: INodeProperties = {\n\tdisplayName: 'Vector Index Name',\n\tname: VECTOR_INDEX_NAME,\n\ttype: 'string',\n\tdefault: '',\n\tdescription: 'The name of the vector index',\n\trequired: true,\n};\n\nconst embeddingField: INodeProperties = {\n\tdisplayName: 'Embedding',\n\tname: EMBEDDING_NAME,\n\ttype: 'string',\n\tdefault: 'embedding',\n\tdescription: 'The field with the embedding array',\n\trequired: true,\n};\n\nconst metadataField: INodeProperties = {\n\tdisplayName: 'Metadata Field',\n\tname: METADATA_FIELD_NAME,\n\ttype: 'string',\n\tdefault: 'text',\n\tdescription: 'The text field of the raw data',\n\trequired: true,\n};\n\nconst sharedFields: INodeProperties[] = [\n\tmongoCollectionRLC,\n\tembeddingField,\n\tmetadataField,\n\tvectorIndexName,\n];\n\nconst mongoNamespaceField: INodeProperties = {\n\tdisplayName: 'Namespace',\n\tname: 'namespace',\n\ttype: 'string',\n\tdescription: 'Logical partition for documents. Uses metadata.namespace field for filtering.',\n\tdefault: '',\n};\n\nconst preFilterField: INodeProperties = {\n\tdisplayName: 'Pre Filter',\n\tname: PRE_FILTER_NAME,\n\ttype: 'json',\n\ttypeOptions: {\n\t\talwaysOpenEditWindow: true,\n\t},\n\tdefault: '',\n\tplaceholder: '{ \"key\": \"value\" }',\n\thint: 'This is a filter applied in the $vectorSearch stage <a href=\"https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-stage/#atlas-vector-search-pre-filter\">here</a>',\n\trequired: true,\n\tdescription: 'MongoDB Atlas Vector Search pre-filter',\n};\n\nconst postFilterField: INodeProperties = {\n\tdisplayName: 'Post Filter Pipeline',\n\tname: POST_FILTER_NAME,\n\ttype: 'json',\n\ttypeOptions: {\n\t\talwaysOpenEditWindow: true,\n\t},\n\tdefault: '',\n\tplaceholder: '[{ \"$match\": { \"$gt\": \"1950-01-01\" }, ... }]',\n\thint: 'Learn more about aggregation pipeline <a href=\"https://docs.mongodb.com/manual/core/aggregation-pipeline/\">here</a>',\n\trequired: true,\n\tdescription: 'MongoDB aggregation pipeline in JSON format',\n};\n\nconst retrieveFields: INodeProperties[] = [\n\t{\n\t\tdisplayName: 'Options',\n\t\tname: 'options',\n\t\ttype: 'collection',\n\t\tplaceholder: 'Add Option',\n\t\tdefault: {},\n\t\toptions: [mongoNamespaceField, metadataFilterField, preFilterField, postFilterField],\n\t},\n];\n\nconst insertFields: INodeProperties[] = [\n\t{\n\t\tdisplayName: 'Options',\n\t\tname: 'options',\n\t\ttype: 'collection',\n\t\tplaceholder: 'Add Option',\n\t\tdefault: {},\n\t\toptions: [\n\t\t\t{\n\t\t\t\tdisplayName: 'Clear Namespace',\n\t\t\t\tname: 'clearNamespace',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t\tdescription: 'Whether to clear documents in the namespace before inserting new data',\n\t\t\t},\n\t\t\tmongoNamespaceField,\n\t\t],\n\t},\n];\n\nexport const mongoConfig = {\n\tclient: null as MongoClient | null,\n\tconnectionString: '',\n\tnodeVersion: 0,\n};\n\n/**\n * Type used for cleaner, more intentional typing.\n */\ntype IFunctionsContext = IExecuteFunctions | ISupplyDataFunctions | ILoadOptionsFunctions;\n\n/**\n * Get the mongo client.\n * @param context - The context.\n * @returns the MongoClient for the node.\n */\nexport async function getMongoClient(context: any, version: number) {\n\tconst credentials = await context.getCredentials(MONGODB_CREDENTIALS);\n\tconst connectionString = credentials.connectionString as string;\n\tif (\n\t\t!mongoConfig.client ||\n\t\tmongoConfig.connectionString !== connectionString ||\n\t\tmongoConfig.nodeVersion !== version\n\t) {\n\t\tif (mongoConfig.client) {\n\t\t\tawait mongoConfig.client.close();\n\t\t}\n\n\t\tmongoConfig.connectionString = connectionString;\n\t\tmongoConfig.nodeVersion = version;\n\t\tmongoConfig.client = new MongoClient(connectionString, {\n\t\t\tappName: 'devrel.integration.n8n_vector_integ',\n\t\t\tdriverInfo: {\n\t\t\t\tname: 'n8n_vector',\n\t\t\t\tversion: version.toString(),\n\t\t\t},\n\t\t});\n\t\tawait mongoConfig.client.connect();\n\t}\n\treturn mongoConfig.client;\n}\n\n/**\n * Get the database object from the MongoClient by the configured name.\n * @param context - The context.\n * @returns the Db object.\n */\nexport async function getDatabase(context: IFunctionsContext, client: MongoClient) {\n\tconst credentials = await context.getCredentials(MONGODB_CREDENTIALS);\n\treturn client.db(credentials.database as string);\n}\n\n/**\n * Get all the collection in the database.\n * @param this The load options context.\n * @returns The list of collections.\n */\nexport async function getCollections(this: ILoadOptionsFunctions) {\n\ttry {\n\t\tconst client = await getMongoClient(this, this.getNode().typeVersion);\n\t\tconst db = await getDatabase(this, client);\n\t\tconst collections = await db.listCollections().toArray();\n\t\tconst results = collections.map((collection) => ({\n\t\t\tname: collection.name,\n\t\t\tvalue: collection.name,\n\t\t}));\n\n\t\treturn { results };\n\t} catch (error) {\n\t\tthrow new NodeOperationError(this.getNode(), `Error: ${error.message}`);\n\t}\n}\n\n/**\n * Get a parameter from the context.\n * @param key - The key of the parameter.\n * @param context - The context.\n * @param itemIndex - The index.\n * @returns The value.\n */\nexport function getParameter(key: string, context: IFunctionsContext, itemIndex: number): string {\n\tconst value = context.getNodeParameter(key, itemIndex, '', {\n\t\textractValue: true,\n\t}) as string;\n\tif (typeof value !== 'string') {\n\t\tthrow new NodeOperationError(context.getNode(), `Parameter ${key} must be a string`);\n\t}\n\treturn value;\n}\n\nexport const getCollectionName = getParameter.bind(null, MONGODB_COLLECTION_NAME);\nexport const getVectorIndexName = getParameter.bind(null, VECTOR_INDEX_NAME);\nexport const getEmbeddingFieldName = getParameter.bind(null, EMBEDDING_NAME);\nexport const getMetadataFieldName = getParameter.bind(null, METADATA_FIELD_NAME);\n\nexport function getFilterValue<T>(\n\tname: string,\n\tcontext: IExecuteFunctions | ISupplyDataFunctions,\n\titemIndex: number,\n): T | undefined {\n\tconst options: IDataObject = context.getNodeParameter('options', itemIndex, {});\n\n\tif (options[name]) {\n\t\tif (typeof options[name] === 'string') {\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(options[name]);\n\t\t\t} catch (error) {\n\t\t\t\tthrow new NodeOperationError(context.getNode(), `Error: ${error.message}`, {\n\t\t\t\t\titemIndex,\n\t\t\t\t\tdescription: `Could not parse JSON for ${name}`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthrow new NodeOperationError(context.getNode(), 'Error: No JSON string provided.', {\n\t\t\titemIndex,\n\t\t\tdescription: `Could not parse JSON for ${name}`,\n\t\t});\n\t}\n\n\treturn undefined;\n}\n\nclass ExtendedMongoDBAtlasVectorSearch extends MongoDBAtlasVectorSearch {\n\tpreFilter: IDataObject;\n\tpostFilterPipeline?: IDataObject[];\n\n\tconstructor(\n\t\tembeddings: EmbeddingsInterface,\n\t\toptions: MongoDBAtlasVectorSearchLibArgs,\n\t\tpreFilter: IDataObject,\n\t\tpostFilterPipeline?: IDataObject[],\n\t) {\n\t\tsuper(embeddings, options);\n\t\tthis.preFilter = preFilter;\n\t\tthis.postFilterPipeline = postFilterPipeline;\n\t}\n\n\tasync similaritySearchVectorWithScore(query: number[], k: number) {\n\t\tconst mergedFilter: MongoDBAtlasVectorSearch['FilterType'] = {\n\t\t\tpreFilter: this.preFilter,\n\t\t\tpostFilterPipeline: this.postFilterPipeline,\n\t\t};\n\t\treturn await super.similaritySearchVectorWithScore(query, k, mergedFilter);\n\t}\n}\n\nexport class VectorStoreMongoDBAtlas extends createVectorStoreNode({\n\tmeta: {\n\t\tdisplayName: 'MongoDB Atlas Vector Store',\n\t\tname: 'vectorStoreMongoDBAtlas',\n\t\tdescription: 'Work with your data in MongoDB Atlas Vector Store',\n\t\ticon: { light: 'file:mongodb.svg', dark: 'file:mongodb.dark.svg' },\n\t\tdocsUrl:\n\t\t\t'https://docs.n8n.io/integrations/builtin/cluster-nodes/root-nodes/n8n-nodes-langchain.vectorstoremongodbatlas/',\n\t\tcredentials: [\n\t\t\t{\n\t\t\t\tname: 'mongoDb',\n\t\t\t\trequired: true,\n\t\t\t},\n\t\t],\n\t\toperationModes: ['load', 'insert', 'retrieve', 'update', 'retrieve-as-tool'],\n\t},\n\tmethods: { listSearch: { mongoCollectionSearch: getCollections } },\n\tretrieveFields,\n\tloadFields: retrieveFields,\n\tinsertFields,\n\tsharedFields,\n\tasync getVectorStoreClient(context, _filter, embeddings, itemIndex) {\n\t\ttry {\n\t\t\tconst client = await getMongoClient(context, context.getNode().typeVersion);\n\t\t\tconst db = await getDatabase(context, client);\n\t\t\tconst collectionName = getCollectionName(context, itemIndex);\n\t\t\tconst mongoVectorIndexName = getVectorIndexName(context, itemIndex);\n\t\t\tconst embeddingFieldName = getEmbeddingFieldName(context, itemIndex);\n\t\t\tconst metadataFieldName = getMetadataFieldName(context, itemIndex);\n\n\t\t\tconst collection = db.collection(collectionName);\n\n\t\t\t// test index exists\n\t\t\tconst indexes = await collection.listSearchIndexes().toArray();\n\n\t\t\tconst indexExists = indexes.some((index) => index.name === mongoVectorIndexName);\n\n\t\t\tif (!indexExists) {\n\t\t\t\tthrow new NodeOperationError(context.getNode(), `Index ${mongoVectorIndexName} not found`, {\n\t\t\t\t\titemIndex,\n\t\t\t\t\tdescription: 'Please check that the index exists in your collection',\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst preFilter = getFilterValue<IDataObject>(PRE_FILTER_NAME, context, itemIndex);\n\t\t\tconst postFilterPipeline = getFilterValue<IDataObject[]>(\n\t\t\t\tPOST_FILTER_NAME,\n\t\t\t\tcontext,\n\t\t\t\titemIndex,\n\t\t\t);\n\n\t\t\treturn new ExtendedMongoDBAtlasVectorSearch(\n\t\t\t\tembeddings,\n\t\t\t\t{\n\t\t\t\t\tcollection,\n\t\t\t\t\tindexName: mongoVectorIndexName, // Default index name\n\t\t\t\t\ttextKey: metadataFieldName, // Field containing raw text\n\t\t\t\t\tembeddingKey: embeddingFieldName, // Field containing embeddings\n\t\t\t\t},\n\t\t\t\tpreFilter ?? {},\n\t\t\t\tpostFilterPipeline,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (error instanceof NodeOperationError) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tthrow new NodeOperationError(context.getNode(), `Error: ${error.message}`, {\n\t\t\t\titemIndex,\n\t\t\t\tdescription: 'Please check your MongoDB Atlas connection details',\n\t\t\t});\n\t\t}\n\t},\n\tasync populateVectorStore(context, embeddings, documents, itemIndex) {\n\t\ttry {\n\t\t\tconst client = await getMongoClient(context, context.getNode().typeVersion);\n\t\t\tconst db = await getDatabase(context, client);\n\t\t\tconst collectionName = getCollectionName(context, itemIndex);\n\t\t\tconst mongoVectorIndexName = getVectorIndexName(context, itemIndex);\n\t\t\tconst embeddingFieldName = getEmbeddingFieldName(context, itemIndex);\n\t\t\tconst metadataFieldName = getMetadataFieldName(context, itemIndex);\n\n\t\t\t// Check if collection exists\n\t\t\tconst collections = await db.listCollections({ name: collectionName }).toArray();\n\t\t\tif (collections.length === 0) {\n\t\t\t\tawait db.createCollection(collectionName);\n\t\t\t}\n\t\t\tconst collection = db.collection(collectionName);\n\t\t\tawait ExtendedMongoDBAtlasVectorSearch.fromDocuments(documents, embeddings, {\n\t\t\t\tcollection,\n\t\t\t\tindexName: mongoVectorIndexName, // Default index name\n\t\t\t\ttextKey: metadataFieldName, // Field containing raw text\n\t\t\t\tembeddingKey: embeddingFieldName, // Field containing embeddings\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new NodeOperationError(context.getNode(), `Error: ${error.message}`, {\n\t\t\t\titemIndex,\n\t\t\t\tdescription: 'Please check your MongoDB Atlas connection details',\n\t\t\t});\n\t\t}\n\t},\n}) {}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,qBAA+E;AAC/E,IAAAA,kBAA4B;AAC5B,0BAOO;AACP,0BAAoC;AAEpC,mCAAsC;AAK/B,MAAM,sBAAsB;AAC5B,MAAM,0BAA0B;AAChC,MAAM,oBAAoB;AAC1B,MAAM,iBAAiB;AACvB,MAAM,sBAAsB;AAC5B,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AAEhC,MAAM,qBAAsC;AAAA,EAC3C,aAAa;AAAA,EACb,MAAM;AAAA,EACN,MAAM;AAAA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EAAE,MAAM,eAAe,CAAC,EAAE,QAAQ;AAC/E,UAAI,YAAY,WAAW,GAAG;AAC7B,cAAM,GAAG,iBAAiB,cAAc;AAAA,MACzC;AACA,YAAM,aAAa,GAAG,WAAW,cAAc;AAC/C,YAAM,iCAAiC,cAAc,WAAW,YAAY;AAAA,QAC3E;AAAA,QACA,WAAW;AAAA;AAAA,QACX,SAAS;AAAA;AAAA,QACT,cAAc;AAAA;AAAA,MACf,CAAC;AAAA,IACF,SAAS,OAAO;AACf,YAAM,IAAI,uCAAmB,QAAQ,QAAQ,GAAG,UAAU,MAAM,OAAO,IAAI;AAAA,QAC1E;AAAA,QACA,aAAa;AAAA,MACd,CAAC;AAAA,IACF;AAAA,EACD;AACD,CAAC,EAAE;AAAC;","names":["import_mongodb"]}
1
+ {"version":3,"sources":["../../../../nodes/vector_store/VectorStoreMongoDBAtlas/VectorStoreMongoDBAtlas.node.ts"],"sourcesContent":["import type { EmbeddingsInterface } from '@langchain/core/embeddings';\nimport { MongoDBAtlasVectorSearch, type MongoDBAtlasVectorSearchLibArgs } from '@langchain/mongodb';\nimport { MongoClient } from 'mongodb';\nimport {\n\ttype IDataObject,\n\ttype ILoadOptionsFunctions,\n\tNodeOperationError,\n\ttype INodeProperties,\n\ttype IExecuteFunctions,\n\ttype ISupplyDataFunctions,\n} from 'n8n-workflow';\nimport { metadataFilterField } from '@utils/sharedFields';\n\nimport { createVectorStoreNode } from '../shared/createVectorStoreNode/createVectorStoreNode';\n\nimport { validateAndResolveMongoCredentials } from 'n8n-nodes-base/dist/nodes/MongoDb/GenericFunctions';\n\n/**\n * Constants for the name of the credentials and Node parameters.\n */\nexport const MONGODB_CREDENTIALS = 'mongoDb';\nexport const MONGODB_COLLECTION_NAME = 'mongoCollection';\nexport const VECTOR_INDEX_NAME = 'vectorIndexName';\nexport const EMBEDDING_NAME = 'embedding';\nexport const METADATA_FIELD_NAME = 'metadata_field';\nexport const PRE_FILTER_NAME = 'preFilter';\nexport const POST_FILTER_NAME = 'postFilterPipeline';\n\nconst mongoCollectionRLC: INodeProperties = {\n\tdisplayName: 'MongoDB Collection',\n\tname: MONGODB_COLLECTION_NAME,\n\ttype: 'resourceLocator',\n\tdefault: { mode: 'list', value: '' },\n\trequired: true,\n\tmodes: [\n\t\t{\n\t\t\tdisplayName: 'From List',\n\t\t\tname: 'list',\n\t\t\ttype: 'list',\n\t\t\ttypeOptions: {\n\t\t\t\tsearchListMethod: 'mongoCollectionSearch', // Method to fetch collections\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdisplayName: 'Name',\n\t\t\tname: 'name',\n\t\t\ttype: 'string',\n\t\t\tplaceholder: 'e.g. my_collection',\n\t\t},\n\t],\n};\n\nconst vectorIndexName: INodeProperties = {\n\tdisplayName: 'Vector Index Name',\n\tname: VECTOR_INDEX_NAME,\n\ttype: 'string',\n\tdefault: '',\n\tdescription: 'The name of the vector index',\n\trequired: true,\n};\n\nconst embeddingField: INodeProperties = {\n\tdisplayName: 'Embedding',\n\tname: EMBEDDING_NAME,\n\ttype: 'string',\n\tdefault: 'embedding',\n\tdescription: 'The field with the embedding array',\n\trequired: true,\n};\n\nconst metadataField: INodeProperties = {\n\tdisplayName: 'Metadata Field',\n\tname: METADATA_FIELD_NAME,\n\ttype: 'string',\n\tdefault: 'text',\n\tdescription: 'The text field of the raw data',\n\trequired: true,\n};\n\nconst sharedFields: INodeProperties[] = [\n\tmongoCollectionRLC,\n\tembeddingField,\n\tmetadataField,\n\tvectorIndexName,\n];\n\nconst mongoNamespaceField: INodeProperties = {\n\tdisplayName: 'Namespace',\n\tname: 'namespace',\n\ttype: 'string',\n\tdescription: 'Logical partition for documents. Uses metadata.namespace field for filtering.',\n\tdefault: '',\n};\n\nconst preFilterField: INodeProperties = {\n\tdisplayName: 'Pre Filter',\n\tname: PRE_FILTER_NAME,\n\ttype: 'json',\n\ttypeOptions: {\n\t\talwaysOpenEditWindow: true,\n\t},\n\tdefault: '',\n\tplaceholder: '{ \"key\": \"value\" }',\n\thint: 'This is a filter applied in the $vectorSearch stage <a href=\"https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-stage/#atlas-vector-search-pre-filter\">here</a>',\n\trequired: true,\n\tdescription: 'MongoDB Atlas Vector Search pre-filter',\n};\n\nconst postFilterField: INodeProperties = {\n\tdisplayName: 'Post Filter Pipeline',\n\tname: POST_FILTER_NAME,\n\ttype: 'json',\n\ttypeOptions: {\n\t\talwaysOpenEditWindow: true,\n\t},\n\tdefault: '',\n\tplaceholder: '[{ \"$match\": { \"$gt\": \"1950-01-01\" }, ... }]',\n\thint: 'Learn more about aggregation pipeline <a href=\"https://docs.mongodb.com/manual/core/aggregation-pipeline/\">here</a>',\n\trequired: true,\n\tdescription: 'MongoDB aggregation pipeline in JSON format',\n};\n\nconst retrieveFields: INodeProperties[] = [\n\t{\n\t\tdisplayName: 'Options',\n\t\tname: 'options',\n\t\ttype: 'collection',\n\t\tplaceholder: 'Add Option',\n\t\tdefault: {},\n\t\toptions: [mongoNamespaceField, metadataFilterField, preFilterField, postFilterField],\n\t},\n];\n\nconst insertFields: INodeProperties[] = [\n\t{\n\t\tdisplayName: 'Options',\n\t\tname: 'options',\n\t\ttype: 'collection',\n\t\tplaceholder: 'Add Option',\n\t\tdefault: {},\n\t\toptions: [\n\t\t\t{\n\t\t\t\tdisplayName: 'Clear Namespace',\n\t\t\t\tname: 'clearNamespace',\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t\tdescription: 'Whether to clear documents in the namespace before inserting new data',\n\t\t\t},\n\t\t\tmongoNamespaceField,\n\t\t],\n\t},\n];\n\nexport const mongoConfig = {\n\tclient: null as MongoClient | null,\n\tconnectionString: '',\n\tnodeVersion: 0,\n};\n\n/**\n * Type used for cleaner, more intentional typing.\n */\ntype IFunctionsContext = IExecuteFunctions | ISupplyDataFunctions | ILoadOptionsFunctions;\n\n/**\n * Get the mongo client.\n * @param context - The context.\n * @returns the MongoClient for the node.\n */\nexport async function getMongoClient(\n\tcontext: IExecuteFunctions | ISupplyDataFunctions | ILoadOptionsFunctions,\n\tversion: number,\n) {\n\tconst credentials = await context.getCredentials(MONGODB_CREDENTIALS);\n\tconst node = context.getNode();\n\tconst { connectionString } = validateAndResolveMongoCredentials(node, credentials);\n\tif (\n\t\t!mongoConfig.client ||\n\t\tmongoConfig.connectionString !== connectionString ||\n\t\tmongoConfig.nodeVersion !== version\n\t) {\n\t\tif (mongoConfig.client) {\n\t\t\tawait mongoConfig.client.close();\n\t\t}\n\n\t\tmongoConfig.connectionString = connectionString;\n\t\tmongoConfig.nodeVersion = version;\n\t\tmongoConfig.client = new MongoClient(connectionString, {\n\t\t\tappName: 'devrel.integration.n8n_vector_integ',\n\t\t\tdriverInfo: {\n\t\t\t\tname: 'n8n_vector',\n\t\t\t\tversion: version.toString(),\n\t\t\t},\n\t\t});\n\t\tawait mongoConfig.client.connect();\n\t}\n\treturn mongoConfig.client;\n}\n\n/**\n * Get the database object from the MongoClient by the configured name.\n * @param context - The context.\n * @returns the Db object.\n */\nexport async function getDatabase(context: IFunctionsContext, client: MongoClient) {\n\tconst credentials = await context.getCredentials(MONGODB_CREDENTIALS);\n\treturn client.db(credentials.database as string);\n}\n\n/**\n * Get all the collection in the database.\n * @param this The load options context.\n * @returns The list of collections.\n */\nexport async function getCollections(this: ILoadOptionsFunctions) {\n\ttry {\n\t\tconst client = await getMongoClient(this, this.getNode().typeVersion);\n\t\tconst db = await getDatabase(this, client);\n\t\tconst collections = await db.listCollections().toArray();\n\t\tconst results = collections.map((collection) => ({\n\t\t\tname: collection.name,\n\t\t\tvalue: collection.name,\n\t\t}));\n\n\t\treturn { results };\n\t} catch (error) {\n\t\tthrow new NodeOperationError(this.getNode(), `Error: ${error.message}`);\n\t}\n}\n\n/**\n * Get a parameter from the context.\n * @param key - The key of the parameter.\n * @param context - The context.\n * @param itemIndex - The index.\n * @returns The value.\n */\nexport function getParameter(key: string, context: IFunctionsContext, itemIndex: number): string {\n\tconst value = context.getNodeParameter(key, itemIndex, '', {\n\t\textractValue: true,\n\t}) as string;\n\tif (typeof value !== 'string') {\n\t\tthrow new NodeOperationError(context.getNode(), `Parameter ${key} must be a string`);\n\t}\n\treturn value;\n}\n\nexport const getCollectionName = getParameter.bind(null, MONGODB_COLLECTION_NAME);\nexport const getVectorIndexName = getParameter.bind(null, VECTOR_INDEX_NAME);\nexport const getEmbeddingFieldName = getParameter.bind(null, EMBEDDING_NAME);\nexport const getMetadataFieldName = getParameter.bind(null, METADATA_FIELD_NAME);\n\nexport function getFilterValue<T>(\n\tname: string,\n\tcontext: IExecuteFunctions | ISupplyDataFunctions,\n\titemIndex: number,\n): T | undefined {\n\tconst options: IDataObject = context.getNodeParameter('options', itemIndex, {});\n\n\tif (options[name]) {\n\t\tif (typeof options[name] === 'string') {\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(options[name]);\n\t\t\t} catch (error) {\n\t\t\t\tthrow new NodeOperationError(context.getNode(), `Error: ${error.message}`, {\n\t\t\t\t\titemIndex,\n\t\t\t\t\tdescription: `Could not parse JSON for ${name}`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthrow new NodeOperationError(context.getNode(), 'Error: No JSON string provided.', {\n\t\t\titemIndex,\n\t\t\tdescription: `Could not parse JSON for ${name}`,\n\t\t});\n\t}\n\n\treturn undefined;\n}\n\nclass ExtendedMongoDBAtlasVectorSearch extends MongoDBAtlasVectorSearch {\n\tpreFilter: IDataObject;\n\tpostFilterPipeline?: IDataObject[];\n\n\tconstructor(\n\t\tembeddings: EmbeddingsInterface,\n\t\toptions: MongoDBAtlasVectorSearchLibArgs,\n\t\tpreFilter: IDataObject,\n\t\tpostFilterPipeline?: IDataObject[],\n\t) {\n\t\tsuper(embeddings, options);\n\t\tthis.preFilter = preFilter;\n\t\tthis.postFilterPipeline = postFilterPipeline;\n\t}\n\n\tasync similaritySearchVectorWithScore(query: number[], k: number) {\n\t\tconst mergedFilter: MongoDBAtlasVectorSearch['FilterType'] = {\n\t\t\tpreFilter: this.preFilter,\n\t\t\tpostFilterPipeline: this.postFilterPipeline,\n\t\t};\n\t\treturn await super.similaritySearchVectorWithScore(query, k, mergedFilter);\n\t}\n}\n\nexport class VectorStoreMongoDBAtlas extends createVectorStoreNode({\n\tmeta: {\n\t\tdisplayName: 'MongoDB Atlas Vector Store',\n\t\tname: 'vectorStoreMongoDBAtlas',\n\t\tdescription: 'Work with your data in MongoDB Atlas Vector Store',\n\t\ticon: { light: 'file:mongodb.svg', dark: 'file:mongodb.dark.svg' },\n\t\tdocsUrl:\n\t\t\t'https://docs.n8n.io/integrations/builtin/cluster-nodes/root-nodes/n8n-nodes-langchain.vectorstoremongodbatlas/',\n\t\tcredentials: [\n\t\t\t{\n\t\t\t\tname: 'mongoDb',\n\t\t\t\trequired: true,\n\t\t\t},\n\t\t],\n\t\toperationModes: ['load', 'insert', 'retrieve', 'update', 'retrieve-as-tool'],\n\t},\n\tmethods: { listSearch: { mongoCollectionSearch: getCollections } },\n\tretrieveFields,\n\tloadFields: retrieveFields,\n\tinsertFields,\n\tsharedFields,\n\tasync getVectorStoreClient(context, _filter, embeddings, itemIndex) {\n\t\ttry {\n\t\t\tconst client = await getMongoClient(context, context.getNode().typeVersion);\n\t\t\tconst db = await getDatabase(context, client);\n\t\t\tconst collectionName = getCollectionName(context, itemIndex);\n\t\t\tconst mongoVectorIndexName = getVectorIndexName(context, itemIndex);\n\t\t\tconst embeddingFieldName = getEmbeddingFieldName(context, itemIndex);\n\t\t\tconst metadataFieldName = getMetadataFieldName(context, itemIndex);\n\n\t\t\tconst collection = db.collection(collectionName);\n\n\t\t\t// test index exists\n\t\t\tconst indexes = await collection.listSearchIndexes().toArray();\n\n\t\t\tconst indexExists = indexes.some((index) => index.name === mongoVectorIndexName);\n\n\t\t\tif (!indexExists) {\n\t\t\t\tthrow new NodeOperationError(context.getNode(), `Index ${mongoVectorIndexName} not found`, {\n\t\t\t\t\titemIndex,\n\t\t\t\t\tdescription: 'Please check that the index exists in your collection',\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst preFilter = getFilterValue<IDataObject>(PRE_FILTER_NAME, context, itemIndex);\n\t\t\tconst postFilterPipeline = getFilterValue<IDataObject[]>(\n\t\t\t\tPOST_FILTER_NAME,\n\t\t\t\tcontext,\n\t\t\t\titemIndex,\n\t\t\t);\n\n\t\t\treturn new ExtendedMongoDBAtlasVectorSearch(\n\t\t\t\tembeddings,\n\t\t\t\t{\n\t\t\t\t\tcollection,\n\t\t\t\t\tindexName: mongoVectorIndexName, // Default index name\n\t\t\t\t\ttextKey: metadataFieldName, // Field containing raw text\n\t\t\t\t\tembeddingKey: embeddingFieldName, // Field containing embeddings\n\t\t\t\t},\n\t\t\t\tpreFilter ?? {},\n\t\t\t\tpostFilterPipeline,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (error instanceof NodeOperationError) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tthrow new NodeOperationError(context.getNode(), `Error: ${error.message}`, {\n\t\t\t\titemIndex,\n\t\t\t\tdescription: 'Please check your MongoDB Atlas connection details',\n\t\t\t});\n\t\t}\n\t},\n\tasync populateVectorStore(context, embeddings, documents, itemIndex) {\n\t\ttry {\n\t\t\tconst client = await getMongoClient(context, context.getNode().typeVersion);\n\t\t\tconst db = await getDatabase(context, client);\n\t\t\tconst collectionName = getCollectionName(context, itemIndex);\n\t\t\tconst mongoVectorIndexName = getVectorIndexName(context, itemIndex);\n\t\t\tconst embeddingFieldName = getEmbeddingFieldName(context, itemIndex);\n\t\t\tconst metadataFieldName = getMetadataFieldName(context, itemIndex);\n\n\t\t\t// Check if collection exists\n\t\t\tconst collections = await db.listCollections({ name: collectionName }).toArray();\n\t\t\tif (collections.length === 0) {\n\t\t\t\tawait db.createCollection(collectionName);\n\t\t\t}\n\t\t\tconst collection = db.collection(collectionName);\n\t\t\tawait ExtendedMongoDBAtlasVectorSearch.fromDocuments(documents, embeddings, {\n\t\t\t\tcollection,\n\t\t\t\tindexName: mongoVectorIndexName, // Default index name\n\t\t\t\ttextKey: metadataFieldName, // Field containing raw text\n\t\t\t\tembeddingKey: embeddingFieldName, // Field containing embeddings\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new NodeOperationError(context.getNode(), `Error: ${error.message}`, {\n\t\t\t\titemIndex,\n\t\t\t\tdescription: 'Please check your MongoDB Atlas connection details',\n\t\t\t});\n\t\t}\n\t},\n}) {}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,qBAA+E;AAC/E,IAAAA,kBAA4B;AAC5B,0BAOO;AACP,0BAAoC;AAEpC,mCAAsC;AAEtC,8BAAmD;AAK5C,MAAM,sBAAsB;AAC5B,MAAM,0BAA0B;AAChC,MAAM,oBAAoB;AAC1B,MAAM,iBAAiB;AACvB,MAAM,sBAAsB;AAC5B,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AAEhC,MAAM,qBAAsC;AAAA,EAC3C,aAAa;AAAA,EACb,MAAM;AAAA,EACN,MAAM;AAAA,EACN,SAAS,EAAE,MAAM,QAAQ,OAAO,GAAG;AAAA,EACnC,UAAU;AAAA,EACV,OAAO;AAAA,IACN;AAAA,MACC,aAAa;AAAA,MACb,MAAM;AAAA,MACN,MAAM;AAAA,MACN,aAAa;AAAA,QACZ,kBAAkB;AAAA;AAAA,MACnB;AAAA,IACD;AAAA,IACA;AAAA,MACC,aAAa;AAAA,MACb,MAAM;AAAA,MACN,MAAM;AAAA,MACN,aAAa;AAAA,IACd;AAAA,EACD;AACD;AAEA,MAAM,kBAAmC;AAAA,EACxC,aAAa;AAAA,EACb,MAAM;AAAA,EACN,MAAM;AAAA,EACN,SAAS;AAAA,EACT,aAAa;AAAA,EACb,UAAU;AACX;AAEA,MAAM,iBAAkC;AAAA,EACvC,aAAa;AAAA,EACb,MAAM;AAAA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,EACD;AACD,CAAC,EAAE;AAAC;","names":["import_mongodb"]}
@@ -41,7 +41,7 @@ const modelRLC = {
41
41
  displayName: "ID",
42
42
  name: "id",
43
43
  type: "string",
44
- placeholder: "e.g. claude-3-5-sonnet-20241022"
44
+ placeholder: "e.g. claude-sonnet-4-5-20250929"
45
45
  }
46
46
  ]
47
47
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../nodes/vendors/Anthropic/actions/descriptions.ts"],"sourcesContent":["import type { INodeProperties } from 'n8n-workflow';\n\nexport const modelRLC: INodeProperties = {\n\tdisplayName: 'Model',\n\tname: 'modelId',\n\ttype: 'resourceLocator',\n\tdefault: { mode: 'list', value: '' },\n\trequired: true,\n\tmodes: [\n\t\t{\n\t\t\tdisplayName: 'From List',\n\t\t\tname: 'list',\n\t\t\ttype: 'list',\n\t\t\ttypeOptions: {\n\t\t\t\tsearchListMethod: 'modelSearch',\n\t\t\t\tsearchable: true,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdisplayName: 'ID',\n\t\t\tname: 'id',\n\t\t\ttype: 'string',\n\t\t\tplaceholder: 'e.g. claude-3-5-sonnet-20241022',\n\t\t},\n\t],\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEO,MAAM,WAA4B;AAAA,EACxC,aAAa;AAAA,EACb,MAAM;AAAA,EACN,MAAM;AAAA,EACN,SAAS,EAAE,MAAM,QAAQ,OAAO,GAAG;AAAA,EACnC,UAAU;AAAA,EACV,OAAO;AAAA,IACN;AAAA,MACC,aAAa;AAAA,MACb,MAAM;AAAA,MACN,MAAM;AAAA,MACN,aAAa;AAAA,QACZ,kBAAkB;AAAA,QAClB,YAAY;AAAA,MACb;AAAA,IACD;AAAA,IACA;AAAA,MACC,aAAa;AAAA,MACb,MAAM;AAAA,MACN,MAAM;AAAA,MACN,aAAa;AAAA,IACd;AAAA,EACD;AACD;","names":[]}
1
+ {"version":3,"sources":["../../../../../nodes/vendors/Anthropic/actions/descriptions.ts"],"sourcesContent":["import type { INodeProperties } from 'n8n-workflow';\n\nexport const modelRLC: INodeProperties = {\n\tdisplayName: 'Model',\n\tname: 'modelId',\n\ttype: 'resourceLocator',\n\tdefault: { mode: 'list', value: '' },\n\trequired: true,\n\tmodes: [\n\t\t{\n\t\t\tdisplayName: 'From List',\n\t\t\tname: 'list',\n\t\t\ttype: 'list',\n\t\t\ttypeOptions: {\n\t\t\t\tsearchListMethod: 'modelSearch',\n\t\t\t\tsearchable: true,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdisplayName: 'ID',\n\t\t\tname: 'id',\n\t\t\ttype: 'string',\n\t\t\tplaceholder: 'e.g. claude-sonnet-4-5-20250929',\n\t\t},\n\t],\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEO,MAAM,WAA4B;AAAA,EACxC,aAAa;AAAA,EACb,MAAM;AAAA,EACN,MAAM;AAAA,EACN,SAAS,EAAE,MAAM,QAAQ,OAAO,GAAG;AAAA,EACnC,UAAU;AAAA,EACV,OAAO;AAAA,IACN;AAAA,MACC,aAAa;AAAA,MACb,MAAM;AAAA,MACN,MAAM;AAAA,MACN,aAAa;AAAA,QACZ,kBAAkB;AAAA,QAClB,YAAY;AAAA,MACb;AAAA,IACD;AAAA,IACA;AAAA,MACC,aAAa;AAAA,MACb,MAAM;AAAA,MACN,MAAM;AAAA,MACN,aAAa;AAAA,IACd;AAAA,EACD;AACD;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../nodes/vendors/OpenAi/helpers/interfaces.ts"],"sourcesContent":["import { type OpenAIClient } from '@langchain/openai';\nimport type { IDataObject } from 'n8n-workflow';\nimport type {\n\tComputerTool,\n\tCustomTool,\n\tFileSearchTool,\n\tFunctionTool,\n\tResponseInputContent,\n\tResponseInputItem,\n\tTool,\n\tWebSearchTool as OpenAIChatWebSearchTool,\n} from 'openai/resources/responses/responses';\n\nexport type ChatResponse = OpenAIClient.Responses.Response;\nexport type ChatContent = ResponseInputContent[];\nexport type ChatInputItem = OpenAIClient.Responses.ResponseInputItem.Message;\n\n// FIXME: remove these overrides, when langchain-openai is updated with the new types\nexport type WebSearchTool = Omit<OpenAIChatWebSearchTool, 'type'> & {\n\ttype: 'web_search';\n\tfilters?: {\n\t\tallowed_domains?: string[];\n\t};\n};\nexport type McpTool = Tool.Mcp & {\n\ttype: 'mcp';\n\tauthorization?: string;\n\tconnector_id?: string;\n};\n\nexport type ChatTool =\n\t| FunctionTool\n\t| FileSearchTool\n\t| WebSearchTool\n\t| ComputerTool\n\t| McpTool\n\t| Tool.CodeInterpreter\n\t| Tool.ImageGeneration\n\t| Tool.LocalShell\n\t| CustomTool;\n\nexport type ChatResponseRequest = Omit<\n\tOpenAIClient.Responses.ResponseCreateParamsNonStreaming,\n\t'input'\n> & {\n\tmax_tool_calls?: number;\n\tconversation?:\n\t\t| string\n\t\t| {\n\t\t\t\tid: string;\n\t\t };\n\tinput: ResponseInputItem[];\n\ttop_logprobs?: number;\n\ttools?: ChatTool[];\n};\n\nexport type ChatCompletion = {\n\tid: string;\n\tobject: string;\n\tcreated: number;\n\tmodel: string;\n\tchoices: Array<{\n\t\tindex: number;\n\t\tmessage: {\n\t\t\trole: string;\n\t\t\tcontent: string;\n\t\t\ttool_calls?: Array<{\n\t\t\t\tid: string;\n\t\t\t\ttype: 'function';\n\t\t\t\tfunction: {\n\t\t\t\t\tname: string;\n\t\t\t\t\targuments: string;\n\t\t\t\t};\n\t\t\t}>;\n\t\t};\n\t\tfinish_reason?: 'tool_calls';\n\t}>;\n\tusage: {\n\t\tprompt_tokens: number;\n\t\tcompletion_tokens: number;\n\t\ttotal_tokens: number;\n\t};\n\tsystem_fingerprint: string;\n};\n\nexport type ThreadMessage = {\n\tid: string;\n\tobject: string;\n\tcreated_at: number;\n\tthread_id: string;\n\trole: string;\n\tcontent: Array<{\n\t\ttype: string;\n\t\ttext: {\n\t\t\tvalue: string;\n\t\t\tannotations: string[];\n\t\t};\n\t}>;\n\tfile_ids: string[];\n\tassistant_id: string;\n\trun_id: string;\n\tmetadata: IDataObject;\n};\n\nexport type ExternalApiCallOptions = {\n\tcallExternalApi: boolean;\n\turl: string;\n\tpath: string;\n\tmethod: string;\n\trequestOptions: IDataObject;\n\tsendParametersIn: string;\n};\n\nexport type VideoJob = {\n\tid: string;\n\tcompleted_at?: number;\n\tcreated_at: number;\n\terror?: {\n\t\tcode: string;\n\t\tmessage: string;\n\t};\n\texpires_at?: number;\n\tmodel: string;\n\tobject: 'video';\n\tprogress?: number;\n\tremixed_from_video_id?: string;\n\tseconds: string;\n\tsize: string;\n\tstatus: 'completed' | 'queued' | 'in_progress';\n};\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
1
+ {"version":3,"sources":["../../../../../nodes/vendors/OpenAi/helpers/interfaces.ts"],"sourcesContent":["import { type OpenAIClient } from '@langchain/openai';\nimport type { IDataObject } from 'n8n-workflow';\nimport type {\n\tComputerTool,\n\tCustomTool,\n\tFileSearchTool,\n\tFunctionTool,\n\tResponseInputContent,\n\tResponseInputItem,\n\tTool,\n\tWebSearchTool as OpenAIChatWebSearchTool,\n} from 'openai/resources/responses/responses';\n\nexport type ChatResponse = OpenAIClient.Responses.Response;\nexport type ChatContent = ResponseInputContent[];\nexport type ChatInputItem = OpenAIClient.Responses.ResponseInputItem.Message;\n\n// FIXME: remove these overrides, when langchain-openai is updated with the new types\nexport type WebSearchTool = Omit<OpenAIChatWebSearchTool, 'type'> & {\n\ttype: 'web_search';\n\tfilters?: {\n\t\tallowed_domains?: string[];\n\t};\n};\n\nexport type ChatTool =\n\t| FunctionTool\n\t| FileSearchTool\n\t| WebSearchTool\n\t| ComputerTool\n\t| Tool.CodeInterpreter\n\t| Tool.ImageGeneration\n\t| Tool.LocalShell\n\t| CustomTool;\n\nexport type ChatResponseRequest = Omit<\n\tOpenAIClient.Responses.ResponseCreateParamsNonStreaming,\n\t'input'\n> & {\n\tmax_tool_calls?: number;\n\tconversation?:\n\t\t| string\n\t\t| {\n\t\t\t\tid: string;\n\t\t };\n\tinput: ResponseInputItem[];\n\ttop_logprobs?: number;\n\ttools?: ChatTool[];\n};\n\nexport type ChatCompletion = {\n\tid: string;\n\tobject: string;\n\tcreated: number;\n\tmodel: string;\n\tchoices: Array<{\n\t\tindex: number;\n\t\tmessage: {\n\t\t\trole: string;\n\t\t\tcontent: string;\n\t\t\ttool_calls?: Array<{\n\t\t\t\tid: string;\n\t\t\t\ttype: 'function';\n\t\t\t\tfunction: {\n\t\t\t\t\tname: string;\n\t\t\t\t\targuments: string;\n\t\t\t\t};\n\t\t\t}>;\n\t\t};\n\t\tfinish_reason?: 'tool_calls';\n\t}>;\n\tusage: {\n\t\tprompt_tokens: number;\n\t\tcompletion_tokens: number;\n\t\ttotal_tokens: number;\n\t};\n\tsystem_fingerprint: string;\n};\n\nexport type ThreadMessage = {\n\tid: string;\n\tobject: string;\n\tcreated_at: number;\n\tthread_id: string;\n\trole: string;\n\tcontent: Array<{\n\t\ttype: string;\n\t\ttext: {\n\t\t\tvalue: string;\n\t\t\tannotations: string[];\n\t\t};\n\t}>;\n\tfile_ids: string[];\n\tassistant_id: string;\n\trun_id: string;\n\tmetadata: IDataObject;\n};\n\nexport type ExternalApiCallOptions = {\n\tcallExternalApi: boolean;\n\turl: string;\n\tpath: string;\n\tmethod: string;\n\trequestOptions: IDataObject;\n\tsendParametersIn: string;\n};\n\nexport type VideoJob = {\n\tid: string;\n\tcompleted_at?: number;\n\tcreated_at: number;\n\terror?: {\n\t\tcode: string;\n\t\tmessage: string;\n\t};\n\texpires_at?: number;\n\tmodel: string;\n\tobject: 'video';\n\tprogress?: number;\n\tremixed_from_video_id?: string;\n\tseconds: string;\n\tsize: string;\n\tstatus: 'completed' | 'queued' | 'in_progress';\n};\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
@@ -219,30 +219,6 @@ async function createRequest(i, { model, messages, options, builtInTools, tools
219
219
  })
220
220
  );
221
221
  }
222
- const mcpServers = (0, import_get.default)(builtInTools.mcpServers, "mcpServerOptions");
223
- if (Array.isArray(mcpServers) && mcpServers.length) {
224
- for (const mcpServer of mcpServers) {
225
- let allowedTools;
226
- const allowedToolsRaw = (0, import_get.default)(mcpServer, "allowedTools", "");
227
- if (allowedToolsRaw) {
228
- allowedTools = toArray(allowedToolsRaw);
229
- }
230
- const headersRaw = (0, import_get.default)(mcpServer, "headers", "");
231
- newTools.push(
232
- removeEmptyProperties({
233
- type: "mcp",
234
- server_label: mcpServer.serverLabel,
235
- server_url: mcpServer.serverUrl,
236
- connector_id: mcpServer.connectorId,
237
- authorization: mcpServer.authorization,
238
- allowed_tools: allowedTools,
239
- headers: headersRaw ? (0, import_n8n_workflow.jsonParse)(headersRaw, { errorMessage: "Failed to parse headers" }) : void 0,
240
- require_approval: "never",
241
- server_description: mcpServer.serverDescription
242
- })
243
- );
244
- }
245
- }
246
222
  if (builtInTools.codeInterpreter) {
247
223
  newTools.push({
248
224
  type: "code_interpreter",