@soulcraft/brainy 3.20.2 → 3.20.3

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.
Files changed (89) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/bin/brainy-interactive.js +2 -2
  3. package/dist/brainy.d.ts +1 -1
  4. package/dist/mcp/brainyMCPAdapter.d.ts +1 -1
  5. package/dist/mcp/brainyMCPService.d.ts +1 -1
  6. package/dist/neural/embeddedPatterns.d.ts +1 -1
  7. package/dist/neural/embeddedPatterns.js +1 -1
  8. package/dist/shared/default-augmentations.d.ts +1 -1
  9. package/dist/types/{brainyDataInterface.js → brainyInterface.js} +1 -1
  10. package/package.json +1 -1
  11. package/dist/augmentationFactory.d.ts +0 -86
  12. package/dist/augmentationFactory.js +0 -342
  13. package/dist/augmentationRegistry.d.ts +0 -38
  14. package/dist/augmentationRegistry.js +0 -54
  15. package/dist/augmentationRegistryLoader.d.ts +0 -146
  16. package/dist/augmentationRegistryLoader.js +0 -213
  17. package/dist/augmentations/KnowledgeAugmentation.d.ts +0 -40
  18. package/dist/augmentations/KnowledgeAugmentation.js +0 -251
  19. package/dist/augmentations/intelligentVerbScoring.d.ts +0 -158
  20. package/dist/augmentations/intelligentVerbScoring.js +0 -377
  21. package/dist/augmentations/marketplace/AugmentationMarketplace.d.ts +0 -168
  22. package/dist/augmentations/marketplace/AugmentationMarketplace.js +0 -329
  23. package/dist/augmentations/marketplace/cli.d.ts +0 -47
  24. package/dist/augmentations/marketplace/cli.js +0 -265
  25. package/dist/augmentations/memoryAugmentations.d.ts +0 -72
  26. package/dist/augmentations/memoryAugmentations.js +0 -280
  27. package/dist/augmentations/serverSearchAugmentations.d.ts +0 -190
  28. package/dist/augmentations/serverSearchAugmentations.js +0 -586
  29. package/dist/brainy-unified.d.ts +0 -106
  30. package/dist/brainy-unified.js +0 -327
  31. package/dist/brainyData.d.ts +0 -1832
  32. package/dist/brainyData.js +0 -6443
  33. package/dist/brainyDataV3.d.ts +0 -186
  34. package/dist/brainyDataV3.js +0 -337
  35. package/dist/config/distributedPresets-new.d.ts +0 -118
  36. package/dist/config/distributedPresets-new.js +0 -318
  37. package/dist/config/modelPrecisionManager.d.ts +0 -42
  38. package/dist/config/modelPrecisionManager.js +0 -98
  39. package/dist/connectors/interfaces/IConnector.d.ts +0 -143
  40. package/dist/connectors/interfaces/IConnector.js +0 -8
  41. package/dist/demo.d.ts +0 -106
  42. package/dist/demo.js +0 -201
  43. package/dist/embeddings/SingletonModelManager.d.ts +0 -95
  44. package/dist/embeddings/SingletonModelManager.js +0 -220
  45. package/dist/embeddings/lightweight-embedder.d.ts +0 -22
  46. package/dist/embeddings/lightweight-embedder.js +0 -128
  47. package/dist/embeddings/model-manager.d.ts +0 -39
  48. package/dist/embeddings/model-manager.js +0 -245
  49. package/dist/embeddings/universal-memory-manager.d.ts +0 -38
  50. package/dist/embeddings/universal-memory-manager.js +0 -166
  51. package/dist/embeddings/worker-embedding.d.ts +0 -7
  52. package/dist/embeddings/worker-embedding.js +0 -73
  53. package/dist/embeddings/worker-manager.d.ts +0 -28
  54. package/dist/embeddings/worker-manager.js +0 -162
  55. package/dist/examples/basicUsage.d.ts +0 -4
  56. package/dist/examples/basicUsage.js +0 -121
  57. package/dist/indices/fieldIndex.d.ts +0 -76
  58. package/dist/indices/fieldIndex.js +0 -357
  59. package/dist/mcp/brainyMCPBroadcast.d.ts +0 -82
  60. package/dist/mcp/brainyMCPBroadcast.js +0 -303
  61. package/dist/mcp/brainyMCPClient.d.ts +0 -92
  62. package/dist/mcp/brainyMCPClient.js +0 -258
  63. package/dist/scripts/precomputePatternEmbeddings.d.ts +0 -19
  64. package/dist/scripts/precomputePatternEmbeddings.js +0 -100
  65. package/dist/utils/cacheAutoConfig.d.ts +0 -63
  66. package/dist/utils/cacheAutoConfig.js +0 -261
  67. package/dist/utils/hybridModelManager.d.ts +0 -64
  68. package/dist/utils/hybridModelManager.js +0 -95
  69. package/dist/utils/statistics.d.ts +0 -28
  70. package/dist/utils/statistics.js +0 -25
  71. package/dist/vfs/ConceptSystem.d.ts +0 -203
  72. package/dist/vfs/ConceptSystem.js +0 -545
  73. package/dist/vfs/EntityManager.d.ts +0 -75
  74. package/dist/vfs/EntityManager.js +0 -216
  75. package/dist/vfs/EventRecorder.d.ts +0 -84
  76. package/dist/vfs/EventRecorder.js +0 -269
  77. package/dist/vfs/GitBridge.d.ts +0 -167
  78. package/dist/vfs/GitBridge.js +0 -537
  79. package/dist/vfs/KnowledgeAugmentation.d.ts +0 -104
  80. package/dist/vfs/KnowledgeAugmentation.js +0 -146
  81. package/dist/vfs/KnowledgeLayer.d.ts +0 -35
  82. package/dist/vfs/KnowledgeLayer.js +0 -443
  83. package/dist/vfs/PersistentEntitySystem.d.ts +0 -165
  84. package/dist/vfs/PersistentEntitySystem.js +0 -503
  85. package/dist/vfs/SemanticVersioning.d.ts +0 -105
  86. package/dist/vfs/SemanticVersioning.js +0 -309
  87. package/dist/vfs/VFSHealthCheck.d.ts +0 -78
  88. package/dist/vfs/VFSHealthCheck.js +0 -299
  89. /package/dist/types/{brainyDataInterface.d.ts → brainyInterface.d.ts} +0 -0
