@beltoinc/slyos-sdk 1.5.0 → 1.5.2

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/dist/index.js CHANGED
@@ -870,6 +870,61 @@ class SlyOS {
870
870
  throw error;
871
871
  }
872
872
  }
873
+ /**
874
+ * Stream text generation token-by-token.
875
+ * Calls onToken callback for each generated token.
876
+ */
877
+ async generateStream(modelId, prompt, options = {}) {
878
+ if (!this.models.has(modelId)) {
879
+ await this.loadModel(modelId);
880
+ }
881
+ const loaded = this.models.get(modelId);
882
+ if (!loaded)
883
+ throw new Error(`Model "${modelId}" not loaded`);
884
+ const { pipe, info, contextWindow } = loaded;
885
+ if (info.category !== 'llm')
886
+ throw new Error(`Not an LLM`);
887
+ const maxTokens = Math.min(options.maxTokens || 100, contextWindow || 2048);
888
+ const startTime = Date.now();
889
+ let firstTokenTime = 0;
890
+ let accumulated = '';
891
+ this.emitProgress('generating', 0, `Streaming (max ${maxTokens} tokens)...`);
892
+ try {
893
+ const result = await pipe(prompt, {
894
+ max_new_tokens: maxTokens,
895
+ temperature: options.temperature || 0.7,
896
+ top_p: options.topP || 0.9,
897
+ do_sample: true,
898
+ // Transformers.js streamer callback
899
+ callback_function: (output) => {
900
+ if (!firstTokenTime)
901
+ firstTokenTime = Date.now() - startTime;
902
+ if (output && output.length > 0) {
903
+ // output is token IDs, we need to decode
904
+ // The callback in transformers.js v3 gives decoded text tokens
905
+ const tokenText = typeof output === 'string' ? output : '';
906
+ if (tokenText) {
907
+ accumulated += tokenText;
908
+ options.onToken?.(tokenText, accumulated);
909
+ this.emitEvent('token', { token: tokenText, partial: accumulated });
910
+ }
911
+ }
912
+ }
913
+ });
914
+ const rawOutput = result[0].generated_text;
915
+ const response = rawOutput.startsWith(prompt) ? rawOutput.slice(prompt.length).trim() : rawOutput.trim();
916
+ if (!firstTokenTime)
917
+ firstTokenTime = Date.now() - startTime;
918
+ const totalMs = Date.now() - startTime;
919
+ const tokensGenerated = response.split(/\s+/).length;
920
+ this.emitProgress('ready', 100, `Streamed ${tokensGenerated} tokens in ${(totalMs / 1000).toFixed(1)}s`);
921
+ return { text: response, firstTokenMs: firstTokenTime, totalMs, tokensGenerated };
922
+ }
923
+ catch (error) {
924
+ this.emitProgress('error', 0, `Stream failed: ${error.message}`);
925
+ throw error;
926
+ }
927
+ }
873
928
  // ── Inference: Transcribe ───────────────────────────────────────
