Page MenuHomePhabricator
Paste P88721

nodejs client for the liftwing LaBSE embeddings
ActivePublic

Authored by santhosh on Feb 9 2026, 5:28 AM.
Referenced Files
F71762568: nodejs client for the liftwing LaBSE embeddings
Feb 9 2026, 5:28 AM
Subscribers
None
#!/usr/bin/env node
const http = require("http");
/**
* Get embedding vector from the API
* @param {string[]} text - Text to get embedding for
* @returns {Promise<number[]>} - Embedding vector
*/
async function getEmbedding(texts) {
const postData = JSON.stringify({
input: texts,
});
const options = {
hostname: "localhost",
port: 8080,
path: "/v1/models/labse-embedding:predict",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(postData),
},
};
return new Promise((resolve, reject) => {
const req = http.request(options, (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
try {
const response = JSON.parse(data);
// Adjust this based on the actual API response structure
const embeddings = response.data;
resolve(embeddings);
} catch (error) {
reject(new Error(`Failed to parse response: ${error.message}`));
}
});
});
req.on("error", (error) => {
reject(new Error(`API request failed: ${error.message}`));
});
req.write(postData);
req.end();
});
}
/**
* Calculate cosine similarity between two normalized vectors
* @param {number[]} vec1 - First normalized vector
* @param {number[]} vec2 - Second normalized vector
* @returns {number} - Similarity score between -1 and 1
*/
function cosineSimilarity(vec1, vec2) {
if (vec1.length !== vec2.length) {
throw new Error("Vectors must have the same length");
}
let dotProduct = 0;
for (let i = 0; i < vec1.length; i++) {
dotProduct += vec1[i] * vec2[i];
}
return dotProduct;
}
/**
* Compare two strings for similarity using embeddings
* @param {string} str1 - First string to compare
* @param {string} str2 - Second string to compare
* @returns {Promise<number>} - Similarity score between 0 and 1
*/
async function compareStrings(str1, str2) {
console.log("Getting embeddings ...");
const embeddings = await getEmbedding([str1, str2]);
console.log("Calculating similarity...");
const similarity = cosineSimilarity(
embeddings[0].embedding,
embeddings[1].embedding,
);
return similarity;
}
// Main execution
async function main() {
const args = process.argv.slice(2);
if (args.length < 2) {
console.error("Usage: node compare-strings.js <string1> <string2>");
console.error('Example: node compare-strings.js "Hello world" "Hi there"');
process.exit(1);
}
const string1 = args[0];
const string2 = args[1];
console.log(`\nComparing strings:`);
console.log(`String 1: "${string1}"`);
console.log(`String 2: "${string2}"\n`);
try {
const similarity = await compareStrings(string1, string2);
console.log(
`\nSimilarity score: ${similarity.toFixed(4)} (${(similarity * 100).toFixed(2)}%)`,
);
} catch (error) {
console.error(`Error: ${error.message}`);
process.exit(1);
}
}
main();