UNPKG

ai-utils.js

Version:

Build AI applications, chatbots, and agents with JavaScript and TypeScript.

27 lines (26 loc) 825 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.cosineSimilarity = void 0; /** * Calculates the cosine similarity between two vectors. They must have the same length. * * @param a The first vector. * @param b The second vector. * * @returns The cosine similarity between the two vectors. * * @see https://en.wikipedia.org/wiki/Cosine_similarity */ function cosineSimilarity(a, b) { if (a.length !== b.length) { throw new Error(`Vectors must have the same length (a: ${a.length}, b: ${b.length})`); } return dotProduct(a, b) / (magnitude(a) * magnitude(b)); } exports.cosineSimilarity = cosineSimilarity; function dotProduct(a, b) { return a.reduce((acc, val, i) => acc + val * b[i], 0); } function magnitude(a) { return Math.sqrt(dotProduct(a, a)); }