Generative AI with Node JS in Hindi #25 Dot Product in Node | Find Similarity with Code Example

Find Dot Product with Code


Index.js code:-


import { readFileSync, writeFileSync } from 'fs'
import OpenAI from 'openai';
import dotenv from 'dotenv'

dotenv.config();
const client = new OpenAI({ apiKey: process.env.openAI_Key })

async function generateEmbedding(dataInArray) {
const response = await client.embeddings.create({
input: dataInArray,
model: "text-embedding-3-small"
})
return response.data;

}

function createFileForEmbedding(data, file) {
const fileData = JSON.stringify(data);
const butterData = Buffer.from(fileData);
writeFileSync(file,butterData)


}
async function readFile() {
const data = readFileSync('data.json')
const dataInArray = JSON.parse(data.toString());
let responseData = await generateEmbedding(dataInArray);
responseData= responseData.map((item,index)=>{
return { input:dataInArray[index],embedding:item.embedding }
})
createFileForEmbedding(responseData, "embedding.json")
}

readFile()


dotProduct.js code

// dotProduct=panda.Elephant;
// dotProduct=panda.Tiger;=


// dotProduct=(a1*b1)+(a2*b2)


// panda.Elephant= (0.75*0.50)+(0.22*0.80) =0.551

// panda.Tiger= (0.75* -0.28)+(0.22*0.70)= -0.056

const panda =[0.75,0.22];
const tiger =[-0.28,0.70]
const elephant =[0.50,0.80]

// const data = panda.map((item,index)=>{
// return panda[index]*tiger[index]
// });

// const data = panda.map((item,index)=>{
// return panda[index]*tiger[index]
// }).reduce((a,b)=>a+b,0)

const data = panda.map((item,index)=>{
return panda[index]*elephant[index]
}).reduce((a,b)=>a+b,0)
console.log(data);


// let dotProduct=0;
// for(let i=0;i<data.length;i++){
// dotProduct+=data[i]
// }
// console.log(dotProduct);


data.json file code


[
"Lion",
"Tiger",
"Elephant",
"Dog",
"Cat",
"Mango",
"Apple",
"Banana",
"Orange",
"Grapes",
"Parrot",
"Peacock",
"Eagle",
"Sparrow",
"Pigeon",
"Horse",
"Watermelon",
"Guava",
"Crow",
"Deer"
]

embedding.js file file

https://github.com/anil-sidhu/gen-ai-with-node-js/blob/dot-productnopde/embedding.json