@@ -1,100 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * 🧠 Pre-compute Pattern Embeddings Script
4
- *
5
- * This script pre-computes embeddings for all patterns and saves them to disk.
6
- * Run this once after adding new patterns to avoid runtime embedding costs.
7
- *
8
- * How it works:
9
- * 1. Load all patterns from library.json
10
- * 2. Use Brainy's embedding model to encode each pattern's examples
11
- * 3. Average the example embeddings to get a robust pattern representation
12
- * 4. Save embeddings to patterns/embeddings.bin for instant loading
13
- *
14
- * Benefits:
15
- * - Pattern matching becomes pure math (cosine similarity)
16
- * - No embedding model calls during query processing
17
- * - Patterns load instantly with pre-computed vectors
18
- */
19
- import { BrainyData } from '../brainyData.js';
20
- import patternData from '../patterns/library.json' assert { type: 'json' };
21
- import * as fs from 'fs/promises';
22
- import * as path from 'path';
23
- async function precomputeEmbeddings() {
24
- console.log('🧠 Pre-computing pattern embeddings...');
25
- // Initialize Brainy with minimal config
26
- const brain = new BrainyData({
27
- storage: { forceMemoryStorage: true },
28
- logging: { verbose: false }
29
- });
30
- await brain.init();
31
- console.log('✅ Brainy initialized');
32
- const embeddings = {};
33
- let processedCount = 0;
34
- const totalPatterns = patternData.patterns.length;
35
- for (const pattern of patternData.patterns) {
36
- console.log(`\n📝 Processing pattern: ${pattern.id} (${++processedCount}/${totalPatterns})`);
37
- console.log(` Category: ${pattern.category}`);
38
- console.log(` Examples: ${pattern.examples.length}`);
39
- // Embed all examples
40
- const exampleEmbeddings = [];
41
- for (const example of pattern.examples) {
42
- try {
43
- const embedding = await brain.embed(example);
44
- exampleEmbeddings.push(embedding);
45
- console.log(` ✓ Embedded: "${example.substring(0, 50)}..."`);
46
- }
47
- catch (error) {
48
- console.error(` ✗ Failed to embed: "${example}"`, error);
49
- }
50
- }
51
- if (exampleEmbeddings.length === 0) {
52
- console.warn(` ⚠️ No embeddings generated for pattern ${pattern.id}`);
53
- continue;
54
- }
55
- // Average the embeddings for a robust representation
56
- const avgEmbedding = averageVectors(exampleEmbeddings);
57
- embeddings[pattern.id] = {
58
- patternId: pattern.id,
59
- embedding: avgEmbedding,
60
- examples: pattern.examples,
61
- averageMethod: 'arithmetic_mean'
62
- };
63
- console.log(` ✅ Generated ${avgEmbedding.length}-dimensional embedding`);
64
- }
65
- // Save embeddings to file
66
- const outputPath = path.join(process.cwd(), 'src', 'patterns', 'embeddings.json');
67
- await fs.writeFile(outputPath, JSON.stringify(embeddings, null, 2));
68
- console.log(`\n✅ Saved ${Object.keys(embeddings).length} pattern embeddings to ${outputPath}`);
69
- // Calculate storage size
70
- const stats = await fs.stat(outputPath);
71
- console.log(`📊 File size: ${(stats.size / 1024).toFixed(2)} KB`);
72
- // Print statistics
73
- console.log('\n📈 Embedding Statistics:');
74
- console.log(` Total patterns: ${totalPatterns}`);
75
- console.log(` Successfully embedded: ${Object.keys(embeddings).length}`);
76
- console.log(` Failed: ${totalPatterns - Object.keys(embeddings).length}`);
77
- console.log(` Embedding dimensions: ${Object.values(embeddings)[0]?.embedding.length || 0}`);
78
- await brain.close();
79
- console.log('\n✅ Complete!');
80
- }
81
- function averageVectors(vectors) {
82
- if (vectors.length === 0)
83
- return [];
84
- const dim = vectors[0].length;
85
- const avg = new Array(dim).fill(0);
86
- // Sum all vectors
87
- for (const vec of vectors) {
88
- for (let i = 0; i < dim; i++) {
89
- avg[i] += vec[i];
90
- }
91
- }
92
- // Divide by count to get average
93
- for (let i = 0; i < dim; i++) {
94
- avg[i] /= vectors.length;
95
- }
96
- return avg;
97
- }
98
- // Run the script
99
- precomputeEmbeddings().catch(console.error);
100
- //# sourceMappingURL=precomputePatternEmbeddings.js.map
@@ -1,63 +0,0 @@
1
- /**
2
- * Intelligent cache auto-configuration system
3
- * Adapts cache settings based on environment, usage patterns, and storage type
4
- */
5
- import { SearchCacheConfig } from './searchCache.js';
6
- import { BrainyConfig } from '../brainy.js';
7
- export interface CacheUsageStats {
8
- totalQueries: number;
9
- repeatQueries: number;
10
- avgQueryTime: number;
11
- memoryPressure: number;
12
- storageType: 'memory' | 'opfs' | 's3' | 'filesystem';
13
- isDistributed: boolean;
14
- changeFrequency: number;
15
- readWriteRatio: number;
16
- }
17
- export interface AutoConfigResult {
18
- cacheConfig: SearchCacheConfig;
19
- realtimeConfig: NonNullable<BrainyConfig['realtimeUpdates']>;
20
- reasoning: string[];
21
- }
22
- export declare class CacheAutoConfigurator {
23
- private stats;
24
- private configHistory;
25
- private lastOptimization;
26
- /**
27
- * Auto-detect optimal cache configuration based on current conditions
28
- */
29
- autoDetectOptimalConfig(storageConfig?: BrainyConfig['storage'], currentStats?: Partial<CacheUsageStats>): AutoConfigResult;
30
- /**
31
- * Dynamically adjust configuration based on runtime performance
32
- */
33
- adaptConfiguration(currentConfig: SearchCacheConfig, performanceMetrics: {
34
- hitRate: number;
35
- avgResponseTime: number;
36
- memoryUsage: number;
37
- externalChangesDetected: number;
38
- timeSinceLastChange: number;
39
- }): AutoConfigResult | null;
40
- /**
41
- * Get recommended configuration for specific use case
42
- */
43
- getRecommendedConfig(useCase: 'high-consistency' | 'balanced' | 'performance-first'): AutoConfigResult;
44
- /**
45
- * Learn from usage patterns and improve recommendations
46
- */
47
- learnFromUsage(usageData: {
48
- queryPatterns: string[];
49
- responseTime: number;
50
- cacheHits: number;
51
- totalQueries: number;
52
- dataChanges: number;
53
- timeWindow: number;
54
- }): void;
55
- private detectEnvironment;
56
- private generateOptimalConfig;
57
- private calculateRealtimeConfig;
58
- private detectMemoryConstraints;
59
- /**
60
- * Get human-readable explanation of current configuration
61
- */
62
- getConfigExplanation(config: AutoConfigResult): string;
63
- }
@@ -1,261 +0,0 @@
1
- /**
2
- * Intelligent cache auto-configuration system
3
- * Adapts cache settings based on environment, usage patterns, and storage type
4
- */
5
- export class CacheAutoConfigurator {
6
- constructor() {
7
- this.stats = {
8
- totalQueries: 0,
9
- repeatQueries: 0,
10
- avgQueryTime: 50,
11
- memoryPressure: 0,
12
- storageType: 'memory',
13
- isDistributed: false,
14
- changeFrequency: 0,
15
- readWriteRatio: 10,
16
- };
17
- this.configHistory = [];
18
- this.lastOptimization = 0;
19
- }
20
- /**
21
- * Auto-detect optimal cache configuration based on current conditions
22
- */
23
- autoDetectOptimalConfig(storageConfig, currentStats) {
24
- // Update stats with current information
25
- if (currentStats) {
26
- this.stats = { ...this.stats, ...currentStats };
27
- }
28
- // Detect environment characteristics
29
- this.detectEnvironment(storageConfig);
30
- // Generate optimal configuration
31
- const result = this.generateOptimalConfig();
32
- // Store for learning
33
- this.configHistory.push(result);
34
- this.lastOptimization = Date.now();
35
- return result;
36
- }
37
- /**
38
- * Dynamically adjust configuration based on runtime performance
39
- */
40
- adaptConfiguration(currentConfig, performanceMetrics) {
41
- const reasoning = [];
42
- let needsUpdate = false;
43
- // Check if we should update (don't over-optimize)
44
- if (Date.now() - this.lastOptimization < 60000) {
45
- return null; // Wait at least 1 minute between optimizations
46
- }
47
- // Analyze performance patterns
48
- const adaptations = {};
49
- // Low hit rate → adjust cache size or TTL
50
- if (performanceMetrics.hitRate < 0.3) {
51
- if (performanceMetrics.externalChangesDetected > 5) {
52
- // Too many external changes → shorter TTL
53
- adaptations.maxAge = Math.max(60000, currentConfig.maxAge * 0.7);
54
- reasoning.push('Reduced cache TTL due to frequent external changes');
55
- needsUpdate = true;
56
- }
57
- else {
58
- // Expand cache size for better hit rate
59
- adaptations.maxSize = Math.min(500, (currentConfig.maxSize || 100) * 1.5);
60
- reasoning.push('Increased cache size due to low hit rate');
61
- needsUpdate = true;
62
- }
63
- }
64
- // High hit rate but slow responses → might need cache warming
65
- if (performanceMetrics.hitRate > 0.8 && performanceMetrics.avgResponseTime > 100) {
66
- reasoning.push('High hit rate but slow responses - consider cache warming');
67
- }
68
- // Memory pressure → reduce cache size
69
- if (performanceMetrics.memoryUsage > 100 * 1024 * 1024) { // 100MB
70
- adaptations.maxSize = Math.max(20, (currentConfig.maxSize || 100) * 0.7);
71
- reasoning.push('Reduced cache size due to memory pressure');
72
- needsUpdate = true;
73
- }
74
- // Recent external changes → adaptive TTL
75
- if (performanceMetrics.timeSinceLastChange < 30000) { // 30 seconds
76
- adaptations.maxAge = Math.max(30000, currentConfig.maxAge * 0.8);
77
- reasoning.push('Shortened TTL due to recent external changes');
78
- needsUpdate = true;
79
- }
80
- if (!needsUpdate) {
81
- return null;
82
- }
83
- const newCacheConfig = {
84
- ...currentConfig,
85
- ...adaptations
86
- };
87
- const newRealtimeConfig = this.calculateRealtimeConfig();
88
- return {
89
- cacheConfig: newCacheConfig,
90
- realtimeConfig: newRealtimeConfig,
91
- reasoning
92
- };
93
- }
94
- /**
95
- * Get recommended configuration for specific use case
96
- */
97
- getRecommendedConfig(useCase) {
98
- const configs = {
99
- 'high-consistency': {
100
- cache: { maxAge: 120000, maxSize: 50 },
101
- realtime: { interval: 15000, enabled: true },
102
- reasoning: ['Optimized for data consistency and real-time updates']
103
- },
104
- 'balanced': {
105
- cache: { maxAge: 300000, maxSize: 100 },
106
- realtime: { interval: 30000, enabled: true },
107
- reasoning: ['Balanced performance and consistency']
108
- },
109
- 'performance-first': {
110
- cache: { maxAge: 600000, maxSize: 200 },
111
- realtime: { interval: 60000, enabled: true },
112
- reasoning: ['Optimized for maximum cache performance']
113
- }
114
- };
115
- const config = configs[useCase];
116
- return {
117
- cacheConfig: {
118
- enabled: true,
119
- ...config.cache
120
- },
121
- realtimeConfig: {
122
- updateIndex: true,
123
- updateStatistics: true,
124
- ...config.realtime
125
- },
126
- reasoning: config.reasoning
127
- };
128
- }
129
- /**
130
- * Learn from usage patterns and improve recommendations
131
- */
132
- learnFromUsage(usageData) {
133
- // Update internal stats for better future recommendations
134
- this.stats.totalQueries += usageData.totalQueries;
135
- this.stats.repeatQueries += usageData.cacheHits;
136
- this.stats.avgQueryTime = (this.stats.avgQueryTime + usageData.responseTime) / 2;
137
- this.stats.changeFrequency = usageData.dataChanges / (usageData.timeWindow / 60000);
138
- // Calculate read/write ratio
139
- const writes = usageData.dataChanges;
140
- const reads = usageData.totalQueries;
141
- this.stats.readWriteRatio = reads > 0 ? reads / Math.max(writes, 1) : 10;
142
- }
143
- detectEnvironment(storageConfig) {
144
- // Detect storage type
145
- if (storageConfig?.s3Storage || storageConfig?.customS3Storage) {
146
- this.stats.storageType = 's3';
147
- this.stats.isDistributed = true;
148
- }
149
- else if (storageConfig?.forceFileSystemStorage) {
150
- this.stats.storageType = 'filesystem';
151
- }
152
- else if (storageConfig?.forceMemoryStorage) {
153
- this.stats.storageType = 'memory';
154
- }
155
- else {
156
- // Auto-detect browser vs Node.js
157
- this.stats.storageType = typeof window !== 'undefined' ? 'opfs' : 'filesystem';
158
- }
159
- // Detect distributed mode indicators
160
- this.stats.isDistributed = this.stats.isDistributed ||
161
- Boolean(storageConfig?.s3Storage || storageConfig?.customS3Storage);
162
- }
163
- generateOptimalConfig() {
164
- const reasoning = [];
165
- // Base configuration
166
- let cacheConfig = {
167
- enabled: true,
168
- maxSize: 100,
169
- maxAge: 300000, // 5 minutes
170
- hitCountWeight: 0.3
171
- };
172
- let realtimeConfig = {
173
- enabled: false,
174
- interval: 60000,
175
- updateIndex: true,
176
- updateStatistics: true
177
- };
178
- // Adjust for storage type
179
- if (this.stats.storageType === 's3' || this.stats.isDistributed) {
180
- cacheConfig.maxAge = 180000; // 3 minutes for distributed
181
- realtimeConfig.enabled = true;
182
- realtimeConfig.interval = 30000; // 30 seconds
183
- reasoning.push('Distributed storage detected - enabled real-time updates');
184
- reasoning.push('Reduced cache TTL for distributed consistency');
185
- }
186
- // Adjust for read/write patterns
187
- if (this.stats.readWriteRatio > 20) {
188
- // Read-heavy workload
189
- cacheConfig.maxSize = Math.min(300, (cacheConfig.maxSize || 100) * 2);
190
- cacheConfig.maxAge = Math.min(900000, (cacheConfig.maxAge || 300000) * 1.5); // Up to 15 minutes
191
- reasoning.push('Read-heavy workload detected - increased cache size and TTL');
192
- }
193
- else if (this.stats.readWriteRatio < 5) {
194
- // Write-heavy workload
195
- cacheConfig.maxSize = Math.max(50, (cacheConfig.maxSize || 100) * 0.7);
196
- cacheConfig.maxAge = Math.max(60000, (cacheConfig.maxAge || 300000) * 0.6);
197
- reasoning.push('Write-heavy workload detected - reduced cache size and TTL');
198
- }
199
- // Adjust for change frequency
200
- if (this.stats.changeFrequency > 10) { // More than 10 changes per minute
201
- realtimeConfig.interval = Math.max(10000, realtimeConfig.interval * 0.5);
202
- cacheConfig.maxAge = Math.max(30000, (cacheConfig.maxAge || 300000) * 0.5);
203
- reasoning.push('High change frequency detected - increased update frequency');
204
- }
205
- // Memory constraints
206
- if (this.detectMemoryConstraints()) {
207
- cacheConfig.maxSize = Math.max(20, (cacheConfig.maxSize || 100) * 0.6);
208
- reasoning.push('Memory constraints detected - reduced cache size');
209
- }
210
- // Performance optimization
211
- if (this.stats.avgQueryTime > 200) {
212
- cacheConfig.maxSize = Math.min(500, (cacheConfig.maxSize || 100) * 1.5);
213
- reasoning.push('Slow queries detected - increased cache size');
214
- }
215
- return {
216
- cacheConfig,
217
- realtimeConfig,
218
- reasoning
219
- };
220
- }
221
- calculateRealtimeConfig() {
222
- return {
223
- enabled: this.stats.isDistributed || this.stats.changeFrequency > 1,
224
- interval: this.stats.isDistributed ? 30000 : 60000,
225
- updateIndex: true,
226
- updateStatistics: true
227
- };
228
- }
229
- detectMemoryConstraints() {
230
- // Simple heuristic for memory constraints
231
- try {
232
- if (typeof performance !== 'undefined' && 'memory' in performance) {
233
- const memInfo = performance.memory;
234
- return memInfo.usedJSHeapSize > memInfo.jsHeapSizeLimit * 0.8;
235
- }
236
- }
237
- catch (e) {
238
- // Ignore errors
239
- }
240
- // Default assumption for constrained environments
241
- return false;
242
- }
243
- /**
244
- * Get human-readable explanation of current configuration
245
- */
246
- getConfigExplanation(config) {
247
- const lines = [
248
- '🤖 Brainy Auto-Configuration:',
249
- '',
250
- `📊 Cache: ${config.cacheConfig.maxSize} queries, ${config.cacheConfig.maxAge / 1000}s TTL`,
251
- `🔄 Updates: ${config.realtimeConfig.enabled ? `Every ${(config.realtimeConfig.interval || 30000) / 1000}s` : 'Disabled'}`,
252
- '',
253
- '🎯 Optimizations applied:'
254
- ];
255
- config.reasoning.forEach(reason => {
256
- lines.push(` • ${reason}`);
257
- });
258
- return lines.join('\n');
259
- }
260
- }
261
- //# sourceMappingURL=cacheAutoConfig.js.map
@@ -1,64 +0,0 @@
1
- /**
2
- * Hybrid Model Manager - BEST OF BOTH WORLDS
3
- *
4
- * NOW A WRAPPER AROUND SingletonModelManager
5
- * Maintained for backward compatibility
6
- *
7
- * Previously combined:
8
- * 1. Multi-source downloading strategy (GitHub → CDN → Hugging Face)
9
- * 2. Singleton pattern preventing multiple ONNX model loads
10
- * 3. Environment-specific optimizations
11
- * 4. Graceful fallbacks and error handling
12
- *
13
- * Now delegates all operations to SingletonModelManager for true unification
14
- */
15
- import { EmbeddingFunction } from '../coreTypes.js';
16
- /**
17
- * HybridModelManager - Now a wrapper around SingletonModelManager
18
- * Maintained for backward compatibility
19
- */
20
- declare class HybridModelManager {
21
- private static instance;
22
- private constructor();
23
- static getInstance(): HybridModelManager;
24
- /**
25
- * Get the primary embedding model - delegates to SingletonModelManager
26
- */
27
- getPrimaryModel(): Promise<any>;
28
- /**
29
- * Get embedding function - delegates to SingletonModelManager
30
- */
31
- getEmbeddingFunction(): Promise<EmbeddingFunction>;
32
- /**
33
- * Check if model is ready - delegates to SingletonModelManager
34
- */
35
- isModelReady(): boolean;
36
- /**
37
- * Force model reload - not supported with SingletonModelManager
38
- */
39
- reloadModel(): Promise<void>;
40
- /**
41
- * Get model status - delegates to SingletonModelManager
42
- */
43
- getModelStatus(): {
44
- loaded: boolean;
45
- ready: boolean;
46
- modelType: string;
47
- };
48
- }
49
- export declare const hybridModelManager: HybridModelManager;
50
- /**
51
- * Get the hybrid singleton embedding function - Now delegates to SingletonModelManager
52
- * Maintained for backward compatibility
53
- */
54
- export declare function getHybridEmbeddingFunction(): Promise<EmbeddingFunction>;
55
- /**
56
- * Hybrid embedding function - Now delegates to SingletonModelManager
57
- * Maintained for backward compatibility
58
- */
59
- export declare const hybridEmbeddingFunction: EmbeddingFunction;
60
- /**
61
- * Preload model for tests or production - Now delegates to SingletonModelManager
62
- */
63
- export declare function preloadHybridModel(): Promise<void>;
64
- export {};
@@ -1,95 +0,0 @@
1
- /**
2
- * Hybrid Model Manager - BEST OF BOTH WORLDS
3
- *
4
- * NOW A WRAPPER AROUND SingletonModelManager
5
- * Maintained for backward compatibility
6
- *
7
- * Previously combined:
8
- * 1. Multi-source downloading strategy (GitHub → CDN → Hugging Face)
9
- * 2. Singleton pattern preventing multiple ONNX model loads
10
- * 3. Environment-specific optimizations
11
- * 4. Graceful fallbacks and error handling
12
- *
13
- * Now delegates all operations to SingletonModelManager for true unification
14
- */
15
- import { singletonModelManager, getUnifiedEmbeddingFunction } from '../embeddings/SingletonModelManager.js';
16
- /**
17
- * HybridModelManager - Now a wrapper around SingletonModelManager
18
- * Maintained for backward compatibility
19
- */
20
- class HybridModelManager {
21
- constructor() {
22
- console.log('🔄 HybridModelManager now delegates to SingletonModelManager');
23
- }
24
- static getInstance() {
25
- if (!HybridModelManager.instance) {
26
- HybridModelManager.instance = new HybridModelManager();
27
- }
28
- return HybridModelManager.instance;
29
- }
30
- /**
31
- * Get the primary embedding model - delegates to SingletonModelManager
32
- */
33
- async getPrimaryModel() {
34
- // Delegate to SingletonModelManager
35
- return await singletonModelManager.getModel();
36
- }
37
- /**
38
- * Get embedding function - delegates to SingletonModelManager
39
- */
40
- async getEmbeddingFunction() {
41
- return await getUnifiedEmbeddingFunction();
42
- }
43
- /**
44
- * Check if model is ready - delegates to SingletonModelManager
45
- */
46
- isModelReady() {
47
- return singletonModelManager.isInitialized();
48
- }
49
- /**
50
- * Force model reload - not supported with SingletonModelManager
51
- */
52
- async reloadModel() {
53
- console.warn('⚠️ Model reload not supported with SingletonModelManager');
54
- console.log('ℹ️ Singleton model persists for consistency');
55
- // Just ensure model is initialized
56
- await this.getPrimaryModel();
57
- }
58
- /**
59
- * Get model status - delegates to SingletonModelManager
60
- */
61
- getModelStatus() {
62
- const isReady = singletonModelManager.isInitialized();
63
- return {
64
- loaded: isReady,
65
- ready: isReady,
66
- modelType: 'SingletonModelManager (Unified model instance)'
67
- };
68
- }
69
- }
70
- HybridModelManager.instance = null;
71
- // Export singleton instance
72
- export const hybridModelManager = HybridModelManager.getInstance();
73
- /**
74
- * Get the hybrid singleton embedding function - Now delegates to SingletonModelManager
75
- * Maintained for backward compatibility
76
- */
77
- export async function getHybridEmbeddingFunction() {
78
- return await getUnifiedEmbeddingFunction();
79
- }
80
- /**
81
- * Hybrid embedding function - Now delegates to SingletonModelManager
82
- * Maintained for backward compatibility
83
- */
84
- export const hybridEmbeddingFunction = async (data) => {
85
- return await singletonModelManager.embed(data);
86
- };
87
- /**
88
- * Preload model for tests or production - Now delegates to SingletonModelManager
89
- */
90
- export async function preloadHybridModel() {
91
- console.log('🚀 Preloading model via SingletonModelManager...');
92
- await singletonModelManager.getModel();
93
- console.log('✅ Singleton model preloaded and ready!');
94
- }
95
- //# sourceMappingURL=hybridModelManager.js.map
@@ -1,28 +0,0 @@
1
- /**
2
- * Utility functions for retrieving statistics from Brainy
3
- */
4
- import { Brainy } from '../brainy.js';
5
- /**
6
- * Get statistics about the current state of a Brainy instance
7
- * This function provides access to statistics at the root level of the library
8
- *
9
- * @param instance A Brainy instance to get statistics from
10
- * @param options Additional options for retrieving statistics
11
- * @returns Object containing counts of nouns, verbs, metadata entries, and HNSW index size
12
- * @throws Error if the instance is not provided or if statistics retrieval fails
13
- */
14
- export declare function getStatistics(instance: Brainy, options?: {
15
- service?: string | string[];
16
- }): Promise<{
17
- nounCount: number;
18
- verbCount: number;
19
- metadataCount: number;
20
- hnswIndexSize: number;
21
- serviceBreakdown?: {
22
- [service: string]: {
23
- nounCount: number;
24
- verbCount: number;
25
- metadataCount: number;
26
- };
27
- };
28
- }>;
@@ -1,25 +0,0 @@
1
- /**
2
- * Utility functions for retrieving statistics from Brainy
3
- */
4
- /**
5
- * Get statistics about the current state of a Brainy instance
6
- * This function provides access to statistics at the root level of the library
7
- *
8
- * @param instance A Brainy instance to get statistics from
9
- * @param options Additional options for retrieving statistics
10
- * @returns Object containing counts of nouns, verbs, metadata entries, and HNSW index size
11
- * @throws Error if the instance is not provided or if statistics retrieval fails
12
- */
13
- export async function getStatistics(instance, options = {}) {
14
- if (!instance) {
15
- throw new Error('Brainy instance must be provided to getStatistics');
16
- }
17
- try {
18
- return await instance.getStatistics(options);
19
- }
20
- catch (error) {
21
- console.error('Failed to get statistics:', error);
22
- throw new Error(`Failed to get statistics: ${error}`);
23
- }
24
- }
25
- //# sourceMappingURL=statistics.js.map