forked from MCP-Club/mcp-registry
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoder.mjs
More file actions
46 lines (37 loc) · 1.09 KB
/
encoder.mjs
File metadata and controls
46 lines (37 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { pipeline } from '@xenova/transformers';
import { OpenAI } from 'openai';
let model = null;
let openai = null;
const TextEncoder = () => {
const init = async () => {
if (!model) {
model = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
}
if (!openai) {
openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
}
};
const toEmbedding = async (text) => {
await init();
const input = Array.isArray(text) ? text : [text];
const embeddings = await model(input, { pooling: 'mean', normalize: true });
return Array.isArray(text) ? embeddings : embeddings[0];
};
const toEmbeddingOpenAI = async (text) => {
await init();
const input = Array.isArray(text) ? text : [text];
const response = await openai.embeddings.create({
model: 'text-embedding-3-small',
input
});
const embeddings = response.data.map(item => item.embedding);
return Array.isArray(text) ? embeddings : embeddings[0];
}
return {
toEmbedding,
toEmbeddingOpenAI
};
};
export default TextEncoder;