874
929
  async transcribe(modelId, audioInput, options = {}) {
875
930
  if (!this.models.has(modelId)) {
@@ -1179,6 +1234,45 @@ class SlyOS {
1179
1234
  };
1180
1235
  return modelMapping[slyModelId] || 'gpt-4o-mini';
1181
1236
  }
1237
+ /**
1238
+ * Compute dynamic RAG parameters based on device profile and model.
1239
+ */
1240
+ computeRAGConfig(modelId) {
1241
+ const contextWindow = this.modelContextWindow || 2048;
1242
+ const memoryMB = this.deviceProfile?.memoryMB || 4096;
1243
+ const cpuCores = this.deviceProfile?.cpuCores || 4;
1244
+ const hasGPU = !!(this.deviceProfile?.gpuRenderer || this.deviceProfile?.webgpuAvailable);
1245
+ // Determine device tier
1246
+ let deviceTier = 'low';
1247
+ if (memoryMB >= 8192 && cpuCores >= 8)
1248
+ deviceTier = 'high';
1249
+ else if (memoryMB >= 4096 && cpuCores >= 4)
1250
+ deviceTier = 'mid';
1251
+ // Context chars: scale with context window AND device capability
1252
+ let maxContextChars;
1253
+ if (contextWindow <= 2048) {
1254
+ maxContextChars = deviceTier === 'high' ? 600 : deviceTier === 'mid' ? 400 : 300;
1255
+ }
1256
+ else if (contextWindow <= 4096) {
1257
+ maxContextChars = deviceTier === 'high' ? 1500 : deviceTier === 'mid' ? 1000 : 600;
1258
+ }
1259
+ else {
1260
+ maxContextChars = deviceTier === 'high' ? 3000 : deviceTier === 'mid' ? 2000 : 1000;
1261
+ }
1262
+ // Gen tokens: scale with device tier
1263
+ let maxGenTokens;
1264
+ if (contextWindow <= 2048) {
1265
+ maxGenTokens = deviceTier === 'high' ? 200 : deviceTier === 'mid' ? 150 : 100;
1266
+ }
1267
+ else {
1268
+ maxGenTokens = deviceTier === 'high' ? 400 : deviceTier === 'mid' ? 300 : 150;
1269
+ }
1270
+ // Chunk size: larger chunks for bigger context windows
1271
+ const chunkSize = contextWindow <= 2048 ? 256 : contextWindow <= 4096 ? 512 : 1024;
1272
+ // TopK: more chunks for powerful devices
1273
+ const topK = deviceTier === 'high' ? 5 : deviceTier === 'mid' ? 3 : 1;
1274
+ return { maxContextChars, maxGenTokens, chunkSize, topK, contextWindow, deviceTier };
1275
+ }
1182
1276
  /**
1183
1277
  * Tier 2: Cloud-indexed RAG with local inference.
1184
1278
  * Retrieves relevant chunks from server, generates response locally.
@@ -1188,27 +1282,52 @@ class SlyOS {
1188
1282
  try {
1189
1283
  if (!this.token)
1190
1284
  throw new Error('Not authenticated. Call init() first.');
1285
+ const ragConfig = this.computeRAGConfig(options.modelId);
1191
1286
  // Step 1: Retrieve relevant chunks from backend
1287
+ const retrievalStart = Date.now();
1192
1288
  const searchResponse = await axios.post(`${this.apiUrl}/api/rag/knowledge-bases/${options.knowledgeBaseId}/query`, {
1193
1289
  query: options.query,
1194
- top_k: options.topK || 5,
1290
+ top_k: options.topK || ragConfig.topK,
1195
1291
  model_id: options.modelId
1196
1292
  }, { headers: { Authorization: `Bearer ${this.token}` } });
1293
+ const retrievalMs = Date.now() - retrievalStart;
1197
1294
  let { retrieved_chunks, prompt_template, context } = searchResponse.data;
1198
- // Apply context window limits
1199
- const contextWindow = this.modelContextWindow || 2048;
1200
- const maxContextChars = (contextWindow - 200) * 3; // Rough token-to-char ratio, reserving 200 tokens
1201
- if (context && context.length > maxContextChars) {
1202
- context = context.substring(0, maxContextChars) + '...';
1295
+ // Step 2: Build context with dynamic limits
1296
+ const contextBuildStart = Date.now();
1297
+ if (context && context.length > ragConfig.maxContextChars) {
1298
+ context = context.substring(0, ragConfig.maxContextChars);
1203
1299
  }
1204
- // Step 2: Generate response locally using the augmented prompt
1205
- const response = await this.generate(options.modelId, prompt_template, {
1206
- temperature: options.temperature,
1207
- maxTokens: options.maxTokens,
1208
- });
1300
+ // If no prompt_template from server, build minimal one
1301
+ if (!prompt_template) {
1302
+ prompt_template = `${context}\n\nQ: ${options.query}\nA:`;
1303
+ }
1304
+ const contextBuildMs = Date.now() - contextBuildStart;
1305
+ // Step 3: Generate response — stream if callback provided
1306
+ const genStart = Date.now();
1307
+ let response;
1308
+ let firstTokenMs = 0;
1309
+ if (options.onToken) {
1310
+ const streamResult = await this.generateStream(options.modelId, prompt_template, {
1311
+ temperature: options.temperature,
1312
+ maxTokens: options.maxTokens || ragConfig.maxGenTokens,
1313
+ onToken: options.onToken,
1314
+ });
1315
+ response = streamResult.text;
1316
+ firstTokenMs = streamResult.firstTokenMs;
1317
+ }
1318
+ else {
1319
+ response = await this.generate(options.modelId, prompt_template, {
1320
+ temperature: options.temperature,
1321
+ maxTokens: options.maxTokens || ragConfig.maxGenTokens,
1322
+ });
1323
+ firstTokenMs = Date.now() - genStart; // approximate
1324
+ }
1325
+ const generationMs = Date.now() - genStart;
1326
+ const totalMs = Date.now() - startTime;
1327
+ const tokensGenerated = response.split(/\s+/).length;
1209
1328
  return {
1210
1329
  query: options.query,
1211
- retrievedChunks: retrieved_chunks.map((c) => ({
1330
+ retrievedChunks: (retrieved_chunks || []).map((c) => ({
1212
1331
  id: c.id,
1213
1332
  documentId: c.document_id,
1214
1333
  documentName: c.document_name,
@@ -1218,8 +1337,25 @@ class SlyOS {
1218
1337
  })),
1219
1338
  generatedResponse: response,
1220
1339
  context,
1221
- latencyMs: Date.now() - startTime,
1340
+ latencyMs: totalMs,
1222
1341
  tierUsed: 2,
1342
+ timing: {
1343
+ retrievalMs,
1344
+ contextBuildMs,
1345
+ firstTokenMs,
1346
+ generationMs,
1347
+ totalMs,
1348
+ tokensGenerated,
1349
+ tokensPerSecond: generationMs > 0 ? tokensGenerated / (generationMs / 1000) : 0,
1350
+ },
1351
+ config: {
1352
+ maxContextChars: ragConfig.maxContextChars,
1353
+ maxGenTokens: ragConfig.maxGenTokens,
1354
+ chunkSize: ragConfig.chunkSize,
1355
+ topK: options.topK || ragConfig.topK,
1356
+ contextWindowUsed: ragConfig.contextWindow,
1357
+ deviceTier: ragConfig.deviceTier,
1358
+ },
1223
1359
  };
1224
1360
  }
1225
1361
  catch (error) {
@@ -1234,56 +1370,66 @@ class SlyOS {
1234
1370
  async ragQueryLocal(options) {
1235
1371
  const startTime = Date.now();
1236
1372
  try {
1373
+ const ragConfig = this.computeRAGConfig(options.modelId);
1237
1374
  // Step 1: Load embedding model if needed
1238
1375
  if (!this.localEmbeddingModel) {
1239
1376
  await this.loadEmbeddingModel();
1240
1377
  }
1241
- // Adapt chunk size based on context window for efficiency
1242
- const contextWindow = this.modelContextWindow || 2048;
1243
- const chunkSize = contextWindow <= 1024 ? 256 : contextWindow <= 2048 ? 512 : 1024;
1244
- const overlap = Math.floor(chunkSize / 4);
1245
- // Step 2: Chunk documents if not already chunked
1378
+ // Step 2: Chunk and embed documents (dynamic chunk size)
1379
+ const retrievalStart = Date.now();
1246
1380
  const allChunks = [];
1247
1381
  for (const doc of options.documents) {
1248
- const chunks = this.chunkTextLocal(doc.content, chunkSize, overlap);
1382
+ const chunks = this.chunkTextLocal(doc.content, ragConfig.chunkSize, Math.floor(ragConfig.chunkSize / 4));
1249
1383
  for (const chunk of chunks) {
1250
1384
  const embedding = await this.embedTextLocal(chunk);
1251
1385
  allChunks.push({ content: chunk, documentName: doc.name || 'Document', embedding });
1252
1386
  }
1253
1387
  }
1254
- // Step 3: Embed query
1388
+ // Step 3: Embed query and search
1255
1389
  const queryEmbedding = await this.embedTextLocal(options.query);
1256
- // Step 4: Cosine similarity search
1257
1390
  const scored = allChunks
1258
1391
  .filter(c => c.embedding)
1259
- .map(c => ({
1260
- ...c,
1261
- similarityScore: this.cosineSimilarity(queryEmbedding, c.embedding)
1262
- }))
1392
+ .map(c => ({ ...c, similarityScore: this.cosineSimilarity(queryEmbedding, c.embedding) }))
1263
1393
  .sort((a, b) => b.similarityScore - a.similarityScore)
1264
- .slice(0, options.topK || 5);
1265
- // Step 5: Build context with size limits — keep context SHORT so model has room to generate
1266
- const maxContextChars = contextWindow <= 2048 ? 800 : contextWindow <= 4096 ? 1500 : 3000;
1267
- let contextLength = 0;
1268
- const contextParts = [];
1269
- for (const c of scored) {
1270
- const part = `[Source: ${c.documentName}]\n${c.content}`;
1271
- if (contextLength + part.length <= maxContextChars) {
1272
- contextParts.push(part);
1273
- contextLength += part.length + 10; // Account for separator
1274
- }
1275
- else {
1276
- break;
1277
- }
1394
+ .slice(0, options.topK || ragConfig.topK);
1395
+ const retrievalMs = Date.now() - retrievalStart;
1396
+ // Step 4: Build context
1397
+ const contextBuildStart = Date.now();
1398
+ const bestChunk = scored[0];
1399
+ let context = bestChunk.content
1400
+ .replace(/[^\x20-\x7E\n]/g, ' ')
1401
+ .replace(/\s{2,}/g, ' ')
1402
+ .replace(/<[^>]+>/g, ' ')
1403
+ .replace(/https?:\/\/\S+/g, '')
1404
+ .replace(/[{}()\[\]]/g, '')
1405
+ .trim();
1406
+ if (context.length > ragConfig.maxContextChars)
1407
+ context = context.substring(0, ragConfig.maxContextChars);
1408
+ const prompt = `${context}\n\nQ: ${options.query}\nA:`;
1409
+ const contextBuildMs = Date.now() - contextBuildStart;
1410
+ // Step 5: Generate — stream if callback provided
1411
+ const genStart = Date.now();
1412
+ let response;
1413
+ let firstTokenMs = 0;
1414
+ if (options.onToken) {
1415
+ const streamResult = await this.generateStream(options.modelId, prompt, {
1416
+ temperature: options.temperature || 0.6,
1417
+ maxTokens: options.maxTokens || ragConfig.maxGenTokens,
1418
+ onToken: options.onToken,
1419
+ });
1420
+ response = streamResult.text;
1421
+ firstTokenMs = streamResult.firstTokenMs;
1278
1422
  }
1279
- const context = contextParts.join('\n\n---\n\n');
1280
- const prompt = `Use the following information to answer the question.\n\nInfo: ${context}\n\nQuestion: ${options.query}\nAnswer:`;
1281
- // Step 6: Generate locally
1282
- const maxGen = contextWindow <= 2048 ? 150 : Math.min(300, Math.floor(contextWindow / 4));
1283
- const response = await this.generate(options.modelId, prompt, {
1284
- temperature: options.temperature || 0.6,
1285
- maxTokens: options.maxTokens || maxGen,
1286
- });
1423
+ else {
1424
+ response = await this.generate(options.modelId, prompt, {
1425
+ temperature: options.temperature || 0.6,
1426
+ maxTokens: options.maxTokens || ragConfig.maxGenTokens,
1427
+ });
1428
+ firstTokenMs = Date.now() - genStart;
1429
+ }
1430
+ const generationMs = Date.now() - genStart;
1431
+ const totalMs = Date.now() - startTime;
1432
+ const tokensGenerated = response.split(/\s+/).length;
1287
1433
  return {
1288
1434
  query: options.query,
1289
1435
  retrievedChunks: scored.map((c, i) => ({
@@ -1296,8 +1442,25 @@ class SlyOS {
1296
1442
  })),
1297
1443
  generatedResponse: response,
1298
1444
  context,
1299
- latencyMs: Date.now() - startTime,
1445
+ latencyMs: totalMs,
1300
1446
  tierUsed: 1,
1447
+ timing: {
1448
+ retrievalMs,
1449
+ contextBuildMs,
1450
+ firstTokenMs,
1451
+ generationMs,
1452
+ totalMs,
1453
+ tokensGenerated,
1454
+ tokensPerSecond: generationMs > 0 ? tokensGenerated / (generationMs / 1000) : 0,
1455
+ },
1456
+ config: {
1457
+ maxContextChars: ragConfig.maxContextChars,
1458
+ maxGenTokens: ragConfig.maxGenTokens,
1459
+ chunkSize: ragConfig.chunkSize,
1460
+ topK: options.topK || ragConfig.topK,
1461
+ contextWindowUsed: ragConfig.contextWindow,
1462
+ deviceTier: ragConfig.deviceTier,
1463
+ },
1301
1464
  };
1302
1465
  }
1303
1466
  catch (error) {
@@ -1312,52 +1475,61 @@ class SlyOS {
1312
1475
  async ragQueryOffline(options) {
1313
1476
  const startTime = Date.now();
1314
1477
  const index = this.offlineIndexes.get(options.knowledgeBaseId);
1315
- if (!index) {
1316
- throw new Error(`Knowledge base "${options.knowledgeBaseId}" not synced. Call syncKnowledgeBase() first.`);
1317
- }
1318
- // Check expiry
1319
- if (new Date(index.metadata.expires_at) < new Date()) {
1320
- throw new Error('Offline index has expired. Please re-sync.');
1321
- }
1478
+ if (!index)
1479
+ throw new Error(`KB "${options.knowledgeBaseId}" not synced.`);
1480
+ if (new Date(index.metadata.expires_at) < new Date())
1481
+ throw new Error('Offline index expired.');
1322
1482
  try {
1483
+ const ragConfig = this.computeRAGConfig(options.modelId);
1323
1484
  // Load embedding model
1324
- if (!this.localEmbeddingModel) {
1485
+ if (!this.localEmbeddingModel)
1325
1486
  await this.loadEmbeddingModel();
1326
- }
1327
- // Embed query
1328
- const queryEmbedding = await this.embedTextLocal(options.query);
1329
1487
  // Search offline index
1488
+ const retrievalStart = Date.now();
1489
+ const queryEmbedding = await this.embedTextLocal(options.query);
1330
1490
  const scored = index.chunks
1331
1491
  .filter(c => c.embedding && c.embedding.length > 0)
1332
- .map(c => ({
1333
- ...c,
1334
- similarityScore: this.cosineSimilarity(queryEmbedding, c.embedding)
1335
- }))
1492
+ .map(c => ({ ...c, similarityScore: this.cosineSimilarity(queryEmbedding, c.embedding) }))
1336
1493
  .sort((a, b) => b.similarityScore - a.similarityScore)
1337
- .slice(0, options.topK || 5);
1338
- // Build context with size limits — keep context SHORT so model has room to generate
1339
- const contextWindow = this.modelContextWindow || 2048;
1340
- const maxContextChars = contextWindow <= 2048 ? 800 : contextWindow <= 4096 ? 1500 : 3000;
1341
- let contextLength = 0;
1342
- const contextParts = [];
1343
- for (const c of scored) {
1344
- const part = `[Source: ${c.document_name}]\n${c.content}`;
1345
- if (contextLength + part.length <= maxContextChars) {
1346
- contextParts.push(part);
1347
- contextLength += part.length + 10;
1348
- }
1349
- else {
1350
- break;
1351
- }
1494
+ .slice(0, options.topK || ragConfig.topK);
1495
+ const retrievalMs = Date.now() - retrievalStart;
1496
+ // Build context
1497
+ const contextBuildStart = Date.now();
1498
+ const bestChunk = scored[0];
1499
+ let context = bestChunk.content
1500
+ .replace(/[^\x20-\x7E\n]/g, ' ')
1501
+ .replace(/\s{2,}/g, ' ')
1502
+ .replace(/<[^>]+>/g, ' ')
1503
+ .replace(/https?:\/\/\S+/g, '')
1504
+ .replace(/[{}()\[\]]/g, '')
1505
+ .trim();
1506
+ if (context.length > ragConfig.maxContextChars)
1507
+ context = context.substring(0, ragConfig.maxContextChars);
1508
+ const prompt = `${context}\n\nQ: ${options.query}\nA:`;
1509
+ const contextBuildMs = Date.now() - contextBuildStart;
1510
+ // Generate
1511
+ const genStart = Date.now();
1512
+ let response;
1513
+ let firstTokenMs = 0;
1514
+ if (options.onToken) {
1515
+ const streamResult = await this.generateStream(options.modelId, prompt, {
1516
+ temperature: options.temperature || 0.6,
1517
+ maxTokens: options.maxTokens || ragConfig.maxGenTokens,
1518
+ onToken: options.onToken,
1519
+ });
1520
+ response = streamResult.text;
1521
+ firstTokenMs = streamResult.firstTokenMs;
1352
1522
  }
1353
- const context = contextParts.join('\n\n---\n\n');
1354
- const prompt = `Use the following information to answer the question.\n\nInfo: ${context}\n\nQuestion: ${options.query}\nAnswer:`;
1355
- // Generate locally
1356
- const maxGen = contextWindow <= 2048 ? 150 : Math.min(300, Math.floor(contextWindow / 4));
1357
- const response = await this.generate(options.modelId, prompt, {
1358
- temperature: options.temperature || 0.6,
1359
- maxTokens: options.maxTokens || maxGen,
1360
- });
1523
+ else {
1524
+ response = await this.generate(options.modelId, prompt, {
1525
+ temperature: options.temperature || 0.6,
1526
+ maxTokens: options.maxTokens || ragConfig.maxGenTokens,
1527
+ });
1528
+ firstTokenMs = Date.now() - genStart;
1529
+ }
1530
+ const generationMs = Date.now() - genStart;
1531
+ const totalMs = Date.now() - startTime;
1532
+ const tokensGenerated = response.split(/\s+/).length;
1361
1533
  return {
1362
1534
  query: options.query,
1363
1535
  retrievedChunks: scored.map(c => ({
@@ -1370,8 +1542,25 @@ class SlyOS {
1370
1542
  })),
1371
1543
  generatedResponse: response,
1372
1544
  context,
1373
- latencyMs: Date.now() - startTime,
1545
+ latencyMs: totalMs,
1374
1546
  tierUsed: 3,
1547
+ timing: {
1548
+ retrievalMs,
1549
+ contextBuildMs,
1550
+ firstTokenMs,
1551
+ generationMs,
1552
+ totalMs,
1553
+ tokensGenerated,
1554
+ tokensPerSecond: generationMs > 0 ? tokensGenerated / (generationMs / 1000) : 0,
1555
+ },
1556
+ config: {
1557
+ maxContextChars: ragConfig.maxContextChars,
1558
+ maxGenTokens: ragConfig.maxGenTokens,
1559
+ chunkSize: ragConfig.chunkSize,
1560
+ topK: options.topK || ragConfig.topK,
1561
+ contextWindowUsed: ragConfig.contextWindow,
1562
+ deviceTier: ragConfig.deviceTier,
1563
+ },
1375
1564
  };
1376
1565
  }
1377
1566
  catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@beltoinc/slyos-sdk",
3
- "version": "1.5.0",
3
+ "version": "1.5.2",
4
4
  "description": "SlyOS - On-Device AI SDK for Web and Node.js",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",