n8n-nodes-rckflr-cosine-similarity
Version:
A custom n8n node to calculate cosine similarity between two arrays of vectors.
73 lines • 2.75 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Centroid = void 0;
const n8n_workflow_1 = require("n8n-workflow");
class Centroid {
constructor() {
this.description = {
displayName: 'Centroid',
name: 'centroid',
group: ['transform'],
version: 1,
description: 'Calculates the centroid of an array of vectors',
defaults: {
name: 'Centroid',
},
inputs: ['main'],
outputs: ['main'],
properties: [
{
displayName: 'Array of Vectors',
name: 'vectors',
type: 'json',
default: '',
description: 'Enter an array of vectors directly (e.g., [[1,2,3],[4,5,6],[7,8,9]])',
},
],
};
}
async execute() {
let vectors = this.getNodeParameter('vectors', 0);
if (!vectors) {
const items = this.getInputData();
if (items.length > 0) {
if (Array.isArray(items[0].json)) {
vectors = items[0].json;
}
else if (Array.isArray(items[0].json.vectors)) {
vectors = items[0].json.vectors;
}
}
}
if (typeof vectors === 'string') {
try {
vectors = JSON.parse(vectors);
}
catch (error) {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'The format of the vector array is not valid.');
}
}
if (!Array.isArray(vectors) || vectors.length === 0) {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'You must provide a valid array of vectors.');
}
if (!Array.isArray(vectors[0])) {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Each element of the array must be a vector (another array).');
}
const dimension = vectors[0].length;
for (const vector of vectors) {
if (!Array.isArray(vector) || vector.length !== dimension) {
throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'All vectors must have the same dimension.');
}
}
const sum = new Array(dimension).fill(0);
for (const vector of vectors) {
for (let j = 0; j < dimension; j++) {
sum[j] += vector[j];
}
}
const centroid = sum.map((value) => value / vectors.length);
return [[{ json: { centroid } }]];
}
}
exports.Centroid = Centroid;
//# sourceMappingURL=Centroid.node.js.map