-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
48 lines (40 loc) · 1.64 KB
/
worker.js
File metadata and controls
48 lines (40 loc) · 1.64 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
47
48
import { pipeline, env } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers';
env.allowLocalModels = false;
let textGenerator = null;
// Listen for messages from main thread
self.addEventListener('message', async (event) => {
const { type, data } = event.data;
if (type === 'init') {
try {
self.postMessage({ type: 'status', message: 'Loading AI model...' });
textGenerator = await pipeline('question-answering', 'Xenova/distilbert-base-cased-distilled-squad', {
progress_callback: (progress) => {
if (progress.status === 'downloading') {
const percent = Math.round((progress.loaded / progress.total) * 100);
self.postMessage({
type: 'progress',
message: `Downloading model: ${percent}%`
});
}
}
});
self.postMessage({ type: 'ready', message: 'AI model loaded successfully!' });
} catch (error) {
self.postMessage({ type: 'error', message: 'Failed to load AI model' });
}
}
if (type === 'generate' && textGenerator) {
try {
const answer = await textGenerator(data.query, data.systemPrompt);
self.postMessage({
type: 'result',
data: answer.answer
});
} catch (error) {
self.postMessage({
type: 'error',
message: 'Generation failed: ' + error.message
});
}
}
});