@n8n/n8n-nodes-langchain
Version:
229 lines • 9.07 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildSteps = buildSteps;
const messages_1 = require("@langchain/core/messages");
const omit_1 = __importDefault(require("lodash/omit"));
const n8n_workflow_1 = require("n8n-workflow");
function extractProviderMetadata(metadata) {
if (!metadata)
return {};
const thoughtSignature = typeof metadata.google?.thoughtSignature === 'string'
? metadata.google.thoughtSignature
: undefined;
const thinkingContent = typeof metadata.anthropic?.thinkingContent === 'string'
? metadata.anthropic.thinkingContent
: undefined;
const thinkingType = metadata.anthropic?.thinkingType === 'thinking' ||
metadata.anthropic?.thinkingType === 'redacted_thinking'
? metadata.anthropic.thinkingType
: undefined;
const thinkingSignature = typeof metadata.anthropic?.thinkingSignature === 'string'
? metadata.anthropic.thinkingSignature
: undefined;
const reasoningContent = typeof metadata.deepseek?.reasoningContent === 'string'
? metadata.deepseek.reasoningContent
: undefined;
return {
thoughtSignature,
thinkingContent,
thinkingType,
thinkingSignature,
reasoningContent,
};
}
function buildAnthropicContentBlocks(thinkingContent, thinkingType, thinkingSignature, toolCalls) {
const thinkingBlock = thinkingType === 'thinking'
? {
type: 'thinking',
thinking: thinkingContent,
signature: thinkingSignature ?? '',
}
: {
type: 'redacted_thinking',
data: thinkingContent,
};
const toolUseBlocks = toolCalls.map(({ toolInput, toolId, toolName }) => ({
type: 'tool_use',
id: toolId,
name: toolName,
input: (0, omit_1.default)(toolInput, 'tool'),
}));
return [thinkingBlock, ...toolUseBlocks];
}
function buildMessageContent(providerMetadata, toolInput, toolId, toolName) {
const { thinkingContent, thinkingType, thinkingSignature } = providerMetadata;
if (thinkingContent !== undefined && thinkingType) {
return buildAnthropicContentBlocks(thinkingContent, thinkingType, thinkingSignature, [
{ toolInput, toolId, toolName },
]);
}
return null;
}
function resolveToolName(tool) {
return (tool.action.metadata?.hitl?.toolName ??
(typeof tool.action.input?.tool === 'string' ? tool.action.input.tool : undefined) ??
(0, n8n_workflow_1.nodeNameToToolName)(tool.action.nodeName));
}
function buildGeminiAdditionalKwargs(toolCalls, thoughtSignature, hasLeadingTextPart) {
const signatures = [
...(hasLeadingTextPart ? [''] : []),
thoughtSignature,
...toolCalls.slice(1).map(() => ''),
];
return {
__gemini_function_call_thought_signatures__: {
[toolCalls[0].id]: thoughtSignature,
},
tool_calls: toolCalls.map((tc) => ({ id: tc.id, name: tc.name, args: tc.args })),
signatures,
};
}
function buildIndividualAIMessage(toolId, toolName, toolInput, providerMetadata) {
const toolCall = {
id: toolId,
name: toolName,
args: toolInput,
type: 'tool_call',
};
const content = buildMessageContent(providerMetadata, toolInput, toolId, toolName);
const additionalKwargs = providerMetadata.thoughtSignature
? buildGeminiAdditionalKwargs([{ id: toolId, name: toolName, args: toolInput }], providerMetadata.thoughtSignature, content !== null && content.length > 0)
: {};
if (providerMetadata.reasoningContent) {
additionalKwargs.reasoning_content = providerMetadata.reasoningContent;
}
return new messages_1.AIMessage({
content: content ?? [],
...(content === null && { tool_calls: [toolCall] }),
...(Object.keys(additionalKwargs).length > 0 && { additional_kwargs: additionalKwargs }),
});
}
function buildSharedGeminiAIMessage(processedTools, thoughtSignature) {
const allToolCalls = processedTools.map((pt) => ({
id: pt.toolId,
name: pt.toolName,
args: pt.toolInput,
type: 'tool_call',
}));
const toolNames = processedTools.map((pt) => pt.nodeName).join(', ');
return new messages_1.AIMessage({
content: `Calling tools: ${toolNames}`,
tool_calls: allToolCalls,
additional_kwargs: buildGeminiAdditionalKwargs(allToolCalls, thoughtSignature, true),
});
}
function getSharedAnthropicThinking(batchTools) {
if (batchTools.length < 2)
return undefined;
const first = batchTools[0].providerMetadata;
if (first.thinkingContent === undefined || !first.thinkingType)
return undefined;
const shared = {
thinkingContent: first.thinkingContent,
thinkingType: first.thinkingType,
thinkingSignature: first.thinkingSignature,
};
const matches = batchTools.every((tool) => {
const metadata = tool.providerMetadata;
return (metadata.thinkingContent === shared.thinkingContent &&
metadata.thinkingType === shared.thinkingType &&
metadata.thinkingSignature === shared.thinkingSignature);
});
return matches ? shared : undefined;
}
function buildSharedAnthropicAIMessage(processedTools, sharedThinking) {
const content = buildAnthropicContentBlocks(sharedThinking.thinkingContent, sharedThinking.thinkingType, sharedThinking.thinkingSignature, processedTools.map(({ toolInput, toolId, toolName }) => ({
toolInput,
toolId,
toolName,
})));
return new messages_1.AIMessage({ content });
}
function buildObservation(toolData) {
const aiToolData = toolData?.data?.ai_tool?.[0]?.map((item) => item?.json);
if (aiToolData && aiToolData.length > 0) {
return JSON.stringify(aiToolData);
}
if (toolData?.error) {
const errorInfo = {
error: toolData.error.message ?? 'Unknown error',
...(toolData.error.name && { errorType: toolData.error.name }),
};
return JSON.stringify(errorInfo);
}
return JSON.stringify('');
}
function buildSteps(response, itemIndex) {
const steps = [];
if (!response)
return steps;
const responses = response.actionResponses ?? [];
if (response.metadata?.previousRequests) {
steps.push(...response.metadata.previousRequests);
}
const batchTools = [];
for (const tool of responses) {
if (tool.action?.metadata?.itemIndex !== itemIndex)
continue;
const toolInput = tool.action.input;
if (!tool.data)
continue;
const existingStep = steps.find((s) => s.action.toolCallId === tool.action.id);
if (existingStep)
continue;
const providerMetadata = extractProviderMetadata(tool.action.metadata);
const toolId = tool.action.id;
const toolName = resolveToolName(tool);
batchTools.push({
tool,
toolInput,
toolId,
toolName,
nodeName: tool.action.nodeName,
providerMetadata,
});
}
const sharedThoughtSignature = batchTools.find((bt) => bt.providerMetadata.thoughtSignature)
?.providerMetadata.thoughtSignature;
let sharedAIMessage;
if (sharedThoughtSignature && batchTools.length > 1) {
sharedAIMessage = buildSharedGeminiAIMessage(batchTools, sharedThoughtSignature);
}
else {
const sharedAnthropicThinking = getSharedAnthropicThinking(batchTools);
if (sharedAnthropicThinking) {
sharedAIMessage = buildSharedAnthropicAIMessage(batchTools, sharedAnthropicThinking);
}
}
for (let i = 0; i < batchTools.length; i++) {
const { tool, toolInput, toolId, toolName, nodeName, providerMetadata } = batchTools[i];
const observation = buildObservation(tool.data);
const { id, log, type, ...toolInputForResult } = toolInput;
const messageLog = sharedAIMessage
? i === 0
? [sharedAIMessage]
: []
: [buildIndividualAIMessage(toolId, toolName, toolInput, providerMetadata)];
const logFallback = messageLog[0]?.content?.length
? messageLog[0]?.content
: `Calling ${nodeName}`;
steps.push({
action: {
tool: toolName,
toolInput: toolInputForResult,
log: toolInput.log || logFallback,
messageLog,
toolCallId: toolId,
type: toolInput.type || 'tool_call',
...(tool.action.metadata?.hitl && { hitlDenied: true }),
...(tool.data.error && { errored: true }),
},
observation,
});
}
return steps;
}
//# sourceMappingURL=buildSteps.js.map