@beltoinc/slyos-sdk 1.5.2 → 1.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts DELETED
@@ -1,2073 +0,0 @@
1
- import axios from 'axios';
2
- import { pipeline, env } from '@huggingface/transformers';
3
-
4
- // @ts-ignore - Force CPU in Node.js
5
- if (env.backends?.onnx?.wasm) {
6
- env.backends.onnx.wasm.proxy = false;
7
- }
8
-
9
- // ─── Types ──────────────────────────────────────────────────────────
10
-
11
- interface SlyOSConfig {
12
- apiKey: string;
13
- apiUrl?: string;
14
- onProgress?: ProgressCallback;
15
- onEvent?: EventCallback;
16
- }
17
-
18
- interface GenerateOptions {
19
- temperature?: number;
20
- maxTokens?: number;
21
- topP?: number;
22
- }
23
-
24
- interface TranscribeOptions {
25
- language?: string;
26
- returnTimestamps?: boolean;
27
- }
28
-
29
- type ModelCategory = 'llm' | 'stt';
30
- type QuantizationLevel = 'q4' | 'q8' | 'fp16' | 'fp32';
31
-
32
- interface ModelInfo {
33
- hfModel: string;
34
- task: string;
35
- category: ModelCategory;
36
- sizesMB: Record<QuantizationLevel, number>;
37
- minRAM_MB: Record<QuantizationLevel, number>;
38
- }
39
-
40
- interface DeviceProfile {
41
- cpuCores: number;
42
- memoryMB: number;
43
- estimatedStorageMB: number;
44
- platform: 'web' | 'nodejs';
45
- os: string;
46
- recommendedQuant: QuantizationLevel;
47
- maxContextWindow: number;
48
- // Enhanced device intelligence fields
49
- deviceFingerprint?: string;
50
- gpuRenderer?: string;
51
- gpuVramMb?: number;
52
- screenWidth?: number;
53
- screenHeight?: number;
54
- pixelRatio?: number;
55
- browserName?: string;
56
- browserVersion?: string;
57
- networkType?: string;
58
- latencyToApiMs?: number;
59
- timezone?: string;
60
- wasmAvailable?: boolean;
61
- webgpuAvailable?: boolean;
62
- }
63
-
64
- interface ProgressEvent {
65
- stage: 'initializing' | 'profiling' | 'downloading' | 'loading' | 'ready' | 'generating' | 'transcribing' | 'error';
66
- progress: number; // 0-100
67
- message: string;
68
- detail?: any;
69
- }
70
-
71
- interface SlyEvent {
72
- type: 'auth' | 'device_registered' | 'device_profiled' | 'model_download_start' | 'model_download_progress' | 'model_loaded' | 'inference_start' | 'inference_complete' | 'error' | 'fallback_success' | 'fallback_error' | 'telemetry_flushed' | 'token';
73
- data?: any;
74
- timestamp: number;
75
- }
76
-
77
- type ProgressCallback = (event: ProgressEvent) => void;
78
- type EventCallback = (event: SlyEvent) => void;
79
-
80
- // ─── OpenAI Compatibility Types ──────────────────────────────────────
81
-
82
- interface OpenAIMessage {
83
- role: 'system' | 'user' | 'assistant';
84
- content: string;
85
- }
86
-
87
- interface OpenAIChatCompletionRequest {
88
- messages: OpenAIMessage[];
89
- temperature?: number;
90
- top_p?: number;
91
- max_tokens?: number;
92
- frequency_penalty?: number;
93
- presence_penalty?: number;
94
- stop?: string | string[];
95
- }
96
-
97
- interface OpenAIChoice {
98
- index: number;
99
- message: OpenAIMessage;
100
- finish_reason: string;
101
- }
102
-
103
- interface OpenAIUsage {
104
- prompt_tokens: number;
105
- completion_tokens: number;
106
- total_tokens: number;
107
- }
108
-
109
- interface OpenAIChatCompletionResponse {
110
- id: string;
111
- object: 'chat.completion';
112
- created: number;
113
- model: string;
114
- choices: OpenAIChoice[];
115
- usage: OpenAIUsage;
116
- }
117
-
118
- // ─── AWS Bedrock Compatibility Types ─────────────────────────────────
119
-
120
- interface BedrockTextGenerationConfig {
121
- maxTokenCount?: number;
122
- temperature?: number;
123
- topP?: number;
124
- topK?: number;
125
- stopSequences?: string[];
126
- }
127
-
128
- interface BedrockInvokeRequest {
129
- inputText: string;
130
- textGenerationConfig?: BedrockTextGenerationConfig;
131
- }
132
-
133
- interface BedrockResult {
134
- outputText: string;
135
- tokenCount: number;
136
- }
137
-
138
- interface BedrockInvokeResponse {
139
- results: BedrockResult[];
140
- input_text_token_count?: number;
141
- }
142
-
143
- // ─── Fallback Configuration ─────────────────────────────────────────
144
-
145
- type FallbackProvider = 'openai' | 'bedrock';
146
-
147
- interface FallbackConfig {
148
- provider: FallbackProvider;
149
- apiKey: string;
150
- model: string;
151
- region?: string; // for Bedrock
152
- }
153
-
154
- interface SlyOSConfigWithFallback extends SlyOSConfig {
155
- fallback?: FallbackConfig;
156
- }
157
-
158
- // ─── OpenAI Compatible Client ───────────────────────────────────────
159
-
160
- interface OpenAICompatibleClient {
161
- chat: {
162
- completions: {
163
- create(request: OpenAIChatCompletionRequest & { model: string }): Promise<OpenAIChatCompletionResponse>;
164
- };
165
- };
166
- }
167
-
168
- // ─── RAG Types ──────────────────────────────────────────────────
169
-
170
- interface RAGOptions {
171
- knowledgeBaseId: string;
172
- query: string;
173
- topK?: number;
174
- modelId: string;
175
- temperature?: number;
176
- maxTokens?: number;
177
- // NEW: streaming callback
178
- onToken?: (token: string, partial: string) => void;
179
- }
180
-
181
- interface RAGChunk {
182
- id: string;
183
- documentId: string;
184
- documentName: string;
185
- content: string;
186
- similarityScore: number;
187
- metadata?: Record<string, any>;
188
- }
189
-
190
- interface RAGResponse {
191
- query: string;
192
- retrievedChunks: RAGChunk[];
193
- generatedResponse: string;
194
- context: string;
195
- latencyMs: number;
196
- tierUsed: 1 | 2 | 3;
197
- // NEW: detailed timing metrics
198
- timing: {
199
- retrievalMs: number; // Time spent retrieving/embedding chunks
200
- contextBuildMs: number; // Time spent building context
201
- firstTokenMs: number; // Time to first token (from generation start)
202
- generationMs: number; // Total generation time
203
- totalMs: number; // End-to-end latency
204
- tokensGenerated: number; // Number of tokens in response
205
- tokensPerSecond: number; // Generation throughput
206
- };
207
- // NEW: dynamic config used
208
- config: {
209
- maxContextChars: number;
210
- maxGenTokens: number;
211
- chunkSize: number;
212
- topK: number;
213
- contextWindowUsed: number;
214
- deviceTier: 'low' | 'mid' | 'high';
215
- };
216
- }
217
-
218
- interface OfflineIndex {
219
- metadata: {
220
- kb_id: string;
221
- kb_name: string;
222
- chunk_size: number;
223
- embedding_dim: number;
224
- total_chunks: number;
225
- synced_at: string;
226
- expires_at: string;
227
- sync_token: string;
228
- };
229
- chunks: Array<{
230
- id: string;
231
- document_id: string;
232
- document_name: string;
233
- content: string;
234
- chunk_index: number;
235
- embedding: number[] | null;
236
- metadata: Record<string, any>;
237
- }>;
238
- }
239
-
240
- // ─── Model Registry ─────────────────────────────────────────────────
241
-
242
- const modelMap: Record<string, ModelInfo> = {
243
- // LLM models (1B+)
244
- 'quantum-1.7b': {
245
- hfModel: 'HuggingFaceTB/SmolLM2-1.7B-Instruct',
246
- task: 'text-generation',
247
- category: 'llm',
248
- sizesMB: { q4: 900, q8: 1700, fp16: 3400, fp32: 6800 },
249
- minRAM_MB: { q4: 2048, q8: 3072, fp16: 5120, fp32: 8192 },
250
- },
251
- 'quantum-3b': {
252
- hfModel: 'Qwen/Qwen2.5-3B-Instruct',
253
- task: 'text-generation',
254
- category: 'llm',
255
- sizesMB: { q4: 1600, q8: 3200, fp16: 6400, fp32: 12800 },
256
- minRAM_MB: { q4: 3072, q8: 5120, fp16: 8192, fp32: 16384 },
257
- },
258
- 'quantum-code-3b': {
259
- hfModel: 'Qwen/Qwen2.5-Coder-3B-Instruct',
260
- task: 'text-generation',
261
- category: 'llm',
262
- sizesMB: { q4: 1600, q8: 3200, fp16: 6400, fp32: 12800 },
263
- minRAM_MB: { q4: 3072, q8: 5120, fp16: 8192, fp32: 16384 },
264
- },
265
- 'quantum-8b': {
266
- hfModel: 'Qwen/Qwen2.5-7B-Instruct',
267
- task: 'text-generation',
268
- category: 'llm',
269
- sizesMB: { q4: 4200, q8: 8400, fp16: 16800, fp32: 33600 },
270
- minRAM_MB: { q4: 6144, q8: 10240, fp16: 20480, fp32: 40960 },
271
- },
272
- // STT models
273
- 'voicecore-base': {
274
- hfModel: 'onnx-community/whisper-base',
275
- task: 'automatic-speech-recognition',
276
- category: 'stt',
277
- sizesMB: { q4: 40, q8: 75, fp16: 150, fp32: 300 },
278
- minRAM_MB: { q4: 512, q8: 512, fp16: 1024, fp32: 2048 },
279
- },
280
- 'voicecore-small': {
281
- hfModel: 'onnx-community/whisper-small',
282
- task: 'automatic-speech-recognition',
283
- category: 'stt',
284
- sizesMB: { q4: 100, q8: 200, fp16: 400, fp32: 800 },
285
- minRAM_MB: { q4: 1024, q8: 1024, fp16: 2048, fp32: 4096 },
286
- },
287
- };
288
-
289
- // ─── Context Window Sizing ──────────────────────────────────────────
290
-
291
- function recommendContextWindow(memoryMB: number, quant: QuantizationLevel): number {
292
- // More RAM + smaller quant = larger context window
293
- const base = quant === 'q4' ? 1024 : quant === 'q8' ? 2048 : quant === 'fp16' ? 4096 : 8192;
294
-
295
- if (memoryMB >= 16384) return Math.min(base * 4, 32768);
296
- if (memoryMB >= 8192) return Math.min(base * 2, 16384);
297
- if (memoryMB >= 4096) return base;
298
- return Math.max(512, Math.floor(base / 2));
299
- }
300
-
301
- function selectQuantization(memoryMB: number, modelId: string): QuantizationLevel {
302
- const info = modelMap[modelId];
303
- if (!info) return 'q4';
304
-
305
- // ONNX/WASM has protobuf size limits — fp16 files >2GB crash on many systems.
306
- // For LLMs, cap at q4 via WASM. FP16/Q8 need native backends (llama.cpp).
307
- // STT models are small enough for q8/fp16.
308
- if (info.category === 'llm') {
309
- return 'q4'; // safest for ONNX/WASM across all platforms
310
- }
311
-
312
- // STT models: try from best quality down
313
- const quants: QuantizationLevel[] = ['fp16', 'q8', 'q4'];
314
- for (const q of quants) {
315
- if (memoryMB >= info.minRAM_MB[q]) return q;
316
- }
317
- return 'q4'; // fallback
318
- }
319
-
320
- // ─── Context Window Detection ──────────────────────────────────────
321
-
322
- async function detectContextWindowFromHF(hfModelId: string): Promise<number> {
323
- try {
324
- const configUrl = `https://huggingface.co/${hfModelId}/raw/main/config.json`;
325
- const response = await axios.get(configUrl, { timeout: 5000 });
326
- const config = response.data;
327
-
328
- // Try multiple context window field names
329
- const contextWindow =
330
- config.max_position_embeddings ||
331
- config.n_positions ||
332
- config.max_seq_len ||
333
- config.model_max_length ||
334
- 2048;
335
-
336
- return contextWindow;
337
- } catch {
338
- // Default if config cannot be fetched
339
- return 2048;
340
- }
341
- }
342
-
343
- // ─── SDK Version ────────────────────────────────────────────────────
344
- const SDK_VERSION = '1.4.1';
345
-
346
- // ─── Persistent Device Identity ─────────────────────────────────────
347
-
348
- async function hashString(str: string): Promise<string> {
349
- const isNode = typeof window === 'undefined';
350
- if (isNode) {
351
- const crypto = await import('crypto');
352
- return crypto.createHash('sha256').update(str).digest('hex').substring(0, 32);
353
- } else {
354
- const encoder = new TextEncoder();
355
- const data = encoder.encode(str);
356
- const hashBuffer = await crypto.subtle.digest('SHA-256', data);
357
- return Array.from(new Uint8Array(hashBuffer))
358
- .map(b => b.toString(16).padStart(2, '0'))
359
- .join('')
360
- .substring(0, 32);
361
- }
362
- }
363
-
364
- async function getOrCreateDeviceId(): Promise<string> {
365
- const isNode = typeof window === 'undefined';
366
-
367
- if (isNode) {
368
- // Node.js: persist in ~/.slyos/device-id
369
- try {
370
- const fs = await import('fs');
371
- const path = await import('path');
372
- const os = await import('os');
373
- const slyosDir = path.join(os.homedir(), '.slyos');
374
- const idFile = path.join(slyosDir, 'device-id');
375
-
376
- try {
377
- const existing = fs.readFileSync(idFile, 'utf-8').trim();
378
- if (existing) return existing;
379
- } catch {}
380
-
381
- const deviceId = `device-${Date.now()}-${Math.random().toString(36).substr(2, 12)}`;
382
- fs.mkdirSync(slyosDir, { recursive: true });
383
- fs.writeFileSync(idFile, deviceId);
384
- return deviceId;
385
- } catch {
386
- return `device-${Date.now()}-${Math.random().toString(36).substr(2, 12)}`;
387
- }
388
- } else {
389
- // Browser: persist in localStorage
390
- const key = 'slyos_device_id';
391
- try {
392
- const existing = localStorage.getItem(key);
393
- if (existing) return existing;
394
- } catch {}
395
-
396
- const deviceId = `device-${Date.now()}-${Math.random().toString(36).substr(2, 12)}`;
397
- try { localStorage.setItem(key, deviceId); } catch {}
398
- return deviceId;
399
- }
400
- }
401
-
402
- async function generateDeviceFingerprint(): Promise<string> {
403
- const isNode = typeof window === 'undefined';
404
- let components: string[] = [];
405
-
406
- if (isNode) {
407
- try {
408
- const os = await import('os');
409
- const cpus = os.cpus();
410
- components.push(cpus[0]?.model || 'unknown-cpu');
411
- components.push(String(os.totalmem()));
412
- components.push(os.platform());
413
- components.push(os.arch());
414
- components.push(String(cpus.length));
415
- } catch {}
416
- } else {
417
- components.push(String(navigator.hardwareConcurrency || 0));
418
- components.push(String((navigator as any).deviceMemory || 0));
419
- components.push(navigator.platform || 'unknown');
420
- // WebGL renderer for GPU fingerprint
421
- try {
422
- const canvas = document.createElement('canvas');
423
- const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl') as WebGLRenderingContext | null;
424
- if (gl) {
425
- const ext = gl.getExtension('WEBGL_debug_renderer_info');
426
- if (ext) {
427
- components.push(gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) || 'unknown-gpu');
428
- }
429
- }
430
- } catch {}
431
- components.push(String(screen.width || 0));
432
- components.push(String(screen.height || 0));
433
- }
434
-
435
- return await hashString(components.join('|'));
436
- }
437
-
438
- // ─── Enhanced Device Profiling ──────────────────────────────────────
439
-
440
- function detectGPU(): { renderer: string | null; vramMb: number } {
441
- if (typeof window === 'undefined') return { renderer: null, vramMb: 0 };
442
- try {
443
- const canvas = document.createElement('canvas');
444
- const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl') as WebGLRenderingContext | null;
445
- if (!gl) return { renderer: null, vramMb: 0 };
446
- const ext = gl.getExtension('WEBGL_debug_renderer_info');
447
- const renderer = ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : null;
448
- // Rough VRAM estimate from renderer string
449
- let vramMb = 0;
450
- if (renderer) {
451
- const match = renderer.match(/(\d+)\s*MB/i);
452
- if (match) vramMb = parseInt(match[1]);
453
- else if (/RTX\s*40/i.test(renderer)) vramMb = 8192;
454
- else if (/RTX\s*30/i.test(renderer)) vramMb = 6144;
455
- else if (/GTX/i.test(renderer)) vramMb = 4096;
456
- else if (/Apple M[2-4]/i.test(renderer)) vramMb = 8192;
457
- else if (/Apple M1/i.test(renderer)) vramMb = 4096;
458
- else if (/Intel/i.test(renderer)) vramMb = 1024;
459
- }
460
- return { renderer, vramMb };
461
- } catch {
462
- return { renderer: null, vramMb: 0 };
463
- }
464
- }
465
-
466
- function detectBrowser(): { name: string; version: string } {
467
- if (typeof window === 'undefined' || typeof navigator === 'undefined') return { name: 'node', version: process.version || 'unknown' };
468
- const ua = navigator.userAgent;
469
- if (/Edg\//i.test(ua)) { const m = ua.match(/Edg\/([\d.]+)/); return { name: 'Edge', version: m?.[1] || '' }; }
470
- if (/Chrome\//i.test(ua)) { const m = ua.match(/Chrome\/([\d.]+)/); return { name: 'Chrome', version: m?.[1] || '' }; }
471
- if (/Firefox\//i.test(ua)) { const m = ua.match(/Firefox\/([\d.]+)/); return { name: 'Firefox', version: m?.[1] || '' }; }
472
- if (/Safari\//i.test(ua)) { const m = ua.match(/Version\/([\d.]+)/); return { name: 'Safari', version: m?.[1] || '' }; }
473
- return { name: 'unknown', version: '' };
474
- }
475
-
476
- function detectNetworkType(): string {
477
- if (typeof navigator === 'undefined') return 'unknown';
478
- const conn = (navigator as any).connection || (navigator as any).mozConnection || (navigator as any).webkitConnection;
479
- if (!conn) return 'unknown';
480
- return conn.effectiveType || conn.type || 'unknown';
481
- }
482
-
483
- async function measureApiLatency(apiUrl: string): Promise<number> {
484
- try {
485
- const start = Date.now();
486
- await axios.head(`${apiUrl}/api/health`, { timeout: 5000 });
487
- return Date.now() - start;
488
- } catch {
489
- try {
490
- const start = Date.now();
491
- await axios.get(`${apiUrl}/api/health`, { timeout: 5000 });
492
- return Date.now() - start;
493
- } catch {
494
- return -1;
495
- }
496
- }
497
- }
498
-
499
- // ─── Device Profiling ───────────────────────────────────────────────
500
-
501
- async function profileDevice(): Promise<DeviceProfile> {
502
- const isNode = typeof window === 'undefined';
503
- let cpuCores = 4;
504
- let memoryMB = 4096;
505
- let estimatedStorageMB = 10000;
506
- let platform: 'web' | 'nodejs' = isNode ? 'nodejs' : 'web';
507
- let os = 'unknown';
508
-
509
- if (isNode) {
510
- // Node.js environment
511
- try {
512
- const osModule = await import('os');
513
- cpuCores = osModule.cpus().length;
514
- memoryMB = Math.round(osModule.totalmem() / (1024 * 1024));
515
- os = `${osModule.platform()} ${osModule.release()}`;
516
-
517
- // Estimate free disk via df-like check
518
- try {
519
- const { execSync } = await import('child_process');
520
- const dfOutput = execSync('df -m . 2>/dev/null || echo "0 0 0 0"', { encoding: 'utf-8' });
521
- const lines = dfOutput.trim().split('\n');
522
- if (lines.length > 1) {
523
- const parts = lines[1].split(/\s+/);
524
- estimatedStorageMB = parseInt(parts[3]) || 10000; // Available column
525
- }
526
- } catch {
527
- estimatedStorageMB = 10000;
528
- }
529
- } catch {
530
- // Fallback
531
- }
532
- } else {
533
- // Browser environment
534
- cpuCores = navigator.hardwareConcurrency || 4;
535
- memoryMB = ((navigator as any).deviceMemory || 4) * 1024; // deviceMemory is in GB
536
- os = navigator.userAgent;
537
-
538
- // Storage Manager API (Chrome 61+)
539
- try {
540
- if (navigator.storage && navigator.storage.estimate) {
541
- const estimate = await navigator.storage.estimate();
542
- estimatedStorageMB = Math.round((estimate.quota || 0) / (1024 * 1024));
543
- }
544
- } catch {
545
- estimatedStorageMB = 5000;
546
- }
547
- }
548
-
549
- const recommendedQuant = selectQuantization(memoryMB, 'quantum-1.7b'); // default baseline
550
- const maxContextWindow = recommendContextWindow(memoryMB, recommendedQuant);
551
-
552
- // Enhanced profiling
553
- const gpu = detectGPU();
554
- const browser = detectBrowser();
555
- const networkType = detectNetworkType();
556
- const timezone = Intl?.DateTimeFormat?.()?.resolvedOptions?.()?.timeZone || 'unknown';
557
-
558
- let screenWidth = 0, screenHeight = 0, pixelRatio = 0;
559
- let wasmAvailable = false, webgpuAvailable = false;
560
-
561
- if (!isNode) {
562
- screenWidth = screen?.width || 0;
563
- screenHeight = screen?.height || 0;
564
- pixelRatio = window?.devicePixelRatio || 1;
565
- }
566
-
567
- // Capability detection
568
- try { wasmAvailable = typeof WebAssembly !== 'undefined'; } catch {}
569
- if (!isNode) {
570
- try { webgpuAvailable = !!(navigator as any).gpu; } catch {}
571
- }
572
-
573
- return {
574
- cpuCores,
575
- memoryMB,
576
- estimatedStorageMB,
577
- platform,
578
- os,
579
- recommendedQuant,
580
- maxContextWindow,
581
- gpuRenderer: gpu.renderer || undefined,
582
- gpuVramMb: gpu.vramMb || undefined,
583
- screenWidth: screenWidth || undefined,
584
- screenHeight: screenHeight || undefined,
585
- pixelRatio: pixelRatio || undefined,
586
- browserName: browser.name,
587
- browserVersion: browser.version,
588
- networkType,
589
- timezone,
590
- wasmAvailable,
591
- webgpuAvailable,
592
- };
593
- }
594
-
595
- // ─── Main SDK Class ─────────────────────────────────────────────────
596
-
597
- interface TelemetryEntry {
598
- latency_ms: number;
599
- tokens_generated: number;
600
- success: boolean;
601
- model_id: string;
602
- timestamp: number;
603
- }
604
-
605
- class SlyOS {
606
- private apiKey: string;
607
- private apiUrl: string;
608
- private deviceId: string;
609
- private token: string | null = null;
610
- private models: Map<string, any> = new Map();
611
- private deviceProfile: DeviceProfile | null = null;
612
- private onProgress: ProgressCallback | null;
613
- private onEvent: EventCallback | null;
614
- private fallbackConfig: FallbackConfig | null;
615
- private modelContextWindow: number = 0;
616
- // Telemetry batching
617
- private telemetryBuffer: TelemetryEntry[] = [];
618
- private telemetryFlushTimer: any = null;
619
- private static readonly TELEMETRY_BATCH_SIZE = 10;
620
- private static readonly TELEMETRY_FLUSH_INTERVAL = 60000; // 60 seconds
621
-
622
- constructor(config: SlyOSConfigWithFallback) {
623
- this.apiKey = config.apiKey;
624
- this.apiUrl = config.apiUrl || 'https://api.slyos.world';
625
- this.deviceId = ''; // Set asynchronously in initialize()
626
- this.onProgress = config.onProgress || null;
627
- this.onEvent = config.onEvent || null;
628
- this.fallbackConfig = config.fallback || null;
629
- }
630
-
631
- // ── Progress & Event Helpers ────────────────────────────────────
632
-
633
- private emitProgress(stage: ProgressEvent['stage'], progress: number, message: string, detail?: any) {
634
- if (this.onProgress) {
635
- this.onProgress({ stage, progress, message, detail });
636
- }
637
- }
638
-
639
- private emitEvent(type: SlyEvent['type'], data?: any) {
640
- if (this.onEvent) {
641
- this.onEvent({ type, data, timestamp: Date.now() });
642
- }
643
- }
644
-
645
- // ── Telemetry Batching ─────────────────────────────────────────
646
-
647
- private recordTelemetry(entry: TelemetryEntry) {
648
- this.telemetryBuffer.push(entry);
649
- if (this.telemetryBuffer.length >= SlyOS.TELEMETRY_BATCH_SIZE) {
650
- this.flushTelemetry();
651
- } else if (!this.telemetryFlushTimer) {
652
- this.telemetryFlushTimer = setTimeout(() => this.flushTelemetry(), SlyOS.TELEMETRY_FLUSH_INTERVAL);
653
- }
654
- }
655
-
656
- private async flushTelemetry() {
657
- if (this.telemetryFlushTimer) {
658
- clearTimeout(this.telemetryFlushTimer);
659
- this.telemetryFlushTimer = null;
660
- }
661
- if (this.telemetryBuffer.length === 0 || !this.token) return;
662
-
663
- const batch = [...this.telemetryBuffer];
664
- this.telemetryBuffer = [];
665
-
666
- try {
667
- await axios.post(`${this.apiUrl}/api/devices/telemetry`, {
668
- device_id: this.deviceId,
669
- metrics: batch,
670
- }, {
671
- headers: { Authorization: `Bearer ${this.token}` },
672
- timeout: 10000,
673
- });
674
- this.emitEvent('telemetry_flushed', { count: batch.length });
675
- } catch {
676
- // Put back on failure for next attempt
677
- this.telemetryBuffer.unshift(...batch);
678
- // Cap buffer to prevent memory leak
679
- if (this.telemetryBuffer.length > 100) {
680
- this.telemetryBuffer = this.telemetryBuffer.slice(-100);
681
- }
682
- }
683
- }
684
-
685
- // ── Device Analysis ─────────────────────────────────────────────
686
-
687
- async analyzeDevice(): Promise<DeviceProfile> {
688
- try {
689
- this.emitProgress('profiling', 10, 'Analyzing device capabilities...');
690
- this.deviceProfile = await profileDevice();
691
- this.emitProgress('profiling', 100, `Device: ${this.deviceProfile.cpuCores} cores, ${Math.round(this.deviceProfile.memoryMB / 1024 * 10) / 10}GB RAM`);
692
- this.emitEvent('device_profiled', this.deviceProfile);
693
- return this.deviceProfile;
694
- } catch (err: any) {
695
- this.emitEvent('error', { method: 'analyzeDevice', error: err.message });
696
- throw new Error(`Device analysis failed: ${err.message}`);
697
- }
698
- }
699
-
700
- getDeviceProfile(): DeviceProfile | null {
701
- return this.deviceProfile;
702
- }
703
-
704
- getModelContextWindow(): number {
705
- return this.modelContextWindow;
706
- }
707
-
708
- getDeviceId(): string {
709
- return this.deviceId;
710
- }
711
-
712
- getSdkVersion(): string {
713
- return SDK_VERSION;
714
- }
715
-
716
- // Flush remaining telemetry and clean up timers
717
- async destroy(): Promise<void> {
718
- await this.flushTelemetry();
719
- if (this.telemetryFlushTimer) {
720
- clearTimeout(this.telemetryFlushTimer);
721
- this.telemetryFlushTimer = null;
722
- }
723
- }
724
-
725
- // ── Smart Model Recommendation ──────────────────────────────────
726
-
727
- recommendModel(category: ModelCategory = 'llm'): { modelId: string; quant: QuantizationLevel; contextWindow: number; reason: string } | null {
728
- if (!this.deviceProfile) {
729
- throw new Error('Call analyzeDevice() first to get a recommendation.');
730
- }
731
-
732
- const mem = this.deviceProfile.memoryMB;
733
- const candidates = Object.entries(modelMap).filter(([_, info]) => info.category === category);
734
-
735
- // Sort by size descending — pick the biggest model that fits
736
- for (const [id, info] of candidates.sort((a, b) => b[1].sizesMB.q4 - a[1].sizesMB.q4)) {
737
- const quant = selectQuantization(mem, id);
738
- if (mem >= info.minRAM_MB[quant]) {
739
- const ctx = recommendContextWindow(mem, quant);
740
- return {
741
- modelId: id,
742
- quant,
743
- contextWindow: ctx,
744
- reason: `Best model for ${Math.round(mem / 1024)}GB RAM at ${quant.toUpperCase()} precision`,
745
- };
746
- }
747
- }
748
-
749
- // Fallback to smallest
750
- const smallest = candidates.sort((a, b) => a[1].sizesMB.q4 - b[1].sizesMB.q4)[0];
751
- if (smallest) {
752
- return {
753
- modelId: smallest[0],
754
- quant: 'q4',
755
- contextWindow: 512,
756
- reason: 'Limited device memory — using smallest available model at Q4',
757
- };
758
- }
759
-
760
- return null;
761
- }
762
-
763
- // ── Initialize ──────────────────────────────────────────────────
764
-
765
- async initialize(): Promise<DeviceProfile> {
766
- this.emitProgress('initializing', 0, 'Starting SlyOS...');
767
-
768
- // Step 1: Persistent device ID
769
- this.deviceId = await getOrCreateDeviceId();
770
-
771
- // Step 2: Profile device (enhanced)
772
- this.emitProgress('profiling', 5, 'Detecting device capabilities...');
773
- this.deviceProfile = await profileDevice();
774
-
775
- // Step 2b: Generate device fingerprint
776
- this.deviceProfile.deviceFingerprint = await generateDeviceFingerprint();
777
-
778
- this.emitProgress('profiling', 20, `Detected: ${this.deviceProfile.cpuCores} CPU cores, ${Math.round(this.deviceProfile.memoryMB / 1024 * 10) / 10}GB RAM${this.deviceProfile.gpuRenderer ? ', GPU: ' + this.deviceProfile.gpuRenderer.substring(0, 30) : ''}`);
779
- this.emitEvent('device_profiled', this.deviceProfile);
780
-
781
- // Step 3: Authenticate
782
- this.emitProgress('initializing', 40, 'Authenticating with API key...');
783
- try {
784
- const authRes = await axios.post(`${this.apiUrl}/api/auth/sdk`, {
785
- apiKey: this.apiKey,
786
- });
787
- this.token = authRes.data.token;
788
- this.emitProgress('initializing', 60, 'Authenticated successfully');
789
- this.emitEvent('auth', { success: true });
790
- } catch (err: any) {
791
- this.emitProgress('error', 0, `Authentication failed: ${err.message}`);
792
- this.emitEvent('error', { stage: 'auth', error: err.message });
793
- throw new Error(`SlyOS auth failed: ${err.response?.data?.error || err.message}`);
794
- }
795
-
796
- // Step 4: Measure API latency
797
- const latency = await measureApiLatency(this.apiUrl);
798
- if (latency > 0) this.deviceProfile.latencyToApiMs = latency;
799
-
800
- // Step 5: Register device with full intelligence profile
801
- this.emitProgress('initializing', 70, 'Registering device...');
802
- try {
803
- // Determine supported quantizations based on memory
804
- const mem = this.deviceProfile.memoryMB;
805
- const supportedQuants: string[] = ['q4'];
806
- if (mem >= 4096) supportedQuants.push('q8');
807
- if (mem >= 8192) supportedQuants.push('fp16');
808
- if (mem >= 16384) supportedQuants.push('fp32');
809
-
810
- // Determine recommended tier
811
- let recommendedTier = 1;
812
- if (mem >= 8192 && this.deviceProfile.cpuCores >= 4) recommendedTier = 2;
813
- if (mem >= 16384 && this.deviceProfile.cpuCores >= 8) recommendedTier = 3;
814
-
815
- await axios.post(`${this.apiUrl}/api/devices/register`, {
816
- device_id: this.deviceId,
817
- device_fingerprint: this.deviceProfile.deviceFingerprint,
818
- platform: this.deviceProfile.platform,
819
- os_version: this.deviceProfile.os,
820
- total_memory_mb: this.deviceProfile.memoryMB,
821
- cpu_cores: this.deviceProfile.cpuCores,
822
- // Enhanced fields
823
- gpu_renderer: this.deviceProfile.gpuRenderer || null,
824
- gpu_vram_mb: this.deviceProfile.gpuVramMb || null,
825
- screen_width: this.deviceProfile.screenWidth || null,
826
- screen_height: this.deviceProfile.screenHeight || null,
827
- pixel_ratio: this.deviceProfile.pixelRatio || null,
828
- browser_name: this.deviceProfile.browserName || null,
829
- browser_version: this.deviceProfile.browserVersion || null,
830
- sdk_version: SDK_VERSION,
831
- network_type: this.deviceProfile.networkType || null,
832
- latency_to_api_ms: this.deviceProfile.latencyToApiMs || null,
833
- timezone: this.deviceProfile.timezone || null,
834
- // Capabilities
835
- wasm_available: this.deviceProfile.wasmAvailable || false,
836
- webgpu_available: this.deviceProfile.webgpuAvailable || false,
837
- supported_quants: supportedQuants,
838
- recommended_tier: recommendedTier,
839
- }, {
840
- headers: { Authorization: `Bearer ${this.token}` },
841
- });
842
- this.emitProgress('initializing', 90, 'Device registered');
843
- this.emitEvent('device_registered', { deviceId: this.deviceId, fingerprint: this.deviceProfile.deviceFingerprint });
844
- } catch (err: any) {
845
- // Non-fatal — device registration shouldn't block usage
846
- this.emitProgress('initializing', 90, 'Device registration skipped (non-fatal)');
847
- }
848
-
849
- // Step 6: Start telemetry flush timer
850
- this.telemetryFlushTimer = setTimeout(() => this.flushTelemetry(), SlyOS.TELEMETRY_FLUSH_INTERVAL);
851
-
852
- this.emitProgress('ready', 100, `SlyOS v${SDK_VERSION} ready — ${this.deviceProfile.recommendedQuant.toUpperCase()}, ${this.deviceProfile.gpuRenderer ? 'GPU detected' : 'CPU only'}`);
853
-
854
- return this.deviceProfile;
855
- }
856
-
857
- // ── Model Loading ───────────────────────────────────────────────
858
-
859
- getAvailableModels(): Record<string, { models: { id: string; sizesMB: Record<string, number>; minRAM_MB: Record<string, number> }[] }> {
860
- const grouped: Record<string, any[]> = { llm: [], stt: [] };
861
- for (const [id, info] of Object.entries(modelMap)) {
862
- if (!grouped[info.category]) grouped[info.category] = [];
863
- grouped[info.category].push({
864
- id,
865
- sizesMB: info.sizesMB,
866
- minRAM_MB: info.minRAM_MB,
867
- });
868
- }
869
- return Object.fromEntries(
870
- Object.entries(grouped).map(([cat, models]) => [cat, { models }])
871
- );
872
- }
873
-
874
- async searchModels(query: string, options?: { limit?: number; task?: string }): Promise<Array<{
875
- id: string;
876
- name: string;
877
- downloads: number;
878
- likes: number;
879
- task: string;
880
- size_category: string;
881
- }>> {
882
- try {
883
- const limit = options?.limit || 20;
884
- const filters = ['onnx']; // Filter for ONNX models only
885
- if (options?.task) {
886
- filters.push(options.task);
887
- }
888
-
889
- const filterString = filters.map(f => `"${f}"`).join(',');
890
- const url = `https://huggingface.co/api/models?search=${encodeURIComponent(query)}&filter=${encodeURIComponent(`[${filterString}]`)}&sort=downloads&direction=-1&limit=${limit}`;
891
-
892
- const response = await axios.get(url, { timeout: 10000 });
893
- const models = Array.isArray(response.data) ? response.data : [];
894
-
895
- return models.map((model: any) => ({
896
- id: model.id,
897
- name: model.id.split('/')[1] || model.id,
898
- downloads: model.downloads || 0,
899
- likes: model.likes || 0,
900
- task: model.task || 'unknown',
901
- size_category: model.size_category || 'unknown',
902
- }));
903
- } catch (error: any) {
904
- this.emitEvent('error', { stage: 'model_search', error: error.message });
905
- throw new Error(`Model search failed: ${error.message}`);
906
- }
907
- }
908
-
909
- canRunModel(modelId: string, quant?: QuantizationLevel): { canRun: boolean; reason: string; recommendedQuant: QuantizationLevel } {
910
- const info = modelMap[modelId];
911
- if (!info) return { canRun: false, reason: `Unknown model "${modelId}"`, recommendedQuant: 'q4' };
912
- if (!this.deviceProfile) return { canRun: true, reason: 'Device not profiled yet — call initialize() first', recommendedQuant: 'q4' };
913
-
914
- const mem = this.deviceProfile.memoryMB;
915
- const bestQuant = selectQuantization(mem, modelId);
916
-
917
- if (quant && mem < info.minRAM_MB[quant]) {
918
- return {
919
- canRun: false,
920
- reason: `Not enough RAM for ${quant.toUpperCase()} (need ${info.minRAM_MB[quant]}MB, have ${mem}MB). Try ${bestQuant.toUpperCase()} instead.`,
921
- recommendedQuant: bestQuant,
922
- };
923
- }
924
-
925
- if (mem < info.minRAM_MB.q4) {
926
- return {
927
- canRun: false,
928
- reason: `Model requires at least ${info.minRAM_MB.q4}MB RAM even at Q4. Device has ${mem}MB.`,
929
- recommendedQuant: 'q4',
930
- };
931
- }
932
-
933
- return { canRun: true, reason: `OK at ${bestQuant.toUpperCase()} precision`, recommendedQuant: bestQuant };
934
- }
935
-
936
- async loadModel(modelId: string, options?: { quant?: QuantizationLevel }): Promise<void> {
937
- const info = modelMap[modelId];
938
- let hfModelId: string;
939
- let task: string;
940
- let estimatedSize: number;
941
-
942
- // Handle curated models
943
- if (info) {
944
- hfModelId = info.hfModel;
945
- task = info.task;
946
-
947
- // Determine quantization
948
- let quant: QuantizationLevel = options?.quant || 'fp32';
949
- if (!options?.quant && this.deviceProfile) {
950
- quant = selectQuantization(this.deviceProfile.memoryMB, modelId);
951
- this.emitProgress('downloading', 0, `Auto-selected ${quant.toUpperCase()} quantization for your device`);
952
- }
953
-
954
- // Check feasibility
955
- const check = this.canRunModel(modelId, quant);
956
- if (!check.canRun) {
957
- this.emitProgress('error', 0, check.reason);
958
- throw new Error(check.reason);
959
- }
960
-
961
- estimatedSize = info.sizesMB[quant];
962
- this.emitProgress('downloading', 0, `Downloading ${modelId} (${quant.toUpperCase()}, ~${estimatedSize}MB)...`);
963
- this.emitEvent('model_download_start', { modelId, quant, estimatedSizeMB: estimatedSize });
964
- } else {
965
- // Handle custom HuggingFace models
966
- hfModelId = modelId;
967
- task = 'text-generation'; // Default task
968
- estimatedSize = 2048; // Default estimate
969
-
970
- this.emitProgress('downloading', 0, `Loading custom HuggingFace model: ${modelId}...`);
971
- this.emitEvent('model_download_start', { modelId, custom: true, estimatedSizeMB: estimatedSize });
972
- }
973
-
974
- // Map quant to dtype for HuggingFace
975
- const dtypeMap: Record<QuantizationLevel, string> = {
976
- q4: 'q4',
977
- q8: 'q8',
978
- fp16: 'fp16',
979
- fp32: 'fp32',
980
- };
981
-
982
- let lastReportedPercent = 0;
983
- const startTime = Date.now();
984
-
985
- try {
986
- // For custom HF models, detect context window
987
- let detectedContextWindow = 2048;
988
- if (!info) {
989
- detectedContextWindow = await detectContextWindowFromHF(hfModelId);
990
- }
991
-
992
- const pipe = await pipeline(task as any, hfModelId, {
993
- device: 'cpu',
994
- dtype: 'q4' as any, // Default to q4 for stability
995
- progress_callback: (progressData: any) => {
996
- // HuggingFace transformers sends progress events during download
997
- if (progressData && typeof progressData === 'object') {
998
- let percent = 0;
999
- let msg = 'Downloading...';
1000
-
1001
- if (progressData.status === 'progress' && progressData.progress !== undefined) {
1002
- percent = Math.round(progressData.progress);
1003
- const loaded = progressData.loaded ? `${Math.round(progressData.loaded / 1024 / 1024)}MB` : '';
1004
- const total = progressData.total ? `${Math.round(progressData.total / 1024 / 1024)}MB` : '';
1005
- msg = loaded && total ? `Downloading: ${loaded} / ${total}` : `Downloading: ${percent}%`;
1006
- } else if (progressData.status === 'done') {
1007
- percent = 100;
1008
- msg = progressData.file ? `Downloaded ${progressData.file}` : 'Download complete';
1009
- } else if (progressData.status === 'initiate') {
1010
- msg = progressData.file ? `Starting download: ${progressData.file}` : 'Initiating download...';
1011
- }
1012
-
1013
- // Only emit if progress meaningfully changed (avoid flooding)
1014
- if (percent !== lastReportedPercent || progressData.status === 'done' || progressData.status === 'initiate') {
1015
- lastReportedPercent = percent;
1016
- this.emitProgress('downloading', percent, msg, progressData);
1017
- this.emitEvent('model_download_progress', { modelId, percent, ...progressData });
1018
- }
1019
- }
1020
- },
1021
- });
1022
-
1023
- const loadTime = Date.now() - startTime;
1024
- let contextWindow: number;
1025
-
1026
- if (info) {
1027
- // For curated models, use recommendContextWindow
1028
- const quant = options?.quant || (this.deviceProfile ? selectQuantization(this.deviceProfile.memoryMB, modelId) : 'q4');
1029
- contextWindow = this.deviceProfile
1030
- ? recommendContextWindow(this.deviceProfile.memoryMB, quant)
1031
- : 2048;
1032
- } else {
1033
- // For custom HF models, use detected context window
1034
- contextWindow = detectedContextWindow;
1035
- }
1036
-
1037
- this.modelContextWindow = contextWindow;
1038
- this.models.set(modelId, { pipe, info, quant: 'q4', contextWindow });
1039
-
1040
- this.emitProgress('ready', 100, `${modelId} loaded (q4, ${(loadTime / 1000).toFixed(1)}s, ctx: ${contextWindow})`);
1041
- this.emitEvent('model_loaded', { modelId, quant: 'q4', loadTimeMs: loadTime, contextWindow });
1042
-
1043
- // Telemetry
1044
- if (this.token) {
1045
- await axios.post(`${this.apiUrl}/api/telemetry`, {
1046
- device_id: this.deviceId,
1047
- event_type: 'model_load',
1048
- model_id: modelId,
1049
- success: true,
1050
- metadata: { quant: 'q4', loadTimeMs: loadTime, contextWindow, custom: !info },
1051
- }, {
1052
- headers: { Authorization: `Bearer ${this.token}` },
1053
- }).catch(() => {});
1054
- }
1055
- } catch (error: any) {
1056
- this.emitProgress('error', 0, `Failed to load ${modelId}: ${error.message}`);
1057
- this.emitEvent('error', { stage: 'model_load', modelId, error: error.message });
1058
-
1059
- if (this.token) {
1060
- await axios.post(`${this.apiUrl}/api/telemetry`, {
1061
- device_id: this.deviceId,
1062
- event_type: 'model_load',
1063
- model_id: modelId,
1064
- success: false,
1065
- error_message: error.message,
1066
- }, {
1067
- headers: { Authorization: `Bearer ${this.token}` },
1068
- }).catch(() => {});
1069
- }
1070
- throw error;
1071
- }
1072
- }
1073
-
1074
- // ── Inference: Generate ─────────────────────────────────────────
1075
-
1076
- async generate(modelId: string, prompt: string, options: GenerateOptions = {}): Promise<string> {
1077
- if (!this.models.has(modelId)) {
1078
- await this.loadModel(modelId);
1079
- }
1080
-
1081
- const loaded = this.models.get(modelId);
1082
- if (!loaded) {
1083
- throw new Error(`Model "${modelId}" failed to load. Check your connection and model ID.`);
1084
- }
1085
- const { pipe, info, contextWindow } = loaded;
1086
- if (info.category !== 'llm') {
1087
- throw new Error(`Model "${modelId}" is not an LLM. Use transcribe() for STT models.`);
1088
- }
1089
-
1090
- const maxTokens = Math.min(options.maxTokens || 100, contextWindow || 2048);
1091
-
1092
- this.emitProgress('generating', 0, `Generating response (max ${maxTokens} tokens)...`);
1093
- this.emitEvent('inference_start', { modelId, maxTokens });
1094
- const startTime = Date.now();
1095
-
1096
- try {
1097
- const result = await pipe(prompt, {
1098
- max_new_tokens: maxTokens,
1099
- temperature: options.temperature || 0.7,
1100
- top_p: options.topP || 0.9,
1101
- do_sample: true,
1102
- });
1103
-
1104
- const rawOutput = result[0].generated_text;
1105
- // HuggingFace transformers returns the prompt + generated text concatenated.
1106
- // Strip the original prompt so we only return the NEW tokens.
1107
- const response = rawOutput.startsWith(prompt)
1108
- ? rawOutput.slice(prompt.length).trim()
1109
- : rawOutput.trim();
1110
- const latency = Date.now() - startTime;
1111
- const tokensGenerated = response.split(/\s+/).length;
1112
- const tokensPerSec = (tokensGenerated / (latency / 1000)).toFixed(1);
1113
-
1114
- this.emitProgress('ready', 100, `Generated ${tokensGenerated} tokens in ${(latency / 1000).toFixed(1)}s (${tokensPerSec} tok/s)`);
1115
- this.emitEvent('inference_complete', { modelId, latencyMs: latency, tokensGenerated, tokensPerSec: parseFloat(tokensPerSec) });
1116
-
1117
- // Batch telemetry (new device intelligence)
1118
- this.recordTelemetry({
1119
- latency_ms: latency,
1120
- tokens_generated: tokensGenerated,
1121
- success: true,
1122
- model_id: modelId,
1123
- timestamp: Date.now(),
1124
- });
1125
-
1126
- // Legacy telemetry (backwards compatible)
1127
- if (this.token) {
1128
- await axios.post(`${this.apiUrl}/api/telemetry`, {
1129
- device_id: this.deviceId,
1130
- event_type: 'inference',
1131
- model_id: modelId,
1132
- latency_ms: latency,
1133
- tokens_generated: tokensGenerated,
1134
- success: true,
1135
- }, {
1136
- headers: { Authorization: `Bearer ${this.token}` },
1137
- }).catch(() => {});
1138
- }
1139
-
1140
- return response;
1141
- } catch (error: any) {
1142
- this.emitProgress('error', 0, `Generation failed: ${error.message}`);
1143
- this.emitEvent('error', { stage: 'inference', modelId, error: error.message });
1144
-
1145
- // Batch telemetry (failure)
1146
- this.recordTelemetry({
1147
- latency_ms: 0,
1148
- tokens_generated: 0,
1149
- success: false,
1150
- model_id: modelId,
1151
- timestamp: Date.now(),
1152
- });
1153
-
1154
- if (this.token) {
1155
- await axios.post(`${this.apiUrl}/api/telemetry`, {
1156
- device_id: this.deviceId,
1157
- event_type: 'inference',
1158
- model_id: modelId,
1159
- success: false,
1160
- error_message: error.message,
1161
- }, {
1162
- headers: { Authorization: `Bearer ${this.token}` },
1163
- }).catch(() => {});
1164
- }
1165
- throw error;
1166
- }
1167
- }
1168
-
1169
- /**
1170
- * Stream text generation token-by-token.
1171
- * Calls onToken callback for each generated token.
1172
- */
1173
- async generateStream(
1174
- modelId: string,
1175
- prompt: string,
1176
- options: GenerateOptions & { onToken?: (token: string, partial: string) => void } = {}
1177
- ): Promise<{ text: string; firstTokenMs: number; totalMs: number; tokensGenerated: number }> {
1178
- if (!this.models.has(modelId)) {
1179
- await this.loadModel(modelId);
1180
- }
1181
- const loaded = this.models.get(modelId);
1182
- if (!loaded) throw new Error(`Model "${modelId}" not loaded`);
1183
- const { pipe, info, contextWindow } = loaded;
1184
- if (info.category !== 'llm') throw new Error(`Not an LLM`);
1185
-
1186
- const maxTokens = Math.min(options.maxTokens || 100, contextWindow || 2048);
1187
- const startTime = Date.now();
1188
- let firstTokenTime = 0;
1189
- let accumulated = '';
1190
-
1191
- this.emitProgress('generating', 0, `Streaming (max ${maxTokens} tokens)...`);
1192
-
1193
- try {
1194
- const result = await pipe(prompt, {
1195
- max_new_tokens: maxTokens,
1196
- temperature: options.temperature || 0.7,
1197
- top_p: options.topP || 0.9,
1198
- do_sample: true,
1199
- // Transformers.js streamer callback
1200
- callback_function: (output: any) => {
1201
- if (!firstTokenTime) firstTokenTime = Date.now() - startTime;
1202
- if (output && output.length > 0) {
1203
- // output is token IDs, we need to decode
1204
- // The callback in transformers.js v3 gives decoded text tokens
1205
- const tokenText = typeof output === 'string' ? output : '';
1206
- if (tokenText) {
1207
- accumulated += tokenText;
1208
- options.onToken?.(tokenText, accumulated);
1209
- this.emitEvent('token', { token: tokenText, partial: accumulated });
1210
- }
1211
- }
1212
- }
1213
- });
1214
-
1215
- const rawOutput = result[0].generated_text;
1216
- const response = rawOutput.startsWith(prompt) ? rawOutput.slice(prompt.length).trim() : rawOutput.trim();
1217
-
1218
- if (!firstTokenTime) firstTokenTime = Date.now() - startTime;
1219
- const totalMs = Date.now() - startTime;
1220
- const tokensGenerated = response.split(/\s+/).length;
1221
-
1222
- this.emitProgress('ready', 100, `Streamed ${tokensGenerated} tokens in ${(totalMs/1000).toFixed(1)}s`);
1223
-
1224
- return { text: response, firstTokenMs: firstTokenTime, totalMs, tokensGenerated };
1225
- } catch (error: any) {
1226
- this.emitProgress('error', 0, `Stream failed: ${error.message}`);
1227
- throw error;
1228
- }
1229
- }
1230
-
1231
- // ── Inference: Transcribe ───────────────────────────────────────
1232
-
1233
- async transcribe(modelId: string, audioInput: any, options: TranscribeOptions = {}): Promise<string> {
1234
- if (!this.models.has(modelId)) {
1235
- await this.loadModel(modelId);
1236
- }
1237
-
1238
- const loaded = this.models.get(modelId);
1239
- if (!loaded) {
1240
- throw new Error(`Model "${modelId}" failed to load. Check your connection and model ID.`);
1241
- }
1242
- const { pipe, info } = loaded;
1243
- if (info.category !== 'stt') {
1244
- throw new Error(`Model "${modelId}" is not an STT model. Use generate() for LLMs.`);
1245
- }
1246
-
1247
- this.emitProgress('transcribing', 0, 'Transcribing audio...');
1248
- this.emitEvent('inference_start', { modelId, type: 'transcription' });
1249
- const startTime = Date.now();
1250
-
1251
- try {
1252
- const result = await pipe(audioInput, {
1253
- language: options.language || 'en',
1254
- return_timestamps: options.returnTimestamps || false,
1255
- });
1256
-
1257
- const text = result.text;
1258
- const latency = Date.now() - startTime;
1259
-
1260
- this.emitProgress('ready', 100, `Transcribed in ${(latency / 1000).toFixed(1)}s`);
1261
- this.emitEvent('inference_complete', { modelId, latencyMs: latency, type: 'transcription' });
1262
-
1263
- if (this.token) {
1264
- await axios.post(`${this.apiUrl}/api/telemetry`, {
1265
- device_id: this.deviceId,
1266
- event_type: 'inference',
1267
- model_id: modelId,
1268
- latency_ms: latency,
1269
- success: true,
1270
- }, {
1271
- headers: { Authorization: `Bearer ${this.token}` },
1272
- }).catch(() => {});
1273
- }
1274
-
1275
- return text;
1276
- } catch (error: any) {
1277
- this.emitProgress('error', 0, `Transcription failed: ${error.message}`);
1278
- this.emitEvent('error', { stage: 'transcription', modelId, error: error.message });
1279
-
1280
- if (this.token) {
1281
- await axios.post(`${this.apiUrl}/api/telemetry`, {
1282
- device_id: this.deviceId,
1283
- event_type: 'inference',
1284
- model_id: modelId,
1285
- success: false,
1286
- error_message: error.message,
1287
- }, {
1288
- headers: { Authorization: `Bearer ${this.token}` },
1289
- }).catch(() => {});
1290
- }
1291
- throw error;
1292
- }
1293
- }
1294
-
1295
- // ── OpenAI Compatibility ────────────────────────────────────────────
1296
-
1297
- async chatCompletion(modelId: string, request: OpenAIChatCompletionRequest): Promise<OpenAIChatCompletionResponse> {
1298
- try {
1299
- // Convert OpenAI message format to a prompt string
1300
- const prompt = request.messages
1301
- .map(msg => {
1302
- if (msg.role === 'system') {
1303
- return `System: ${msg.content}`;
1304
- } else if (msg.role === 'user') {
1305
- return `User: ${msg.content}`;
1306
- } else {
1307
- return `Assistant: ${msg.content}`;
1308
- }
1309
- })
1310
- .join('\n\n');
1311
-
1312
- const response = await this.generate(modelId, prompt, {
1313
- temperature: request.temperature,
1314
- maxTokens: request.max_tokens,
1315
- topP: request.top_p,
1316
- });
1317
-
1318
- // Estimate token counts (rough approximation: ~4 chars per token)
1319
- const promptTokens = Math.ceil(prompt.length / 4);
1320
- const completionTokens = Math.ceil(response.length / 4);
1321
-
1322
- return {
1323
- id: `chat-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1324
- object: 'chat.completion',
1325
- created: Math.floor(Date.now() / 1000),
1326
- model: modelId,
1327
- choices: [
1328
- {
1329
- index: 0,
1330
- message: {
1331
- role: 'assistant',
1332
- content: response,
1333
- },
1334
- finish_reason: 'stop',
1335
- },
1336
- ],
1337
- usage: {
1338
- prompt_tokens: promptTokens,
1339
- completion_tokens: completionTokens,
1340
- total_tokens: promptTokens + completionTokens,
1341
- },
1342
- };
1343
- } catch (error: any) {
1344
- // Fallback to cloud provider if configured
1345
- if (this.fallbackConfig?.provider === 'openai') {
1346
- return this.fallbackToOpenAI(modelId, request);
1347
- } else if (this.fallbackConfig?.provider === 'bedrock') {
1348
- return this.fallbackToBedrock(modelId, request);
1349
- }
1350
- throw error;
1351
- }
1352
- }
1353
-
1354
- // ── AWS Bedrock Compatibility ──────────────────────────────────────
1355
-
1356
- async bedrockInvoke(modelId: string, request: BedrockInvokeRequest): Promise<BedrockInvokeResponse> {
1357
- try {
1358
- const response = await this.generate(modelId, request.inputText, {
1359
- temperature: request.textGenerationConfig?.temperature,
1360
- maxTokens: request.textGenerationConfig?.maxTokenCount,
1361
- topP: request.textGenerationConfig?.topP,
1362
- });
1363
-
1364
- // Estimate token counts
1365
- const inputTokens = Math.ceil(request.inputText.length / 4);
1366
- const outputTokens = Math.ceil(response.length / 4);
1367
-
1368
- return {
1369
- results: [
1370
- {
1371
- outputText: response,
1372
- tokenCount: outputTokens,
1373
- },
1374
- ],
1375
- input_text_token_count: inputTokens,
1376
- };
1377
- } catch (error: any) {
1378
- // Fallback to cloud provider if configured
1379
- if (this.fallbackConfig?.provider === 'bedrock') {
1380
- return this.fallbackToBedrockCloud(modelId, request);
1381
- } else if (this.fallbackConfig?.provider === 'openai') {
1382
- return this.fallbackToOpenAICloud(modelId, request);
1383
- }
1384
- throw error;
1385
- }
1386
- }
1387
-
1388
- // ── Fallback: OpenAI Cloud ────────────────────────────────────────
1389
-
1390
- private async fallbackToOpenAI(modelId: string, request: OpenAIChatCompletionRequest): Promise<OpenAIChatCompletionResponse> {
1391
- if (!this.fallbackConfig) {
1392
- throw new Error('OpenAI fallback not configured');
1393
- }
1394
-
1395
- const mappedModel = this.mapModelToOpenAI(modelId);
1396
- const payload = {
1397
- model: this.fallbackConfig.model || mappedModel,
1398
- messages: request.messages,
1399
- temperature: request.temperature,
1400
- max_tokens: request.max_tokens,
1401
- top_p: request.top_p,
1402
- frequency_penalty: request.frequency_penalty,
1403
- presence_penalty: request.presence_penalty,
1404
- stop: request.stop,
1405
- };
1406
-
1407
- try {
1408
- const response = await axios.post('https://api.openai.com/v1/chat/completions', payload, {
1409
- headers: {
1410
- Authorization: `Bearer ${this.fallbackConfig.apiKey}`,
1411
- 'Content-Type': 'application/json',
1412
- },
1413
- });
1414
-
1415
- this.emitEvent('fallback_success', { provider: 'openai', originalModel: modelId, mappedModel: this.fallbackConfig.model });
1416
- return response.data;
1417
- } catch (error: any) {
1418
- this.emitProgress('error', 0, `OpenAI fallback failed: ${error.message}`);
1419
- this.emitEvent('fallback_error', { provider: 'openai', error: error.message });
1420
- throw error;
1421
- }
1422
- }
1423
-
1424
- private async fallbackToBedrock(modelId: string, request: OpenAIChatCompletionRequest): Promise<OpenAIChatCompletionResponse> {
1425
- if (!this.fallbackConfig) {
1426
- throw new Error('Bedrock fallback not configured');
1427
- }
1428
-
1429
- // Convert OpenAI format to Bedrock's expected format (simplified)
1430
- const lastMessage = request.messages[request.messages.length - 1];
1431
- const inputText = lastMessage.content;
1432
-
1433
- const bedrockResponse = await this.invokeBedrockCloud(inputText, {
1434
- temperature: request.temperature,
1435
- maxTokenCount: request.max_tokens,
1436
- topP: request.top_p,
1437
- });
1438
-
1439
- // Convert Bedrock response back to OpenAI format
1440
- const promptTokens = Math.ceil(inputText.length / 4);
1441
- const completionTokens = bedrockResponse.results[0].tokenCount;
1442
-
1443
- this.emitEvent('fallback_success', { provider: 'bedrock', originalModel: modelId, mappedModel: this.fallbackConfig.model });
1444
-
1445
- return {
1446
- id: `chat-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1447
- object: 'chat.completion',
1448
- created: Math.floor(Date.now() / 1000),
1449
- model: modelId,
1450
- choices: [
1451
- {
1452
- index: 0,
1453
- message: {
1454
- role: 'assistant',
1455
- content: bedrockResponse.results[0].outputText,
1456
- },
1457
- finish_reason: 'stop',
1458
- },
1459
- ],
1460
- usage: {
1461
- prompt_tokens: promptTokens,
1462
- completion_tokens: completionTokens,
1463
- total_tokens: promptTokens + completionTokens,
1464
- },
1465
- };
1466
- }
1467
-
1468
- private async fallbackToOpenAICloud(modelId: string, request: BedrockInvokeRequest): Promise<BedrockInvokeResponse> {
1469
- if (!this.fallbackConfig) {
1470
- throw new Error('OpenAI fallback not configured');
1471
- }
1472
-
1473
- const mappedModel = this.mapModelToOpenAI(modelId);
1474
- const payload = {
1475
- model: this.fallbackConfig.model || mappedModel,
1476
- messages: [{ role: 'user', content: request.inputText }],
1477
- temperature: request.textGenerationConfig?.temperature,
1478
- max_tokens: request.textGenerationConfig?.maxTokenCount,
1479
- top_p: request.textGenerationConfig?.topP,
1480
- };
1481
-
1482
- try {
1483
- const response = await axios.post('https://api.openai.com/v1/chat/completions', payload, {
1484
- headers: {
1485
- Authorization: `Bearer ${this.fallbackConfig.apiKey}`,
1486
- 'Content-Type': 'application/json',
1487
- },
1488
- });
1489
-
1490
- const outputText = response.data.choices[0].message.content;
1491
- const inputTokens = Math.ceil(request.inputText.length / 4);
1492
- const outputTokens = response.data.usage.completion_tokens;
1493
-
1494
- this.emitEvent('fallback_success', { provider: 'openai', originalModel: modelId, mappedModel: this.fallbackConfig.model });
1495
-
1496
- return {
1497
- results: [
1498
- {
1499
- outputText,
1500
- tokenCount: outputTokens,
1501
- },
1502
- ],
1503
- input_text_token_count: inputTokens,
1504
- };
1505
- } catch (error: any) {
1506
- this.emitProgress('error', 0, `OpenAI fallback failed: ${error.message}`);
1507
- this.emitEvent('fallback_error', { provider: 'openai', error: error.message });
1508
- throw error;
1509
- }
1510
- }
1511
-
1512
- private async fallbackToBedrockCloud(modelId: string, request: BedrockInvokeRequest): Promise<BedrockInvokeResponse> {
1513
- if (!this.fallbackConfig) {
1514
- throw new Error('Bedrock fallback not configured');
1515
- }
1516
-
1517
- try {
1518
- return await this.invokeBedrockCloud(request.inputText, request.textGenerationConfig);
1519
- } catch (error: any) {
1520
- this.emitProgress('error', 0, `Bedrock fallback failed: ${error.message}`);
1521
- this.emitEvent('fallback_error', { provider: 'bedrock', error: error.message });
1522
- throw error;
1523
- }
1524
- }
1525
-
1526
- private async invokeBedrockCloud(inputText: string, config?: BedrockTextGenerationConfig): Promise<BedrockInvokeResponse> {
1527
- if (!this.fallbackConfig) {
1528
- throw new Error('Bedrock fallback not configured');
1529
- }
1530
-
1531
- const region = this.fallbackConfig.region || 'us-east-1';
1532
- const model = this.fallbackConfig.model || 'anthropic.claude-3-sonnet-20240229-v1:0';
1533
-
1534
- // Bedrock endpoint format: https://bedrock-runtime.{region}.amazonaws.com/model/{modelId}/invoke
1535
- const endpoint = `https://bedrock-runtime.${region}.amazonaws.com/model/${model}/invoke`;
1536
-
1537
- const payload = {
1538
- inputText,
1539
- textGenerationConfig: {
1540
- maxTokenCount: config?.maxTokenCount || 256,
1541
- temperature: config?.temperature || 0.7,
1542
- topP: config?.topP || 0.9,
1543
- topK: config?.topK,
1544
- stopSequences: config?.stopSequences,
1545
- },
1546
- };
1547
-
1548
- try {
1549
- const response = await axios.post(endpoint, payload, {
1550
- headers: {
1551
- Authorization: `Bearer ${this.fallbackConfig.apiKey}`,
1552
- 'Content-Type': 'application/json',
1553
- 'X-Amz-Target': 'AmazonBedrockRuntime.InvokeModel',
1554
- },
1555
- });
1556
-
1557
- this.emitEvent('fallback_success', { provider: 'bedrock', model });
1558
- return response.data;
1559
- } catch (error: any) {
1560
- throw new Error(`Bedrock invocation failed: ${error.message}`);
1561
- }
1562
- }
1563
-
1564
- private mapModelToOpenAI(slyModelId: string): string {
1565
- const modelMapping: Record<string, string> = {
1566
- 'quantum-1.7b': 'gpt-4o-mini',
1567
- 'quantum-3b': 'gpt-4o',
1568
- 'quantum-code-3b': 'gpt-4o',
1569
- 'quantum-8b': 'gpt-4-turbo',
1570
- };
1571
- return modelMapping[slyModelId] || 'gpt-4o-mini';
1572
- }
1573
-
1574
- // ═══════════════════════════════════════════════════════════
1575
- // RAG — Retrieval Augmented Generation
1576
- // ═══════════════════════════════════════════════════════════
1577
-
1578
- private localEmbeddingModel: any = null;
1579
- private offlineIndexes: Map<string, OfflineIndex> = new Map();
1580
-
1581
- /**
1582
- * Compute dynamic RAG parameters based on device profile and model.
1583
- */
1584
- private computeRAGConfig(modelId: string): {
1585
- maxContextChars: number;
1586
- maxGenTokens: number;
1587
- chunkSize: number;
1588
- topK: number;
1589
- contextWindow: number;
1590
- deviceTier: 'low' | 'mid' | 'high';
1591
- } {
1592
- const contextWindow = this.modelContextWindow || 2048;
1593
- const memoryMB = this.deviceProfile?.memoryMB || 4096;
1594
- const cpuCores = this.deviceProfile?.cpuCores || 4;
1595
- const hasGPU = !!(this.deviceProfile?.gpuRenderer || this.deviceProfile?.webgpuAvailable);
1596
-
1597
- // Determine device tier
1598
- let deviceTier: 'low' | 'mid' | 'high' = 'low';
1599
- if (memoryMB >= 8192 && cpuCores >= 8) deviceTier = 'high';
1600
- else if (memoryMB >= 4096 && cpuCores >= 4) deviceTier = 'mid';
1601
-
1602
- // Context chars: scale with context window AND device capability
1603
- let maxContextChars: number;
1604
- if (contextWindow <= 2048) {
1605
- maxContextChars = deviceTier === 'high' ? 600 : deviceTier === 'mid' ? 400 : 300;
1606
- } else if (contextWindow <= 4096) {
1607
- maxContextChars = deviceTier === 'high' ? 1500 : deviceTier === 'mid' ? 1000 : 600;
1608
- } else {
1609
- maxContextChars = deviceTier === 'high' ? 3000 : deviceTier === 'mid' ? 2000 : 1000;
1610
- }
1611
-
1612
- // Gen tokens: scale with device tier
1613
- let maxGenTokens: number;
1614
- if (contextWindow <= 2048) {
1615
- maxGenTokens = deviceTier === 'high' ? 200 : deviceTier === 'mid' ? 150 : 100;
1616
- } else {
1617
- maxGenTokens = deviceTier === 'high' ? 400 : deviceTier === 'mid' ? 300 : 150;
1618
- }
1619
-
1620
- // Chunk size: larger chunks for bigger context windows
1621
- const chunkSize = contextWindow <= 2048 ? 256 : contextWindow <= 4096 ? 512 : 1024;
1622
-
1623
- // TopK: more chunks for powerful devices
1624
- const topK = deviceTier === 'high' ? 5 : deviceTier === 'mid' ? 3 : 1;
1625
-
1626
- return { maxContextChars, maxGenTokens, chunkSize, topK, contextWindow, deviceTier };
1627
- }
1628
-
1629
- /**
1630
- * Tier 2: Cloud-indexed RAG with local inference.
1631
- * Retrieves relevant chunks from server, generates response locally.
1632
- */
1633
- async ragQuery(options: RAGOptions): Promise<RAGResponse> {
1634
- const startTime = Date.now();
1635
-
1636
- try {
1637
- if (!this.token) throw new Error('Not authenticated. Call init() first.');
1638
-
1639
- const ragConfig = this.computeRAGConfig(options.modelId);
1640
-
1641
- // Step 1: Retrieve relevant chunks from backend
1642
- const retrievalStart = Date.now();
1643
- const searchResponse = await axios.post(
1644
- `${this.apiUrl}/api/rag/knowledge-bases/${options.knowledgeBaseId}/query`,
1645
- {
1646
- query: options.query,
1647
- top_k: options.topK || ragConfig.topK,
1648
- model_id: options.modelId
1649
- },
1650
- { headers: { Authorization: `Bearer ${this.token}` } }
1651
- );
1652
- const retrievalMs = Date.now() - retrievalStart;
1653
-
1654
- let { retrieved_chunks, prompt_template, context } = searchResponse.data;
1655
-
1656
- // Step 2: Build context with dynamic limits
1657
- const contextBuildStart = Date.now();
1658
- if (context && context.length > ragConfig.maxContextChars) {
1659
- context = context.substring(0, ragConfig.maxContextChars);
1660
- }
1661
- // If no prompt_template from server, build minimal one
1662
- if (!prompt_template) {
1663
- prompt_template = `${context}\n\nQ: ${options.query}\nA:`;
1664
- }
1665
- const contextBuildMs = Date.now() - contextBuildStart;
1666
-
1667
- // Step 3: Generate response — stream if callback provided
1668
- const genStart = Date.now();
1669
- let response: string;
1670
- let firstTokenMs = 0;
1671
-
1672
- if (options.onToken) {
1673
- const streamResult = await this.generateStream(options.modelId, prompt_template, {
1674
- temperature: options.temperature,
1675
- maxTokens: options.maxTokens || ragConfig.maxGenTokens,
1676
- onToken: options.onToken,
1677
- });
1678
- response = streamResult.text;
1679
- firstTokenMs = streamResult.firstTokenMs;
1680
- } else {
1681
- response = await this.generate(options.modelId, prompt_template, {
1682
- temperature: options.temperature,
1683
- maxTokens: options.maxTokens || ragConfig.maxGenTokens,
1684
- });
1685
- firstTokenMs = Date.now() - genStart; // approximate
1686
- }
1687
- const generationMs = Date.now() - genStart;
1688
- const totalMs = Date.now() - startTime;
1689
- const tokensGenerated = response.split(/\s+/).length;
1690
-
1691
- return {
1692
- query: options.query,
1693
- retrievedChunks: (retrieved_chunks || []).map((c: any) => ({
1694
- id: c.id,
1695
- documentId: c.document_id,
1696
- documentName: c.document_name,
1697
- content: c.content,
1698
- similarityScore: c.similarity_score,
1699
- metadata: c.metadata
1700
- })),
1701
- generatedResponse: response,
1702
- context,
1703
- latencyMs: totalMs,
1704
- tierUsed: 2,
1705
- timing: {
1706
- retrievalMs,
1707
- contextBuildMs,
1708
- firstTokenMs,
1709
- generationMs,
1710
- totalMs,
1711
- tokensGenerated,
1712
- tokensPerSecond: generationMs > 0 ? tokensGenerated / (generationMs / 1000) : 0,
1713
- },
1714
- config: {
1715
- maxContextChars: ragConfig.maxContextChars,
1716
- maxGenTokens: ragConfig.maxGenTokens,
1717
- chunkSize: ragConfig.chunkSize,
1718
- topK: options.topK || ragConfig.topK,
1719
- contextWindowUsed: ragConfig.contextWindow,
1720
- deviceTier: ragConfig.deviceTier,
1721
- },
1722
- };
1723
- } catch (error: any) {
1724
- this.emitEvent('error', { stage: 'rag_query', error: error.message });
1725
- throw new Error(`RAG query failed: ${error.message}`);
1726
- }
1727
- }
1728
-
1729
- /**
1730
- * Tier 1: Fully local RAG. Zero network calls.
1731
- * Documents are chunked/embedded on-device, retrieval and generation all local.
1732
- */
1733
- async ragQueryLocal(options: RAGOptions & { documents: Array<{ content: string; name?: string }> }): Promise<RAGResponse> {
1734
- const startTime = Date.now();
1735
-
1736
- try {
1737
- const ragConfig = this.computeRAGConfig(options.modelId);
1738
-
1739
- // Step 1: Load embedding model if needed
1740
- if (!this.localEmbeddingModel) {
1741
- await this.loadEmbeddingModel();
1742
- }
1743
-
1744
- // Step 2: Chunk and embed documents (dynamic chunk size)
1745
- const retrievalStart = Date.now();
1746
- const allChunks: Array<{ content: string; documentName: string; embedding?: number[] }> = [];
1747
- for (const doc of options.documents) {
1748
- const chunks = this.chunkTextLocal(doc.content, ragConfig.chunkSize, Math.floor(ragConfig.chunkSize / 4));
1749
- for (const chunk of chunks) {
1750
- const embedding = await this.embedTextLocal(chunk);
1751
- allChunks.push({ content: chunk, documentName: doc.name || 'Document', embedding });
1752
- }
1753
- }
1754
-
1755
- // Step 3: Embed query and search
1756
- const queryEmbedding = await this.embedTextLocal(options.query);
1757
- const scored = allChunks
1758
- .filter(c => c.embedding)
1759
- .map(c => ({ ...c, similarityScore: this.cosineSimilarity(queryEmbedding, c.embedding!) }))
1760
- .sort((a, b) => b.similarityScore - a.similarityScore)
1761
- .slice(0, options.topK || ragConfig.topK);
1762
- const retrievalMs = Date.now() - retrievalStart;
1763
-
1764
- // Step 4: Build context
1765
- const contextBuildStart = Date.now();
1766
- const bestChunk = scored[0];
1767
- let context = bestChunk.content
1768
- .replace(/[^\x20-\x7E\n]/g, ' ')
1769
- .replace(/\s{2,}/g, ' ')
1770
- .replace(/<[^>]+>/g, ' ')
1771
- .replace(/https?:\/\/\S+/g, '')
1772
- .replace(/[{}()\[\]]/g, '')
1773
- .trim();
1774
- if (context.length > ragConfig.maxContextChars) context = context.substring(0, ragConfig.maxContextChars);
1775
- const prompt = `${context}\n\nQ: ${options.query}\nA:`;
1776
- const contextBuildMs = Date.now() - contextBuildStart;
1777
-
1778
- // Step 5: Generate — stream if callback provided
1779
- const genStart = Date.now();
1780
- let response: string;
1781
- let firstTokenMs = 0;
1782
-
1783
- if (options.onToken) {
1784
- const streamResult = await this.generateStream(options.modelId, prompt, {
1785
- temperature: options.temperature || 0.6,
1786
- maxTokens: options.maxTokens || ragConfig.maxGenTokens,
1787
- onToken: options.onToken,
1788
- });
1789
- response = streamResult.text;
1790
- firstTokenMs = streamResult.firstTokenMs;
1791
- } else {
1792
- response = await this.generate(options.modelId, prompt, {
1793
- temperature: options.temperature || 0.6,
1794
- maxTokens: options.maxTokens || ragConfig.maxGenTokens,
1795
- });
1796
- firstTokenMs = Date.now() - genStart;
1797
- }
1798
- const generationMs = Date.now() - genStart;
1799
- const totalMs = Date.now() - startTime;
1800
- const tokensGenerated = response.split(/\s+/).length;
1801
-
1802
- return {
1803
- query: options.query,
1804
- retrievedChunks: scored.map((c, i) => ({
1805
- id: `local-${i}`,
1806
- documentId: 'local',
1807
- documentName: c.documentName,
1808
- content: c.content,
1809
- similarityScore: c.similarityScore,
1810
- metadata: {}
1811
- })),
1812
- generatedResponse: response,
1813
- context,
1814
- latencyMs: totalMs,
1815
- tierUsed: 1,
1816
- timing: {
1817
- retrievalMs,
1818
- contextBuildMs,
1819
- firstTokenMs,
1820
- generationMs,
1821
- totalMs,
1822
- tokensGenerated,
1823
- tokensPerSecond: generationMs > 0 ? tokensGenerated / (generationMs / 1000) : 0,
1824
- },
1825
- config: {
1826
- maxContextChars: ragConfig.maxContextChars,
1827
- maxGenTokens: ragConfig.maxGenTokens,
1828
- chunkSize: ragConfig.chunkSize,
1829
- topK: options.topK || ragConfig.topK,
1830
- contextWindowUsed: ragConfig.contextWindow,
1831
- deviceTier: ragConfig.deviceTier,
1832
- },
1833
- };
1834
- } catch (error: any) {
1835
- this.emitEvent('error', { stage: 'rag_local', error: error.message });
1836
- throw new Error(`Local RAG failed: ${error.message}`);
1837
- }
1838
- }
1839
-
1840
- /**
1841
- * Tier 3: Offline RAG using a synced knowledge base.
1842
- * First call syncKnowledgeBase(), then use this for offline queries.
1843
- */
1844
- async ragQueryOffline(options: RAGOptions): Promise<RAGResponse> {
1845
- const startTime = Date.now();
1846
-
1847
- const index = this.offlineIndexes.get(options.knowledgeBaseId);
1848
- if (!index) throw new Error(`KB "${options.knowledgeBaseId}" not synced.`);
1849
- if (new Date(index.metadata.expires_at) < new Date()) throw new Error('Offline index expired.');
1850
-
1851
- try {
1852
- const ragConfig = this.computeRAGConfig(options.modelId);
1853
-
1854
- // Load embedding model
1855
- if (!this.localEmbeddingModel) await this.loadEmbeddingModel();
1856
-
1857
- // Search offline index
1858
- const retrievalStart = Date.now();
1859
- const queryEmbedding = await this.embedTextLocal(options.query);
1860
- const scored = index.chunks
1861
- .filter(c => c.embedding && c.embedding.length > 0)
1862
- .map(c => ({ ...c, similarityScore: this.cosineSimilarity(queryEmbedding, c.embedding!) }))
1863
- .sort((a, b) => b.similarityScore - a.similarityScore)
1864
- .slice(0, options.topK || ragConfig.topK);
1865
- const retrievalMs = Date.now() - retrievalStart;
1866
-
1867
- // Build context
1868
- const contextBuildStart = Date.now();
1869
- const bestChunk = scored[0];
1870
- let context = bestChunk.content
1871
- .replace(/[^\x20-\x7E\n]/g, ' ')
1872
- .replace(/\s{2,}/g, ' ')
1873
- .replace(/<[^>]+>/g, ' ')
1874
- .replace(/https?:\/\/\S+/g, '')
1875
- .replace(/[{}()\[\]]/g, '')
1876
- .trim();
1877
- if (context.length > ragConfig.maxContextChars) context = context.substring(0, ragConfig.maxContextChars);
1878
- const prompt = `${context}\n\nQ: ${options.query}\nA:`;
1879
- const contextBuildMs = Date.now() - contextBuildStart;
1880
-
1881
- // Generate
1882
- const genStart = Date.now();
1883
- let response: string;
1884
- let firstTokenMs = 0;
1885
-
1886
- if (options.onToken) {
1887
- const streamResult = await this.generateStream(options.modelId, prompt, {
1888
- temperature: options.temperature || 0.6,
1889
- maxTokens: options.maxTokens || ragConfig.maxGenTokens,
1890
- onToken: options.onToken,
1891
- });
1892
- response = streamResult.text;
1893
- firstTokenMs = streamResult.firstTokenMs;
1894
- } else {
1895
- response = await this.generate(options.modelId, prompt, {
1896
- temperature: options.temperature || 0.6,
1897
- maxTokens: options.maxTokens || ragConfig.maxGenTokens,
1898
- });
1899
- firstTokenMs = Date.now() - genStart;
1900
- }
1901
- const generationMs = Date.now() - genStart;
1902
- const totalMs = Date.now() - startTime;
1903
- const tokensGenerated = response.split(/\s+/).length;
1904
-
1905
- return {
1906
- query: options.query,
1907
- retrievedChunks: scored.map(c => ({
1908
- id: c.id,
1909
- documentId: c.document_id,
1910
- documentName: c.document_name,
1911
- content: c.content,
1912
- similarityScore: c.similarityScore,
1913
- metadata: c.metadata
1914
- })),
1915
- generatedResponse: response,
1916
- context,
1917
- latencyMs: totalMs,
1918
- tierUsed: 3,
1919
- timing: {
1920
- retrievalMs,
1921
- contextBuildMs,
1922
- firstTokenMs,
1923
- generationMs,
1924
- totalMs,
1925
- tokensGenerated,
1926
- tokensPerSecond: generationMs > 0 ? tokensGenerated / (generationMs / 1000) : 0,
1927
- },
1928
- config: {
1929
- maxContextChars: ragConfig.maxContextChars,
1930
- maxGenTokens: ragConfig.maxGenTokens,
1931
- chunkSize: ragConfig.chunkSize,
1932
- topK: options.topK || ragConfig.topK,
1933
- contextWindowUsed: ragConfig.contextWindow,
1934
- deviceTier: ragConfig.deviceTier,
1935
- },
1936
- };
1937
- } catch (error: any) {
1938
- this.emitEvent('error', { stage: 'rag_offline', error: error.message });
1939
- throw new Error(`Offline RAG failed: ${error.message}`);
1940
- }
1941
- }
1942
-
1943
- /**
1944
- * Sync a knowledge base for offline use (Tier 3).
1945
- * Downloads chunks + embeddings from server, stores locally.
1946
- */
1947
- async syncKnowledgeBase(knowledgeBaseId: string, deviceId?: string): Promise<{ chunkCount: number; sizeMb: number; expiresAt: string }> {
1948
- try {
1949
- if (!this.token) throw new Error('Not authenticated. Call init() first.');
1950
-
1951
- const response = await axios.post(
1952
- `${this.apiUrl}/api/rag/knowledge-bases/${knowledgeBaseId}/sync`,
1953
- { device_id: deviceId || this.deviceId || 'sdk-device' },
1954
- { headers: { Authorization: `Bearer ${this.token}` } }
1955
- );
1956
-
1957
- const { sync_package, chunk_count, package_size_mb, expires_at } = response.data;
1958
- this.offlineIndexes.set(knowledgeBaseId, sync_package);
1959
-
1960
- return {
1961
- chunkCount: chunk_count,
1962
- sizeMb: package_size_mb,
1963
- expiresAt: expires_at
1964
- };
1965
- } catch (error: any) {
1966
- throw new Error(`Sync failed: ${error.message}`);
1967
- }
1968
- }
1969
-
1970
- // --- RAG Helper Methods ---
1971
-
1972
- private async loadEmbeddingModel(): Promise<void> {
1973
- this.emitProgress('downloading', 0, 'Loading embedding model (all-MiniLM-L6-v2)...');
1974
- try {
1975
- const { pipeline } = await import('@huggingface/transformers');
1976
- this.localEmbeddingModel = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
1977
- this.emitProgress('ready', 100, 'Embedding model loaded');
1978
- } catch (error: any) {
1979
- this.emitProgress('error', 0, `Embedding model failed: ${error.message}`);
1980
- throw error;
1981
- }
1982
- }
1983
-
1984
- private async embedTextLocal(text: string): Promise<number[]> {
1985
- if (!this.localEmbeddingModel) throw new Error('Embedding model not loaded');
1986
- const result = await this.localEmbeddingModel(text, { pooling: 'mean', normalize: true });
1987
- // Handle different tensor output formats (v2 vs v3 of transformers)
1988
- if (result.data) return Array.from(result.data);
1989
- if (result.tolist) return result.tolist().flat();
1990
- if (Array.isArray(result)) return result.flat();
1991
- throw new Error('Unexpected embedding output format');
1992
- }
1993
-
1994
- private cosineSimilarity(a: number[], b: number[]): number {
1995
- let dot = 0, normA = 0, normB = 0;
1996
- for (let i = 0; i < a.length; i++) {
1997
- dot += a[i] * b[i];
1998
- normA += a[i] * a[i];
1999
- normB += b[i] * b[i];
2000
- }
2001
- const denom = Math.sqrt(normA) * Math.sqrt(normB);
2002
- return denom === 0 ? 0 : dot / denom;
2003
- }
2004
-
2005
- private chunkTextLocal(text: string, chunkSize: number = 512, overlap: number = 128): string[] {
2006
- if (!text || text.length === 0) return [];
2007
- if (overlap >= chunkSize) overlap = Math.floor(chunkSize * 0.25);
2008
- const chunks: string[] = [];
2009
- let start = 0;
2010
- while (start < text.length) {
2011
- let end = start + chunkSize;
2012
- if (end < text.length) {
2013
- const bp = Math.max(text.lastIndexOf('.', end), text.lastIndexOf('\n', end));
2014
- if (bp > start + chunkSize / 2) end = bp + 1;
2015
- }
2016
- const chunk = text.slice(start, end).trim();
2017
- if (chunk.length > 20) chunks.push(chunk);
2018
- start = end - overlap;
2019
- if (start >= text.length) break;
2020
- }
2021
- return chunks;
2022
- }
2023
-
2024
- // ── Static OpenAI Compatible Factory ────────────────────────────────
2025
-
2026
- static openaiCompatible(config: { apiKey: string; apiUrl?: string; fallback?: FallbackConfig }): OpenAICompatibleClient {
2027
- const instance = new SlyOS({
2028
- apiKey: config.apiKey,
2029
- apiUrl: config.apiUrl,
2030
- fallback: { ...config.fallback, provider: config.fallback?.provider || 'openai' } as FallbackConfig,
2031
- });
2032
-
2033
- return {
2034
- chat: {
2035
- completions: {
2036
- async create(request: OpenAIChatCompletionRequest & { model: string }): Promise<OpenAIChatCompletionResponse> {
2037
- const { model, ...chatRequest } = request;
2038
- return instance.chatCompletion(model, chatRequest);
2039
- },
2040
- },
2041
- },
2042
- };
2043
- }
2044
- }
2045
-
2046
- export default SlyOS;
2047
- export type {
2048
- SlyOSConfig,
2049
- SlyOSConfigWithFallback,
2050
- GenerateOptions,
2051
- TranscribeOptions,
2052
- DeviceProfile,
2053
- ProgressEvent,
2054
- SlyEvent,
2055
- QuantizationLevel,
2056
- ModelCategory,
2057
- OpenAIMessage,
2058
- OpenAIChatCompletionRequest,
2059
- OpenAIChatCompletionResponse,
2060
- OpenAIChoice,
2061
- OpenAIUsage,
2062
- BedrockTextGenerationConfig,
2063
- BedrockInvokeRequest,
2064
- BedrockInvokeResponse,
2065
- BedrockResult,
2066
- FallbackConfig,
2067
- FallbackProvider,
2068
- OpenAICompatibleClient,
2069
- RAGOptions,
2070
- RAGChunk,
2071
- RAGResponse,
2072
- OfflineIndex,
2073
- };