File size: 10,745 Bytes
40d7073
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/**
 * Model Loader for RuVector ONNX Embeddings WASM
 *
 * Provides easy loading of pre-trained models from HuggingFace Hub
 */

/**
 * Pre-configured models with their HuggingFace URLs
 */
export const MODELS = {
    // Sentence Transformers - Small & Fast
    'all-MiniLM-L6-v2': {
        name: 'all-MiniLM-L6-v2',
        dimension: 384,
        maxLength: 256,
        size: '23MB',
        description: 'Fast, general-purpose embeddings',
        model: 'https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2/resolve/main/onnx/model.onnx',
        tokenizer: 'https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2/resolve/main/tokenizer.json',
    },
    'all-MiniLM-L12-v2': {
        name: 'all-MiniLM-L12-v2',
        dimension: 384,
        maxLength: 256,
        size: '33MB',
        description: 'Better quality, balanced speed',
        model: 'https://huggingface.co/sentence-transformers/all-MiniLM-L12-v2/resolve/main/onnx/model.onnx',
        tokenizer: 'https://huggingface.co/sentence-transformers/all-MiniLM-L12-v2/resolve/main/tokenizer.json',
    },

    // BGE Models - State of the art
    'bge-small-en-v1.5': {
        name: 'bge-small-en-v1.5',
        dimension: 384,
        maxLength: 512,
        size: '33MB',
        description: 'State-of-the-art small model',
        model: 'https://huggingface.co/BAAI/bge-small-en-v1.5/resolve/main/onnx/model.onnx',
        tokenizer: 'https://huggingface.co/BAAI/bge-small-en-v1.5/resolve/main/tokenizer.json',
    },
    'bge-base-en-v1.5': {
        name: 'bge-base-en-v1.5',
        dimension: 768,
        maxLength: 512,
        size: '110MB',
        description: 'Best overall quality',
        model: 'https://huggingface.co/BAAI/bge-base-en-v1.5/resolve/main/onnx/model.onnx',
        tokenizer: 'https://huggingface.co/BAAI/bge-base-en-v1.5/resolve/main/tokenizer.json',
    },

    // E5 Models - Microsoft
    'e5-small-v2': {
        name: 'e5-small-v2',
        dimension: 384,
        maxLength: 512,
        size: '33MB',
        description: 'Excellent for search & retrieval',
        model: 'https://huggingface.co/intfloat/e5-small-v2/resolve/main/onnx/model.onnx',
        tokenizer: 'https://huggingface.co/intfloat/e5-small-v2/resolve/main/tokenizer.json',
    },

    // GTE Models - Alibaba
    'gte-small': {
        name: 'gte-small',
        dimension: 384,
        maxLength: 512,
        size: '33MB',
        description: 'Good multilingual support',
        model: 'https://huggingface.co/thenlper/gte-small/resolve/main/onnx/model.onnx',
        tokenizer: 'https://huggingface.co/thenlper/gte-small/resolve/main/tokenizer.json',
    },
};

/**
 * Default model for quick start
 */
export const DEFAULT_MODEL = 'all-MiniLM-L6-v2';

/**
 * Model loader with caching support
 */
export class ModelLoader {
    constructor(options = {}) {
        this.cache = options.cache ?? true;
        this.cacheStorage = options.cacheStorage ?? 'ruvector-models';
        this.onProgress = options.onProgress ?? null;
    }

    /**
     * Load a pre-configured model by name
     * @param {string} modelName - Model name from MODELS
     * @returns {Promise<{modelBytes: Uint8Array, tokenizerJson: string, config: object}>}
     */
    async loadModel(modelName = DEFAULT_MODEL) {
        const modelConfig = MODELS[modelName];
        if (!modelConfig) {
            throw new Error(`Unknown model: ${modelName}. Available: ${Object.keys(MODELS).join(', ')}`);
        }

        console.log(`Loading model: ${modelConfig.name} (${modelConfig.size})`);

        const [modelBytes, tokenizerJson] = await Promise.all([
            this.fetchWithCache(modelConfig.model, `${modelName}-model.onnx`, 'arraybuffer'),
            this.fetchWithCache(modelConfig.tokenizer, `${modelName}-tokenizer.json`, 'text'),
        ]);

        return {
            modelBytes: new Uint8Array(modelBytes),
            tokenizerJson,
            config: modelConfig,
        };
    }

    /**
     * Load model from custom URLs
     * @param {string} modelUrl - URL to ONNX model
     * @param {string} tokenizerUrl - URL to tokenizer.json
     * @returns {Promise<{modelBytes: Uint8Array, tokenizerJson: string}>}
     */
    async loadFromUrls(modelUrl, tokenizerUrl) {
        const [modelBytes, tokenizerJson] = await Promise.all([
            this.fetchWithCache(modelUrl, null, 'arraybuffer'),
            this.fetchWithCache(tokenizerUrl, null, 'text'),
        ]);

        return {
            modelBytes: new Uint8Array(modelBytes),
            tokenizerJson,
        };
    }

