@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/src/index.ts CHANGED
@@ -69,7 +69,7 @@ interface ProgressEvent {
69
69
  }
70
70
 
71
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';
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
73
  data?: any;
74
74
  timestamp: number;
75
75
  }
@@ -174,6 +174,8 @@ interface RAGOptions {
174
174
  modelId: string;
175
175
  temperature?: number;
176
176
  maxTokens?: number;
177
+ // NEW: streaming callback
178
+ onToken?: (token: string, partial: string) => void;
177
179
  }
178
180
 
179
181
  interface RAGChunk {
@@ -192,6 +194,25 @@ interface RAGResponse {
192
194
  context: string;
193
195
  latencyMs: number;
194
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
+ };
195
216
  }
196
217
 
197
218
  interface OfflineIndex {
@@ -1145,6 +1166,68 @@ class SlyOS {
1145
1166
  }
1146
1167
  }
1147
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
+
1148
1231
  // ── Inference: Transcribe ───────────────────────────────────────
1149
1232
 
1150
1233
  async transcribe(modelId: string, audioInput: any, options: TranscribeOptions = {}): Promise<string> {
@@ -1495,6 +1578,54 @@ class SlyOS {
1495
1578
  private localEmbeddingModel: any = null;
1496
1579
  private offlineIndexes: Map<string, OfflineIndex> = new Map();
1497
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
+
1498
1629
  /**
1499
1630
  * Tier 2: Cloud-indexed RAG with local inference.
1500
1631
  * Retrieves relevant chunks from server, generates response locally.
@@ -1505,36 +1636,61 @@ class SlyOS {
1505
1636
  try {
1506
1637
  if (!this.token) throw new Error('Not authenticated. Call init() first.');
1507
1638
 
1639
+ const ragConfig = this.computeRAGConfig(options.modelId);
1640
+
1508
1641
  // Step 1: Retrieve relevant chunks from backend
1642
+ const retrievalStart = Date.now();
1509
1643
  const searchResponse = await axios.post(
1510
1644
  `${this.apiUrl}/api/rag/knowledge-bases/${options.knowledgeBaseId}/query`,
1511
1645
  {
1512
1646
  query: options.query,
1513
- top_k: options.topK || 5,
1647
+ top_k: options.topK || ragConfig.topK,
1514
1648
  model_id: options.modelId
1515
1649
  },
1516
1650
  { headers: { Authorization: `Bearer ${this.token}` } }
1517
1651
  );
1652
+ const retrievalMs = Date.now() - retrievalStart;
1518
1653
 
1519
1654
  let { retrieved_chunks, prompt_template, context } = searchResponse.data;
1520
1655
 
1521
- // Apply context window limits
1522
- const contextWindow = this.modelContextWindow || 2048;
1523
- const maxContextChars = (contextWindow - 200) * 3; // Rough token-to-char ratio, reserving 200 tokens
1524
-
1525
- if (context && context.length > maxContextChars) {
1526
- context = context.substring(0, maxContextChars) + '...';
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);
1527
1660
  }
1528
-
1529
- // Step 2: Generate response locally using the augmented prompt
1530
- const response = await this.generate(options.modelId, prompt_template, {
1531
- temperature: options.temperature,
1532
- maxTokens: options.maxTokens,
1533
- });
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;
1534
1690
 
1535
1691
  return {
1536
1692
  query: options.query,
1537
- retrievedChunks: retrieved_chunks.map((c: any) => ({
1693
+ retrievedChunks: (retrieved_chunks || []).map((c: any) => ({
1538
1694
  id: c.id,
1539
1695
  documentId: c.document_id,
1540
1696
  documentName: c.document_name,
@@ -1544,8 +1700,25 @@ class SlyOS {
1544
1700
  })),
1545
1701
  generatedResponse: response,
1546
1702
  context,
1547
- latencyMs: Date.now() - startTime,
1703
+ latencyMs: totalMs,
1548
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
+ },
1549
1722
  };
1550
1723
  } catch (error: any) {
1551
1724
  this.emitEvent('error', { stage: 'rag_query', error: error.message });
@@ -1561,63 +1734,70 @@ class SlyOS {
1561
1734
  const startTime = Date.now();
1562
1735
 
1563
1736
  try {
1737
+ const ragConfig = this.computeRAGConfig(options.modelId);
1738
+
1564
1739
  // Step 1: Load embedding model if needed
1565
1740
  if (!this.localEmbeddingModel) {
1566
1741
  await this.loadEmbeddingModel();
1567
1742
  }
1568
1743
 
1569
- // Adapt chunk size based on context window for efficiency
1570
- const contextWindow = this.modelContextWindow || 2048;
1571
- const chunkSize = contextWindow <= 1024 ? 256 : contextWindow <= 2048 ? 512 : 1024;
1572
- const overlap = Math.floor(chunkSize / 4);
1573
-
1574
- // Step 2: Chunk documents if not already chunked
1744
+ // Step 2: Chunk and embed documents (dynamic chunk size)
1745
+ const retrievalStart = Date.now();
1575
1746
  const allChunks: Array<{ content: string; documentName: string; embedding?: number[] }> = [];
1576
1747
  for (const doc of options.documents) {
1577
- const chunks = this.chunkTextLocal(doc.content, chunkSize, overlap);
1748
+ const chunks = this.chunkTextLocal(doc.content, ragConfig.chunkSize, Math.floor(ragConfig.chunkSize / 4));
1578
1749
  for (const chunk of chunks) {
1579
1750
  const embedding = await this.embedTextLocal(chunk);
1580
1751
  allChunks.push({ content: chunk, documentName: doc.name || 'Document', embedding });
1581
1752
  }
1582
1753
  }
1583
1754
 
1584
- // Step 3: Embed query
1755
+ // Step 3: Embed query and search
1585
1756
  const queryEmbedding = await this.embedTextLocal(options.query);
1586
-
1587
- // Step 4: Cosine similarity search
1588
1757
  const scored = allChunks
1589
1758
  .filter(c => c.embedding)
1590
- .map(c => ({
1591
- ...c,
1592
- similarityScore: this.cosineSimilarity(queryEmbedding, c.embedding!)
1593
- }))
1759
+ .map(c => ({ ...c, similarityScore: this.cosineSimilarity(queryEmbedding, c.embedding!) }))
1594
1760
  .sort((a, b) => b.similarityScore - a.similarityScore)
1595
- .slice(0, options.topK || 5);
1596
-
1597
- // Step 5: Build context with size limits — keep context SHORT so model has room to generate
1598
- const maxContextChars = contextWindow <= 2048 ? 800 : contextWindow <= 4096 ? 1500 : 3000;
1599
- let contextLength = 0;
1600
- const contextParts: string[] = [];
1601
-
1602
- for (const c of scored) {
1603
- const part = `[Source: ${c.documentName}]\n${c.content}`;
1604
- if (contextLength + part.length <= maxContextChars) {
1605
- contextParts.push(part);
1606
- contextLength += part.length + 10; // Account for separator
1607
- } else {
1608
- break;
1609
- }
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;
1610
1797
  }
1611
-
1612
- const context = contextParts.join('\n\n---\n\n');
1613
- const prompt = `Use the following information to answer the question.\n\nInfo: ${context}\n\nQuestion: ${options.query}\nAnswer:`;
1614
-
1615
- // Step 6: Generate locally
1616
- const maxGen = contextWindow <= 2048 ? 150 : Math.min(300, Math.floor(contextWindow / 4));
1617
- const response = await this.generate(options.modelId, prompt, {
1618
- temperature: options.temperature || 0.6,
1619
- maxTokens: options.maxTokens || maxGen,
1620
- });
1798
+ const generationMs = Date.now() - genStart;
1799
+ const totalMs = Date.now() - startTime;
1800
+ const tokensGenerated = response.split(/\s+/).length;
1621
1801
 
1622
1802
  return {
1623
1803
  query: options.query,
@@ -1631,8 +1811,25 @@ class SlyOS {
1631
1811
  })),
1632
1812
  generatedResponse: response,
1633
1813
  context,
1634
- latencyMs: Date.now() - startTime,
1814
+ latencyMs: totalMs,
1635
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
+ },
1636
1833
  };
1637
1834
  } catch (error: any) {
1638
1835
  this.emitEvent('error', { stage: 'rag_local', error: error.message });
@@ -1648,59 +1845,62 @@ class SlyOS {
1648
1845
  const startTime = Date.now();
1649
1846
 
1650
1847
  const index = this.offlineIndexes.get(options.knowledgeBaseId);
1651
- if (!index) {
1652
- throw new Error(`Knowledge base "${options.knowledgeBaseId}" not synced. Call syncKnowledgeBase() first.`);
1653
- }
1654
-
1655
- // Check expiry
1656
- if (new Date(index.metadata.expires_at) < new Date()) {
1657
- throw new Error('Offline index has expired. Please re-sync.');
1658
- }
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.');
1659
1850
 
1660
1851
  try {
1661
- // Load embedding model
1662
- if (!this.localEmbeddingModel) {
1663
- await this.loadEmbeddingModel();
1664
- }
1852
+ const ragConfig = this.computeRAGConfig(options.modelId);
1665
1853
 
1666
- // Embed query
1667
- const queryEmbedding = await this.embedTextLocal(options.query);
1854
+ // Load embedding model
1855
+ if (!this.localEmbeddingModel) await this.loadEmbeddingModel();
1668
1856
 
1669
1857
  // Search offline index
1858
+ const retrievalStart = Date.now();
1859
+ const queryEmbedding = await this.embedTextLocal(options.query);
1670
1860
  const scored = index.chunks
1671
1861
  .filter(c => c.embedding && c.embedding.length > 0)
1672
- .map(c => ({
1673
- ...c,
1674
- similarityScore: this.cosineSimilarity(queryEmbedding, c.embedding!)
1675
- }))
1862
+ .map(c => ({ ...c, similarityScore: this.cosineSimilarity(queryEmbedding, c.embedding!) }))
1676
1863
  .sort((a, b) => b.similarityScore - a.similarityScore)
1677
- .slice(0, options.topK || 5);
1678
-
1679
- // Build context with size limits — keep context SHORT so model has room to generate
1680
- const contextWindow = this.modelContextWindow || 2048;
1681
- const maxContextChars = contextWindow <= 2048 ? 800 : contextWindow <= 4096 ? 1500 : 3000;
1682
- let contextLength = 0;
1683
- const contextParts: string[] = [];
1684
-
1685
- for (const c of scored) {
1686
- const part = `[Source: ${c.document_name}]\n${c.content}`;
1687
- if (contextLength + part.length <= maxContextChars) {
1688
- contextParts.push(part);
1689
- contextLength += part.length + 10;
1690
- } else {
1691
- break;
1692
- }
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;
1693
1900
  }
1694
-
1695
- const context = contextParts.join('\n\n---\n\n');
1696
- const prompt = `Use the following information to answer the question.\n\nInfo: ${context}\n\nQuestion: ${options.query}\nAnswer:`;
1697
-
1698
- // Generate locally
1699
- const maxGen = contextWindow <= 2048 ? 150 : Math.min(300, Math.floor(contextWindow / 4));
1700
- const response = await this.generate(options.modelId, prompt, {
1701
- temperature: options.temperature || 0.6,
1702
- maxTokens: options.maxTokens || maxGen,
1703
- });
1901
+ const generationMs = Date.now() - genStart;
1902
+ const totalMs = Date.now() - startTime;
1903
+ const tokensGenerated = response.split(/\s+/).length;
1704
1904
 
1705
1905
  return {
1706
1906
  query: options.query,
@@ -1714,8 +1914,25 @@ class SlyOS {
1714
1914
  })),
1715
1915
  generatedResponse: response,
1716
1916
  context,
1717
- latencyMs: Date.now() - startTime,
1917
+ latencyMs: totalMs,
1718
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
+ },
1719
1936
  };
1720
1937
  } catch (error: any) {
1721
1938
  this.emitEvent('error', { stage: 'rag_offline', error: error.message });