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-base-en-v1.5');
5
6// Compute sentence embeddings
7const texts = ['Hello world.', 'Example sentence.'];
8const embeddings = await extractor(texts, { pooling: 'mean', normalize: true });
9console.log(embeddings);
10// Tensor {
11// dims: [ 2, 768 ],
12// type: 'float32',
13// data: Float32Array(1536) [ 0.019079938530921936, 0.041718777269124985, ... ],
14// size: 1536
15// }
16
17console.log(embeddings.tolist()); // Convert embeddings to a JavaScript list
18// [
19// [ 0.019079938530921936, 0.041718777269124985, 0.037672195583581924, ... ],
20// [ 0.020936904475092888, 0.020080938935279846, -0.00787576474249363, ... ]
21// ]1import { pipeline, cos_sim } from '@huggingface/transformers';
2
3// Create a feature-extraction pipeline
4const extractor = await pipeline('feature-extraction', 'Xenova/bge-base-en-v1.5');
5
6// List of documents you want to embed
7const texts = [
8 'Hello world.',
9 'The giant panda (Ailuropoda melanoleuca), sometimes called a panda bear or simply panda, is a bear species endemic to China.',
10 'I love pandas so much!',
11];
12
13// Compute sentence embeddings
14const embeddings = await extractor(texts, { pooling: 'mean', normalize: true });
15
16// Prepend recommended query instruction for retrieval.
17const query_prefix = 'Represent this sentence for searching relevant passages: '
18const query = query_prefix + 'What is a panda?';
19const query_embeddings = await extractor(query, { pooling: 'mean', 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: 1, score: 0.7787772374597298, text: 'The giant panda (Ailuropoda melanoleuca), sometimes called a panda bear or simply panda, is a bear species endemic to China.' },
32// { id: 2, score: 0.7071589521880506, text: 'I love pandas so much!' },
33// { id: 0, score: 0.4252782730390429, text: 'Hello world.' }
34// ]onnx).