    /**
     * Load model from local files (Node.js)
     * @param {string} modelPath - Path to ONNX model
     * @param {string} tokenizerPath - Path to tokenizer.json
     * @returns {Promise<{modelBytes: Uint8Array, tokenizerJson: string}>}
     */
    async loadFromFiles(modelPath, tokenizerPath) {
        // Node.js environment
        if (typeof process !== 'undefined' && process.versions?.node) {
            const fs = await import('fs/promises');
            const [modelBytes, tokenizerJson] = await Promise.all([
                fs.readFile(modelPath),
                fs.readFile(tokenizerPath, 'utf8'),
            ]);
            return {
                modelBytes: new Uint8Array(modelBytes),
                tokenizerJson,
            };
        }
        throw new Error('loadFromFiles is only available in Node.js');
    }

    /**
     * Fetch with optional caching (uses Cache API in browsers)
     */
    async fetchWithCache(url, cacheKey, responseType) {
        // Try cache first (browser only)
        if (this.cache && typeof caches !== 'undefined' && cacheKey) {
            try {
                const cache = await caches.open(this.cacheStorage);
                const cached = await cache.match(cacheKey);
                if (cached) {
                    console.log(`  Cache hit: ${cacheKey}`);
                    return responseType === 'arraybuffer'
                        ? await cached.arrayBuffer()
                        : await cached.text();
                }
            } catch (e) {
                // Cache API not available, continue with fetch
            }
        }

        // Fetch from network
        console.log(`  Downloading: ${url}`);
        const response = await this.fetchWithProgress(url);

        if (!response.ok) {
            throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
        }

        // Clone for caching
        const responseClone = response.clone();

        // Cache the response (browser only)
        if (this.cache && typeof caches !== 'undefined' && cacheKey) {
            try {
                const cache = await caches.open(this.cacheStorage);
                await cache.put(cacheKey, responseClone);
            } catch (e) {
                // Cache write failed, continue
            }
        }

        return responseType === 'arraybuffer'
            ? await response.arrayBuffer()
            : await response.text();
    }

    /**
     * Fetch with progress reporting
     */
    async fetchWithProgress(url) {
        const response = await fetch(url);

        if (!this.onProgress || !response.body) {
            return response;
        }

        const contentLength = response.headers.get('content-length');
        if (!contentLength) {
            return response;
        }

        const total = parseInt(contentLength, 10);
        let loaded = 0;

        const reader = response.body.getReader();
        const chunks = [];

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            chunks.push(value);
            loaded += value.length;

            this.onProgress({
                loaded,
                total,
                percent: Math.round((loaded / total) * 100),
            });
        }

        const body = new Uint8Array(loaded);
        let position = 0;
        for (const chunk of chunks) {
            body.set(chunk, position);
            position += chunk.length;
        }

        return new Response(body, {
            headers: response.headers,
            status: response.status,
            statusText: response.statusText,
        });
    }

    /**
     * Clear cached models
     */
    async clearCache() {
        if (typeof caches !== 'undefined') {
            await caches.delete(this.cacheStorage);
            console.log('Model cache cleared');
        }
    }

    /**
     * List available models
     */
    static listModels() {
        return Object.entries(MODELS).map(([key, config]) => ({
            id: key,
            ...config,
        }));
    }
}

/**
 * Quick helper to create an embedder with a pre-configured model
 *
 * @example
 * ```javascript
 * import { createEmbedder } from './loader.js';
 *
 * const embedder = await createEmbedder('all-MiniLM-L6-v2');
 * const embedding = embedder.embedOne("Hello world");
 * ```
 */
export async function createEmbedder(modelName = DEFAULT_MODEL, wasmModule = null) {
    // Import WASM module if not provided
    if (!wasmModule) {
        wasmModule = await import('./ruvector_onnx_embeddings_wasm.js');
        await wasmModule.default();
    }

    const loader = new ModelLoader();
    const { modelBytes, tokenizerJson, config } = await loader.loadModel(modelName);

    const embedderConfig = new wasmModule.WasmEmbedderConfig()
        .setMaxLength(config.maxLength)
        .setNormalize(true)
        .setPooling(0); // Mean pooling

    const embedder = wasmModule.WasmEmbedder.withConfig(
        modelBytes,
        tokenizerJson,
        embedderConfig
    );

    return embedder;
}

/**
 * Quick helper for one-off embedding (loads model, embeds, returns)
 *
 * @example
 * ```javascript
 * import { embed } from './loader.js';
 *
 * const embedding = await embed("Hello world");
 * const embeddings = await embed(["Hello", "World"]);
 * ```
 */
export async function embed(text, modelName = DEFAULT_MODEL) {
    const embedder = await createEmbedder(modelName);

    if (Array.isArray(text)) {
        return embedder.embedBatch(text);
    }
    return embedder.embedOne(text);
}

/**
 * Quick helper for similarity comparison
 *
 * @example
 * ```javascript
 * import { similarity } from './loader.js';
 *
 * const score = await similarity("I love dogs", "I adore puppies");
 * console.log(score); // ~0.85
 * ```
 */
export async function similarity(text1, text2, modelName = DEFAULT_MODEL) {
    const embedder = await createEmbedder(modelName);
    return embedder.similarity(text1, text2);
}

export default {
    MODELS,
    DEFAULT_MODEL,
    ModelLoader,
    createEmbedder,
    embed,
    similarity,
};