Views
No views yet
npm i @huggingface/transformers1import { pipeline } from '@huggingface/transformers';
2
3// Create a feature-extraction pipeline
4const extractor = await pipeline('feature-extraction', 'Xenova/bge-m3');
5
6// Compute sentence embeddings
7const texts = ["What is BGE M3?", "Defination of BM25"]
8const embeddings = await extractor(texts, { pooling: 'cls', normalize: true });
9console.log(embeddings);
10// Tensor {
11// dims: [ 2, 1024 ],
12// type: 'float32',
13// data: Float32Array(2048) [ -0.0340719036757946, -0.04478546231985092, ... ],
14// size: 2048
15// }
16
17console.log(embeddings.tolist()); // Convert embeddings to a JavaScript list
18// [
19// [ -0.0340719036757946, -0.04478546231985092, -0.004497686866670847, ... ],
20// [ -0.015383965335786343, -0.041989751160144806, -0.025820579379796982, ... ]
21// ]1import { pipeline, cos_sim } from '@huggingface/transformers';
2
3// Create a feature-extraction pipeline
4const extractor = await pipeline('feature-extraction', 'Xenova/bge-m3');
5
6// Define query to use for retrieval
7const query = 'What is BGE M3?';
8
9// List of documents you want to embed
10const texts = [
11 'BGE M3 is an embedding model supporting dense retrieval, lexical matching and multi-vector interaction.',
12 'BM25 is a bag-of-words retrieval function that ranks a set of documents based on the query terms appearing in each document',
13];
14
15// Compute sentence embeddings
16const embeddings = await extractor(texts, { pooling: 'cls', normalize: true });
17
18// Compute query embeddings
19const query_embeddings = await extractor(query, { pooling: 'cls', normalize: true });
20
21// Sort by cosine similarity score
22const scores = embeddings.tolist().map(
23 (embedding, i) => ({
24 id: i,
25 score: cos_sim(query_embeddings.data, embedding),
26 text: texts[i],
27 })
28).sort((a, b) => b.score - a.score);
29console.log(scores);
30// [
31// { id: 0, score: 0.62532672968664, text: 'BGE M3 is an embedding model supporting dense retrieval, lexical matching and multi-vector interaction.' },
32// { id: 1, score: 0.33111060648806, text: 'BM25 is a bag-of-words retrieval function that ranks a set of documents based on the query terms appearing in each document' },
33// ]onnx).