@n8n/n8n-nodes-langchain
Version:

253 lines • 9.49 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var responses_exports = {};
__export(responses_exports, {
createRequest: () => createRequest,
formatInputMessages: () => formatInputMessages
});
module.exports = __toCommonJS(responses_exports);
var import_get = __toESM(require("lodash/get"));
var import_isObject = __toESM(require("lodash/isObject"));
var import_n8n_workflow = require("n8n-workflow");
var import_binary_data = require("../../../../helpers/binary-data");
const toArray = (str) => str.split(",").map((e) => e.trim());
const removeEmptyProperties = (rest) => {
return Object.keys(rest).filter(
(k) => rest[k] !== "" && rest[k] !== void 0 && !((0, import_isObject.default)(rest[k]) && (0, import_n8n_workflow.isObjectEmpty)(rest[k]))
).reduce((a, k) => ({ ...a, [k]: rest[k] }), {});
};
async function formatInputMessages(i, messages) {
return await Promise.all(
messages.map(async (message) => {
const role = message.role;
let content = [];
if (message.type === "text" || !message.type) {
content = [{ type: "input_text", text: message.content }];
} else if (message.type === "image") {
const detail = message.imageDetail || "auto";
if (message.imageType === "base64") {
const { fileContent, contentType } = await (0, import_binary_data.getBinaryDataFile)(
this,
i,
message.binaryPropertyName
);
const buffer = await this.helpers.binaryToBuffer(fileContent);
content = [
{
type: "input_image",
detail,
image_url: `data:${contentType};base64,${buffer.toString("base64")}`
}
];
} else {
content = [
{
type: "input_image",
detail,
...message.imageType === "url" && { image_url: message.imageUrl },
...message.imageType === "fileId" && { file_id: message.fileId }
}
];
}
} else if (message.type === "file") {
if (message.fileType === "base64") {
const { fileContent, contentType } = await (0, import_binary_data.getBinaryDataFile)(
this,
i,
message.binaryPropertyName
);
const buffer = await this.helpers.binaryToBuffer(fileContent);
content = [
{
type: "input_file",
filename: message.fileName,
file_data: `data:${contentType};base64,${buffer.toString("base64")}`
}
];
} else {
content = [
{
type: "input_file",
...message.fileType === "url" && { file_url: message.fileUrl },
...message.fileType === "fileId" && { file_id: message.fileId }
}
];
}
}
return { role, content };
})
);
}
async function createRequest(i, { model, messages, options, builtInTools, tools }) {
const body = {
model,
input: await formatInputMessages.call(this, i, messages),
parallel_tool_calls: (0, import_get.default)(options, "parallelToolCalls", true),
store: (0, import_get.default)(options, "store", true),
instructions: options.instructions,
max_output_tokens: options.maxTokens,
previous_response_id: options.previousResponseId,
prompt_cache_key: options.promptCacheKey,
safety_identifier: options.safetyIdentifier,
service_tier: options.serviceTier,
temperature: options.temperature,
top_p: options.topP,
top_logprobs: options.topLogprobs,
tools,
max_tool_calls: options.maxToolCalls,
background: (0, import_get.default)(options, "backgroundMode.values.enabled", false)
};
if (options.truncation !== void 0) {
body.truncation = !!options.truncation ? "auto" : "disabled";
}
if (options.conversationId) {
body.conversation = options.conversationId;
}
if (Array.isArray(options.include) && options.include?.length) {
body.include = options.include;
}
if (options.metadata) {
body.metadata = (0, import_n8n_workflow.jsonParse)(options.metadata, {
errorMessage: "Failed to parse metadata"
});
}
if (options.promptConfig) {
const prompt = (0, import_get.default)(options, "promptConfig.promptOptions");
body.prompt = removeEmptyProperties({
id: prompt.promptId,
version: prompt.version,
...prompt.variables && {
variables: (0, import_n8n_workflow.jsonParse)(prompt.variables, {
errorMessage: "Failed to parse prompt variables"
})
}
});
}
if (options.reasoning) {
const reasoning = (0, import_get.default)(options, "reasoning.reasoningOptions");
body.reasoning = removeEmptyProperties({
effort: reasoning.effort,
summary: reasoning.summary && reasoning.summary !== "none" ? reasoning.summary : void 0
});
}
if (options.textFormat) {
const textOptions = (0, import_get.default)(options, "textFormat.textOptions");
const textConfig = {
verbosity: textOptions.verbosity
};
if (textOptions.type === "json_schema") {
textConfig.format = {
type: textOptions.type,
name: textOptions.name,
schema: (0, import_n8n_workflow.jsonParse)(textOptions.schema, {
errorMessage: "Failed to parse schema"
})
};
} else if (textOptions.type === "json_object") {
textConfig.format = {
type: textOptions.type
};
body.input = [
{
role: "system",
content: [
{ type: "input_text", text: "You are a helpful assistant designed to output JSON." }
]
},
...body.input
];
} else if (textOptions.type === "text") {
textConfig.format = {
type: textOptions.type
};
}
if (textConfig.format) {
textConfig.format = removeEmptyProperties(textConfig.format);
}
body.text = textConfig;
}
if (builtInTools) {
const newTools = body.tools ?? [];
const webSearchOptions = (0, import_get.default)(builtInTools, "webSearch");
if (webSearchOptions) {
let allowedDomains;
const allowedDomainsRaw = (0, import_get.default)(webSearchOptions, "allowedDomains", "");
if (allowedDomainsRaw) {
allowedDomains = toArray(allowedDomainsRaw);
}
let userLocation;
if (webSearchOptions.country || webSearchOptions.city || webSearchOptions.region) {
userLocation = {
type: "approximate",
country: webSearchOptions.country,
city: webSearchOptions.city,
region: webSearchOptions.region
};
}
newTools.push(
removeEmptyProperties({
type: "web_search",
search_context_size: (0, import_get.default)(webSearchOptions, "searchContextSize", "medium"),
user_location: userLocation,
...allowedDomains && { filters: { allowed_domains: allowedDomains } }
})
);
}
if (builtInTools.codeInterpreter) {
newTools.push({
type: "code_interpreter",
container: {
type: "auto"
}
});
}
if (builtInTools.fileSearch) {
const vectorStoreIds = (0, import_get.default)(builtInTools.fileSearch, "vectorStoreIds", "[]");
const filters = (0, import_get.default)(builtInTools.fileSearch, "filters", "{}");
newTools.push(
removeEmptyProperties({
type: "file_search",
vector_store_ids: (0, import_n8n_workflow.jsonParse)(vectorStoreIds, {
errorMessage: "Failed to parse vector store IDs"
}),
filters: filters ? (0, import_n8n_workflow.jsonParse)(filters, { errorMessage: "Failed to parse filters" }) : void 0,
max_num_results: (0, import_get.default)(builtInTools.fileSearch, "maxResults")
})
);
}
body.tools = newTools;
}
return await removeEmptyProperties(body);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
createRequest,
formatInputMessages
});
//# sourceMappingURL=responses.js.map