@soulcraft/brainy 3.0.0 → 3.1.0
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/CHANGELOG.md +53 -3
- package/README.md +427 -111
- package/bin/brainy.js +340 -62
- package/dist/api/ConfigAPI.d.ts +67 -0
- package/dist/api/ConfigAPI.js +166 -0
- package/dist/api/DataAPI.d.ts +123 -0
- package/dist/api/DataAPI.js +391 -0
- package/dist/api/SecurityAPI.d.ts +50 -0
- package/dist/api/SecurityAPI.js +139 -0
- package/dist/api/UniversalImportAPI.d.ts +134 -0
- package/dist/api/UniversalImportAPI.js +615 -0
- package/dist/augmentationManager.js +12 -7
- package/dist/augmentationPipeline.d.ts +0 -61
- package/dist/augmentationPipeline.js +0 -87
- package/dist/augmentationRegistry.d.ts +1 -1
- package/dist/augmentationRegistry.js +1 -1
- package/dist/augmentations/apiServerAugmentation.d.ts +27 -1
- package/dist/augmentations/apiServerAugmentation.js +290 -9
- package/dist/augmentations/auditLogAugmentation.d.ts +109 -0
- package/dist/augmentations/auditLogAugmentation.js +358 -0
- package/dist/augmentations/batchProcessingAugmentation.d.ts +3 -2
- package/dist/augmentations/batchProcessingAugmentation.js +123 -22
- package/dist/augmentations/brainyAugmentation.d.ts +142 -8
- package/dist/augmentations/brainyAugmentation.js +179 -2
- package/dist/augmentations/cacheAugmentation.d.ts +8 -5
- package/dist/augmentations/cacheAugmentation.js +116 -17
- package/dist/augmentations/conduitAugmentations.d.ts +2 -2
- package/dist/augmentations/conduitAugmentations.js +2 -2
- package/dist/augmentations/configResolver.d.ts +122 -0
- package/dist/augmentations/configResolver.js +440 -0
- package/dist/augmentations/connectionPoolAugmentation.d.ts +3 -1
- package/dist/augmentations/connectionPoolAugmentation.js +37 -12
- package/dist/augmentations/defaultAugmentations.d.ts +14 -10
- package/dist/augmentations/defaultAugmentations.js +16 -11
- package/dist/augmentations/discovery/catalogDiscovery.d.ts +142 -0
- package/dist/augmentations/discovery/catalogDiscovery.js +249 -0
- package/dist/augmentations/discovery/localDiscovery.d.ts +84 -0
- package/dist/augmentations/discovery/localDiscovery.js +246 -0
- package/dist/augmentations/discovery/runtimeLoader.d.ts +97 -0
- package/dist/augmentations/discovery/runtimeLoader.js +337 -0
- package/dist/augmentations/discovery.d.ts +152 -0
- package/dist/augmentations/discovery.js +441 -0
- package/dist/augmentations/display/cache.d.ts +130 -0
- package/dist/augmentations/display/cache.js +319 -0
- package/dist/augmentations/display/fieldPatterns.d.ts +52 -0
- package/dist/augmentations/display/fieldPatterns.js +393 -0
- package/dist/augmentations/display/iconMappings.d.ts +57 -0
- package/dist/augmentations/display/iconMappings.js +68 -0
- package/dist/augmentations/display/intelligentComputation.d.ts +109 -0
- package/dist/augmentations/display/intelligentComputation.js +462 -0
- package/dist/augmentations/display/types.d.ts +203 -0
- package/dist/augmentations/display/types.js +7 -0
- package/dist/augmentations/entityRegistryAugmentation.d.ts +3 -1
- package/dist/augmentations/entityRegistryAugmentation.js +5 -1
- package/dist/augmentations/indexAugmentation.d.ts +5 -3
- package/dist/augmentations/indexAugmentation.js +5 -2
- package/dist/augmentations/intelligentVerbScoringAugmentation.d.ts +24 -7
- package/dist/augmentations/intelligentVerbScoringAugmentation.js +111 -27
- package/dist/augmentations/manifest.d.ts +176 -0
- package/dist/augmentations/manifest.js +8 -0
- package/dist/augmentations/marketplace/AugmentationMarketplace.d.ts +168 -0
- package/dist/augmentations/marketplace/AugmentationMarketplace.js +329 -0
- package/dist/augmentations/marketplace/cli.d.ts +47 -0
- package/dist/augmentations/marketplace/cli.js +265 -0
- package/dist/augmentations/metricsAugmentation.d.ts +3 -3
- package/dist/augmentations/metricsAugmentation.js +2 -2
- package/dist/augmentations/monitoringAugmentation.d.ts +3 -3
- package/dist/augmentations/monitoringAugmentation.js +2 -2
- package/dist/augmentations/neuralImport.d.ts +1 -1
- package/dist/augmentations/neuralImport.js +4 -4
- package/dist/augmentations/rateLimitAugmentation.d.ts +82 -0
- package/dist/augmentations/rateLimitAugmentation.js +321 -0
- package/dist/augmentations/requestDeduplicatorAugmentation.d.ts +2 -2
- package/dist/augmentations/requestDeduplicatorAugmentation.js +1 -1
- package/dist/augmentations/storageAugmentation.d.ts +1 -1
- package/dist/augmentations/storageAugmentation.js +2 -2
- package/dist/augmentations/storageAugmentations.d.ts +37 -8
- package/dist/augmentations/storageAugmentations.js +204 -15
- package/dist/augmentations/synapseAugmentation.d.ts +1 -1
- package/dist/augmentations/synapseAugmentation.js +35 -16
- package/dist/augmentations/typeMatching/brainyTypes.d.ts +83 -0
- package/dist/augmentations/typeMatching/brainyTypes.js +425 -0
- package/dist/augmentations/typeMatching/intelligentTypeMatcher.d.ts +39 -59
- package/dist/augmentations/typeMatching/intelligentTypeMatcher.js +103 -389
- package/dist/augmentations/universalDisplayAugmentation.d.ts +191 -0
- package/dist/augmentations/universalDisplayAugmentation.js +371 -0
- package/dist/brainy-unified.d.ts +106 -0
- package/dist/brainy-unified.js +327 -0
- package/dist/brainy.d.ts +277 -0
- package/dist/brainy.js +1241 -0
- package/dist/brainyData.d.ts +56 -111
- package/dist/brainyData.js +912 -756
- package/dist/brainyDataV3.d.ts +186 -0
- package/dist/brainyDataV3.js +337 -0
- package/dist/config/distributedPresets-new.d.ts +118 -0
- package/dist/config/distributedPresets-new.js +318 -0
- package/dist/config/distributedPresets.d.ts +118 -0
- package/dist/config/distributedPresets.js +318 -0
- package/dist/config/extensibleConfig.d.ts +99 -0
- package/dist/config/extensibleConfig.js +268 -0
- package/dist/config/index.d.ts +17 -0
- package/dist/config/index.js +35 -0
- package/dist/config/modelAutoConfig.d.ts +32 -0
- package/dist/config/modelAutoConfig.js +139 -0
- package/dist/config/modelPrecisionManager.d.ts +42 -0
- package/dist/config/modelPrecisionManager.js +98 -0
- package/dist/config/sharedConfigManager.d.ts +67 -0
- package/dist/config/sharedConfigManager.js +215 -0
- package/dist/config/storageAutoConfig.d.ts +41 -0
- package/dist/config/storageAutoConfig.js +328 -0
- package/dist/config/zeroConfig.d.ts +68 -0
- package/dist/config/zeroConfig.js +301 -0
- package/dist/cortex/backupRestore.d.ts +2 -2
- package/dist/cortex/backupRestore.js +85 -27
- package/dist/cortex/healthCheck.d.ts +2 -2
- package/dist/cortex/neuralImport.d.ts +2 -2
- package/dist/cortex/neuralImport.js +18 -13
- package/dist/cortex/performanceMonitor.d.ts +2 -2
- package/dist/critical/model-guardian.d.ts +4 -0
- package/dist/critical/model-guardian.js +31 -11
- package/dist/demo.d.ts +4 -4
- package/dist/demo.js +7 -7
- package/dist/distributed/cacheSync.d.ts +112 -0
- package/dist/distributed/cacheSync.js +265 -0
- package/dist/distributed/coordinator.d.ts +193 -0
- package/dist/distributed/coordinator.js +548 -0
- package/dist/distributed/httpTransport.d.ts +120 -0
- package/dist/distributed/httpTransport.js +446 -0
- package/dist/distributed/index.d.ts +8 -0
- package/dist/distributed/index.js +5 -0
- package/dist/distributed/networkTransport.d.ts +132 -0
- package/dist/distributed/networkTransport.js +633 -0
- package/dist/distributed/queryPlanner.d.ts +104 -0
- package/dist/distributed/queryPlanner.js +327 -0
- package/dist/distributed/readWriteSeparation.d.ts +134 -0
- package/dist/distributed/readWriteSeparation.js +350 -0
- package/dist/distributed/shardManager.d.ts +114 -0
- package/dist/distributed/shardManager.js +357 -0
- package/dist/distributed/shardMigration.d.ts +110 -0
- package/dist/distributed/shardMigration.js +289 -0
- package/dist/distributed/storageDiscovery.d.ts +160 -0
- package/dist/distributed/storageDiscovery.js +551 -0
- package/dist/embeddings/CachedEmbeddings.d.ts +40 -0
- package/dist/embeddings/CachedEmbeddings.js +146 -0
- package/dist/embeddings/EmbeddingManager.d.ts +102 -0
- package/dist/embeddings/EmbeddingManager.js +291 -0
- package/dist/embeddings/SingletonModelManager.d.ts +95 -0
- package/dist/embeddings/SingletonModelManager.js +220 -0
- package/dist/embeddings/index.d.ts +12 -0
- package/dist/embeddings/index.js +16 -0
- package/dist/embeddings/lightweight-embedder.d.ts +0 -1
- package/dist/embeddings/lightweight-embedder.js +4 -12
- package/dist/embeddings/model-manager.d.ts +11 -0
- package/dist/embeddings/model-manager.js +43 -7
- package/dist/embeddings/universal-memory-manager.d.ts +1 -1
- package/dist/embeddings/universal-memory-manager.js +27 -67
- package/dist/embeddings/worker-embedding.js +4 -8
- package/dist/errors/brainyError.d.ts +5 -1
- package/dist/errors/brainyError.js +12 -0
- package/dist/examples/basicUsage.js +7 -4
- package/dist/graph/graphAdjacencyIndex.d.ts +96 -0
- package/dist/graph/graphAdjacencyIndex.js +288 -0
- package/dist/graph/pathfinding.js +4 -2
- package/dist/hnsw/scaledHNSWSystem.js +11 -2
- package/dist/importManager.js +8 -5
- package/dist/index.d.ts +17 -22
- package/dist/index.js +37 -23
- package/dist/mcp/brainyMCPAdapter.d.ts +4 -4
- package/dist/mcp/brainyMCPAdapter.js +5 -5
- package/dist/mcp/brainyMCPService.d.ts +3 -3
- package/dist/mcp/brainyMCPService.js +3 -11
- package/dist/mcp/mcpAugmentationToolset.js +20 -30
- package/dist/neural/embeddedPatterns.d.ts +1 -1
- package/dist/neural/embeddedPatterns.js +2 -2
- package/dist/neural/entityExtractor.d.ts +65 -0
- package/dist/neural/entityExtractor.js +316 -0
- package/dist/neural/improvedNeuralAPI.d.ts +357 -0
- package/dist/neural/improvedNeuralAPI.js +2628 -0
- package/dist/neural/naturalLanguageProcessor.d.ts +155 -10
- package/dist/neural/naturalLanguageProcessor.js +941 -66
- package/dist/neural/naturalLanguageProcessorStatic.d.ts +2 -2
- package/dist/neural/naturalLanguageProcessorStatic.js +3 -3
- package/dist/neural/neuralAPI.js +8 -2
- package/dist/neural/patternLibrary.d.ts +57 -3
- package/dist/neural/patternLibrary.js +348 -13
- package/dist/neural/staticPatternMatcher.d.ts +2 -2
- package/dist/neural/staticPatternMatcher.js +2 -2
- package/dist/neural/types.d.ts +287 -0
- package/dist/neural/types.js +24 -0
- package/dist/shared/default-augmentations.d.ts +3 -3
- package/dist/shared/default-augmentations.js +5 -5
- package/dist/storage/adapters/baseStorageAdapter.d.ts +42 -0
- package/dist/storage/adapters/fileSystemStorage.d.ts +26 -2
- package/dist/storage/adapters/fileSystemStorage.js +218 -15
- package/dist/storage/adapters/memoryStorage.d.ts +4 -4
- package/dist/storage/adapters/memoryStorage.js +17 -12
- package/dist/storage/adapters/opfsStorage.d.ts +2 -2
- package/dist/storage/adapters/opfsStorage.js +2 -2
- package/dist/storage/adapters/s3CompatibleStorage.d.ts +2 -2
- package/dist/storage/adapters/s3CompatibleStorage.js +2 -2
- package/dist/storage/backwardCompatibility.d.ts +10 -78
- package/dist/storage/backwardCompatibility.js +17 -132
- package/dist/storage/baseStorage.d.ts +18 -2
- package/dist/storage/baseStorage.js +74 -3
- package/dist/storage/cacheManager.js +2 -2
- package/dist/storage/readOnlyOptimizations.js +8 -3
- package/dist/streaming/pipeline.d.ts +154 -0
- package/dist/streaming/pipeline.js +551 -0
- package/dist/triple/TripleIntelligence.d.ts +25 -110
- package/dist/triple/TripleIntelligence.js +4 -574
- package/dist/triple/TripleIntelligenceSystem.d.ts +159 -0
- package/dist/triple/TripleIntelligenceSystem.js +519 -0
- package/dist/types/apiTypes.d.ts +278 -0
- package/dist/types/apiTypes.js +33 -0
- package/dist/types/brainy.types.d.ts +308 -0
- package/dist/types/brainy.types.js +8 -0
- package/dist/types/brainyDataInterface.d.ts +5 -8
- package/dist/types/brainyDataInterface.js +2 -2
- package/dist/types/graphTypes.js +2 -2
- package/dist/universal/crypto.d.ts +11 -1
- package/dist/universal/crypto.js +24 -93
- package/dist/universal/events.d.ts +3 -2
- package/dist/universal/events.js +6 -75
- package/dist/universal/fs.d.ts +2 -3
- package/dist/universal/fs.js +5 -211
- package/dist/universal/path.d.ts +3 -2
- package/dist/universal/path.js +22 -78
- package/dist/universal/uuid.d.ts +1 -1
- package/dist/universal/uuid.js +1 -1
- package/dist/utils/brainyTypes.d.ts +217 -0
- package/dist/utils/brainyTypes.js +261 -0
- package/dist/utils/cacheAutoConfig.d.ts +3 -3
- package/dist/utils/embedding.d.ts +9 -4
- package/dist/utils/embedding.js +89 -26
- package/dist/utils/enhancedLogger.d.ts +104 -0
- package/dist/utils/enhancedLogger.js +232 -0
- package/dist/utils/hybridModelManager.d.ts +19 -28
- package/dist/utils/hybridModelManager.js +36 -200
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/index.js +1 -1
- package/dist/utils/intelligentTypeMapper.d.ts +60 -0
- package/dist/utils/intelligentTypeMapper.js +349 -0
- package/dist/utils/metadataIndex.d.ts +118 -1
- package/dist/utils/metadataIndex.js +539 -16
- package/dist/utils/nodeVersionCheck.d.ts +24 -0
- package/dist/utils/nodeVersionCheck.js +65 -0
- package/dist/utils/paramValidation.d.ts +39 -0
- package/dist/utils/paramValidation.js +192 -0
- package/dist/utils/rateLimiter.d.ts +160 -0
- package/dist/utils/rateLimiter.js +271 -0
- package/dist/utils/statistics.d.ts +4 -4
- package/dist/utils/statistics.js +3 -3
- package/dist/utils/structuredLogger.d.ts +146 -0
- package/dist/utils/structuredLogger.js +394 -0
- package/dist/utils/textEncoding.js +2 -1
- package/dist/utils/typeValidation.d.ts +59 -0
- package/dist/utils/typeValidation.js +374 -0
- package/dist/utils/version.js +19 -3
- package/package.json +15 -17
- package/scripts/download-models.cjs +94 -20
- package/dist/augmentations/walAugmentation.d.ts +0 -109
- package/dist/augmentations/walAugmentation.js +0 -516
- package/dist/browserFramework.d.ts +0 -15
- package/dist/browserFramework.js +0 -31
- package/dist/browserFramework.minimal.d.ts +0 -14
- package/dist/browserFramework.minimal.js +0 -31
- package/dist/chat/BrainyChat.d.ts +0 -121
- package/dist/chat/BrainyChat.js +0 -396
- package/dist/chat/ChatCLI.d.ts +0 -61
- package/dist/chat/ChatCLI.js +0 -351
|
@@ -26,7 +26,7 @@ export declare class NaturalLanguageProcessor {
|
|
|
26
26
|
/**
|
|
27
27
|
* Process natural language query into structured Triple Intelligence query
|
|
28
28
|
* @param naturalQuery The natural language query string
|
|
29
|
-
* @param queryEmbedding Pre-computed embedding from
|
|
29
|
+
* @param queryEmbedding Pre-computed embedding from Brainy (passed in to avoid circular dependency)
|
|
30
30
|
*/
|
|
31
31
|
processNaturalQuery(naturalQuery: string, queryEmbedding?: Vector): Promise<TripleQuery>;
|
|
32
32
|
/**
|
|
@@ -46,7 +46,7 @@ export declare class NaturalLanguageProcessor {
|
|
|
46
46
|
*/
|
|
47
47
|
private buildFieldConstraints;
|
|
48
48
|
/**
|
|
49
|
-
* Find similar queries from history (without using
|
|
49
|
+
* Find similar queries from history (without using Brainy)
|
|
50
50
|
*/
|
|
51
51
|
private findSimilarQueries;
|
|
52
52
|
/**
|
|
@@ -20,7 +20,7 @@ export class NaturalLanguageProcessor {
|
|
|
20
20
|
/**
|
|
21
21
|
* Process natural language query into structured Triple Intelligence query
|
|
22
22
|
* @param naturalQuery The natural language query string
|
|
23
|
-
* @param queryEmbedding Pre-computed embedding from
|
|
23
|
+
* @param queryEmbedding Pre-computed embedding from Brainy (passed in to avoid circular dependency)
|
|
24
24
|
*/
|
|
25
25
|
async processNaturalQuery(naturalQuery, queryEmbedding) {
|
|
26
26
|
// Use static pattern matcher (no async, no memory allocation!)
|
|
@@ -33,7 +33,7 @@ export class NaturalLanguageProcessor {
|
|
|
33
33
|
structuredQuery.where = this.buildFieldConstraints(intent.extractedTerms.fields);
|
|
34
34
|
}
|
|
35
35
|
}
|
|
36
|
-
// Track for learning (but don't create new
|
|
36
|
+
// Track for learning (but don't create new Brainy!)
|
|
37
37
|
this.queryHistory.push({
|
|
38
38
|
query: naturalQuery,
|
|
39
39
|
result: structuredQuery,
|
|
@@ -118,7 +118,7 @@ export class NaturalLanguageProcessor {
|
|
|
118
118
|
return constraints;
|
|
119
119
|
}
|
|
120
120
|
/**
|
|
121
|
-
* Find similar queries from history (without using
|
|
121
|
+
* Find similar queries from history (without using Brainy)
|
|
122
122
|
*/
|
|
123
123
|
findSimilarQueries(embedding) {
|
|
124
124
|
// Simple similarity check against recent history
|
package/dist/neural/neuralAPI.js
CHANGED
|
@@ -603,10 +603,16 @@ export class NeuralAPI {
|
|
|
603
603
|
return { width: 100, height: 100 };
|
|
604
604
|
}
|
|
605
605
|
async getViewportLOD(viewport, lod) {
|
|
606
|
-
|
|
606
|
+
// LOD visualization is an optional advanced feature
|
|
607
|
+
// Return default view without LOD optimization
|
|
608
|
+
console.warn('Viewport LOD optimization not available. Using standard view.');
|
|
609
|
+
return { nodes: [], edges: [], optimized: false };
|
|
607
610
|
}
|
|
608
611
|
async getGlobalLOD(lod) {
|
|
609
|
-
|
|
612
|
+
// LOD visualization is an optional advanced feature
|
|
613
|
+
// Return default view without LOD optimization
|
|
614
|
+
console.warn('Global LOD optimization not available. Using standard view.');
|
|
615
|
+
return { nodes: [], edges: [], optimized: false };
|
|
610
616
|
}
|
|
611
617
|
}
|
|
612
618
|
//# sourceMappingURL=neuralAPI.js.map
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* - Progressive learning from usage
|
|
9
9
|
*/
|
|
10
10
|
import { Vector } from '../coreTypes.js';
|
|
11
|
-
import {
|
|
11
|
+
import { Brainy } from '../brainy.js';
|
|
12
12
|
export interface Pattern {
|
|
13
13
|
id: string;
|
|
14
14
|
category: string;
|
|
@@ -19,10 +19,20 @@ export interface Pattern {
|
|
|
19
19
|
embedding?: Vector;
|
|
20
20
|
domain?: string;
|
|
21
21
|
frequency?: number | string;
|
|
22
|
+
slots?: SlotDefinition[];
|
|
23
|
+
}
|
|
24
|
+
export interface SlotDefinition {
|
|
25
|
+
name: string;
|
|
26
|
+
type: 'text' | 'number' | 'date' | 'entity' | 'location' | 'person' | 'any';
|
|
27
|
+
required?: boolean;
|
|
28
|
+
default?: any;
|
|
29
|
+
pattern?: string;
|
|
30
|
+
transform?: (value: string) => any;
|
|
22
31
|
}
|
|
23
32
|
export interface SlotExtraction {
|
|
24
33
|
slots: Record<string, any>;
|
|
25
34
|
confidence: number;
|
|
35
|
+
errors?: string[];
|
|
26
36
|
}
|
|
27
37
|
export declare class PatternLibrary {
|
|
28
38
|
private patterns;
|
|
@@ -30,7 +40,7 @@ export declare class PatternLibrary {
|
|
|
30
40
|
private brain;
|
|
31
41
|
private embeddingCache;
|
|
32
42
|
private successMetrics;
|
|
33
|
-
constructor(brain:
|
|
43
|
+
constructor(brain: Brainy);
|
|
34
44
|
/**
|
|
35
45
|
* Initialize pattern library with pre-computed embeddings
|
|
36
46
|
*/
|
|
@@ -51,9 +61,53 @@ export declare class PatternLibrary {
|
|
|
51
61
|
similarity: number;
|
|
52
62
|
}>>;
|
|
53
63
|
/**
|
|
54
|
-
* Extract slots from query based on pattern
|
|
64
|
+
* Extract slots from query based on pattern with enhanced fuzzy matching
|
|
55
65
|
*/
|
|
56
66
|
extractSlots(query: string, pattern: Pattern): SlotExtraction;
|
|
67
|
+
/**
|
|
68
|
+
* Extract named slots with type validation
|
|
69
|
+
*/
|
|
70
|
+
private extractNamedSlots;
|
|
71
|
+
/**
|
|
72
|
+
* Fuzzy extraction using Levenshtein distance
|
|
73
|
+
*/
|
|
74
|
+
private fuzzyExtractSlots;
|
|
75
|
+
/**
|
|
76
|
+
* Fuzzy extraction for named slots
|
|
77
|
+
*/
|
|
78
|
+
private fuzzyExtractNamedSlots;
|
|
79
|
+
/**
|
|
80
|
+
* Find slot value in tokens based on type
|
|
81
|
+
*/
|
|
82
|
+
private findSlotValueInTokens;
|
|
83
|
+
/**
|
|
84
|
+
* Get default regex pattern for slot type
|
|
85
|
+
*/
|
|
86
|
+
private getDefaultPatternForType;
|
|
87
|
+
/**
|
|
88
|
+
* Transform value based on type
|
|
89
|
+
*/
|
|
90
|
+
private transformByType;
|
|
91
|
+
/**
|
|
92
|
+
* Validate slot value against definition
|
|
93
|
+
*/
|
|
94
|
+
private validateSlotValue;
|
|
95
|
+
/**
|
|
96
|
+
* Calculate Levenshtein distance between two strings
|
|
97
|
+
*/
|
|
98
|
+
private levenshteinDistance;
|
|
99
|
+
/**
|
|
100
|
+
* Align two strings for slot extraction
|
|
101
|
+
*/
|
|
102
|
+
private alignStrings;
|
|
103
|
+
/**
|
|
104
|
+
* Find best token match using fuzzy comparison
|
|
105
|
+
*/
|
|
106
|
+
private findBestTokenMatch;
|
|
107
|
+
/**
|
|
108
|
+
* Extract slots from string alignment
|
|
109
|
+
*/
|
|
110
|
+
private extractSlotsFromAlignment;
|
|
57
111
|
/**
|
|
58
112
|
* Fill template with extracted slots
|
|
59
113
|
*/
|
|
@@ -69,6 +69,7 @@ export class PatternLibrary {
|
|
|
69
69
|
if (this.embeddingCache.has(text)) {
|
|
70
70
|
return this.embeddingCache.get(text);
|
|
71
71
|
}
|
|
72
|
+
// Use brain's embed method directly to avoid recursion
|
|
72
73
|
const embedding = await this.brain.embed(text);
|
|
73
74
|
this.embeddingCache.set(text, embedding);
|
|
74
75
|
return embedding;
|
|
@@ -95,11 +96,16 @@ export class PatternLibrary {
|
|
|
95
96
|
return matches.slice(0, k);
|
|
96
97
|
}
|
|
97
98
|
/**
|
|
98
|
-
* Extract slots from query based on pattern
|
|
99
|
+
* Extract slots from query based on pattern with enhanced fuzzy matching
|
|
99
100
|
*/
|
|
100
101
|
extractSlots(query, pattern) {
|
|
101
102
|
const slots = {};
|
|
103
|
+
const errors = [];
|
|
102
104
|
let confidence = pattern.confidence;
|
|
105
|
+
// If pattern has named slot definitions, use them
|
|
106
|
+
if (pattern.slots && pattern.slots.length > 0) {
|
|
107
|
+
return this.extractNamedSlots(query, pattern);
|
|
108
|
+
}
|
|
103
109
|
// Try regex extraction first
|
|
104
110
|
const regex = new RegExp(pattern.pattern, 'i');
|
|
105
111
|
const match = query.match(regex);
|
|
@@ -112,21 +118,350 @@ export class PatternLibrary {
|
|
|
112
118
|
confidence = Math.min(confidence * 1.2, 1.0);
|
|
113
119
|
}
|
|
114
120
|
else {
|
|
115
|
-
//
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
slots[exampleTokens[i]] = tokens[i];
|
|
122
|
-
}
|
|
121
|
+
// Enhanced fuzzy matching with Levenshtein distance
|
|
122
|
+
const fuzzyResult = this.fuzzyExtractSlots(query, pattern);
|
|
123
|
+
Object.assign(slots, fuzzyResult.slots);
|
|
124
|
+
confidence = fuzzyResult.confidence;
|
|
125
|
+
if (fuzzyResult.errors) {
|
|
126
|
+
errors.push(...fuzzyResult.errors);
|
|
123
127
|
}
|
|
124
|
-
// Lower confidence for fuzzy matching
|
|
125
|
-
confidence *= 0.7;
|
|
126
128
|
}
|
|
127
129
|
// Post-process slots
|
|
128
130
|
this.postProcessSlots(slots, pattern);
|
|
129
|
-
return { slots, confidence };
|
|
131
|
+
return { slots, confidence, errors: errors.length > 0 ? errors : undefined };
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Extract named slots with type validation
|
|
135
|
+
*/
|
|
136
|
+
extractNamedSlots(query, pattern) {
|
|
137
|
+
const slots = {};
|
|
138
|
+
const errors = [];
|
|
139
|
+
let confidence = pattern.confidence;
|
|
140
|
+
if (!pattern.slots) {
|
|
141
|
+
return { slots, confidence };
|
|
142
|
+
}
|
|
143
|
+
// Create a flexible regex from pattern
|
|
144
|
+
let flexiblePattern = pattern.pattern;
|
|
145
|
+
const slotPositions = new Map();
|
|
146
|
+
// Replace named slots in pattern with capture groups
|
|
147
|
+
pattern.slots.forEach((slot, index) => {
|
|
148
|
+
const slotPattern = slot.pattern || this.getDefaultPatternForType(slot.type);
|
|
149
|
+
flexiblePattern = flexiblePattern.replace(new RegExp(`\\{${slot.name}\\}`, 'g'), `(${slotPattern})`);
|
|
150
|
+
slotPositions.set(index + 1, slot);
|
|
151
|
+
});
|
|
152
|
+
const regex = new RegExp(flexiblePattern, 'i');
|
|
153
|
+
const match = query.match(regex);
|
|
154
|
+
if (match) {
|
|
155
|
+
// Extract and validate each slot
|
|
156
|
+
slotPositions.forEach((slotDef, position) => {
|
|
157
|
+
const value = match[position];
|
|
158
|
+
if (value) {
|
|
159
|
+
// Apply transformation if defined
|
|
160
|
+
const transformedValue = slotDef.transform
|
|
161
|
+
? slotDef.transform(value)
|
|
162
|
+
: this.transformByType(value, slotDef.type);
|
|
163
|
+
// Validate the value
|
|
164
|
+
if (this.validateSlotValue(transformedValue, slotDef)) {
|
|
165
|
+
slots[slotDef.name] = transformedValue;
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
errors.push(`Invalid value for slot '${slotDef.name}': expected ${slotDef.type}, got '${value}'`);
|
|
169
|
+
confidence *= 0.8;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
else if (slotDef.required) {
|
|
173
|
+
if (slotDef.default !== undefined) {
|
|
174
|
+
slots[slotDef.name] = slotDef.default;
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
errors.push(`Required slot '${slotDef.name}' not found`);
|
|
178
|
+
confidence *= 0.5;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
// Try fuzzy matching for named slots
|
|
185
|
+
const fuzzyResult = this.fuzzyExtractNamedSlots(query, pattern);
|
|
186
|
+
Object.assign(slots, fuzzyResult.slots);
|
|
187
|
+
confidence = fuzzyResult.confidence;
|
|
188
|
+
if (fuzzyResult.errors) {
|
|
189
|
+
errors.push(...fuzzyResult.errors);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return { slots, confidence, errors: errors.length > 0 ? errors : undefined };
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Fuzzy extraction using Levenshtein distance
|
|
196
|
+
*/
|
|
197
|
+
fuzzyExtractSlots(query, pattern) {
|
|
198
|
+
const slots = {};
|
|
199
|
+
let bestConfidence = 0;
|
|
200
|
+
// Try each example with fuzzy matching
|
|
201
|
+
for (const example of pattern.examples) {
|
|
202
|
+
const distance = this.levenshteinDistance(query.toLowerCase(), example.toLowerCase());
|
|
203
|
+
const similarity = 1 - (distance / Math.max(query.length, example.length));
|
|
204
|
+
if (similarity > 0.6) { // 60% similarity threshold
|
|
205
|
+
// Extract slots using alignment
|
|
206
|
+
const aligned = this.alignStrings(query, example);
|
|
207
|
+
const extractedSlots = this.extractSlotsFromAlignment(aligned, pattern);
|
|
208
|
+
if (Object.keys(extractedSlots).length > 0) {
|
|
209
|
+
const currentConfidence = pattern.confidence * similarity;
|
|
210
|
+
if (currentConfidence > bestConfidence) {
|
|
211
|
+
Object.assign(slots, extractedSlots);
|
|
212
|
+
bestConfidence = currentConfidence;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return {
|
|
218
|
+
slots,
|
|
219
|
+
confidence: bestConfidence,
|
|
220
|
+
errors: bestConfidence < 0.5 ? ['Low confidence fuzzy match'] : undefined
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Fuzzy extraction for named slots
|
|
225
|
+
*/
|
|
226
|
+
fuzzyExtractNamedSlots(query, pattern) {
|
|
227
|
+
const slots = {};
|
|
228
|
+
const errors = [];
|
|
229
|
+
let confidence = pattern.confidence * 0.7; // Lower confidence for fuzzy
|
|
230
|
+
if (!pattern.slots) {
|
|
231
|
+
return { slots, confidence };
|
|
232
|
+
}
|
|
233
|
+
// Tokenize query for flexible matching
|
|
234
|
+
const tokens = this.tokenize(query);
|
|
235
|
+
pattern.slots.forEach(slotDef => {
|
|
236
|
+
const value = this.findSlotValueInTokens(tokens, slotDef);
|
|
237
|
+
if (value) {
|
|
238
|
+
const transformedValue = slotDef.transform
|
|
239
|
+
? slotDef.transform(value)
|
|
240
|
+
: this.transformByType(value, slotDef.type);
|
|
241
|
+
if (this.validateSlotValue(transformedValue, slotDef)) {
|
|
242
|
+
slots[slotDef.name] = transformedValue;
|
|
243
|
+
}
|
|
244
|
+
else {
|
|
245
|
+
errors.push(`Fuzzy match: uncertain value for '${slotDef.name}'`);
|
|
246
|
+
confidence *= 0.9;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
else if (slotDef.required && slotDef.default !== undefined) {
|
|
250
|
+
slots[slotDef.name] = slotDef.default;
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
return { slots, confidence, errors: errors.length > 0 ? errors : undefined };
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Find slot value in tokens based on type
|
|
257
|
+
*/
|
|
258
|
+
findSlotValueInTokens(tokens, slotDef) {
|
|
259
|
+
const joinedTokens = tokens.join(' ');
|
|
260
|
+
switch (slotDef.type) {
|
|
261
|
+
case 'number':
|
|
262
|
+
const numberMatch = joinedTokens.match(/\d+(\.\d+)?/);
|
|
263
|
+
return numberMatch ? numberMatch[0] : null;
|
|
264
|
+
case 'date':
|
|
265
|
+
const datePatterns = [
|
|
266
|
+
/\d{4}-\d{2}-\d{2}/,
|
|
267
|
+
/\d{1,2}\/\d{1,2}\/\d{2,4}/,
|
|
268
|
+
/(january|february|march|april|may|june|july|august|september|october|november|december)\s+\d{1,2},?\s+\d{4}/i,
|
|
269
|
+
/(today|tomorrow|yesterday)/i
|
|
270
|
+
];
|
|
271
|
+
for (const pattern of datePatterns) {
|
|
272
|
+
const match = joinedTokens.match(pattern);
|
|
273
|
+
if (match)
|
|
274
|
+
return match[0];
|
|
275
|
+
}
|
|
276
|
+
return null;
|
|
277
|
+
case 'person':
|
|
278
|
+
// Look for capitalized words (proper nouns)
|
|
279
|
+
const personMatch = joinedTokens.match(/\b[A-Z][a-z]+(\s+[A-Z][a-z]+)*\b/);
|
|
280
|
+
return personMatch ? personMatch[0] : null;
|
|
281
|
+
case 'location':
|
|
282
|
+
// Look for location indicators
|
|
283
|
+
const locationPatterns = [
|
|
284
|
+
/\b(in|at|from|to)\s+([A-Z][a-z]+(\s+[A-Z][a-z]+)*)\b/,
|
|
285
|
+
/\b[A-Z][a-z]+,\s+[A-Z]{2}\b/ // City, STATE format
|
|
286
|
+
];
|
|
287
|
+
for (const pattern of locationPatterns) {
|
|
288
|
+
const match = joinedTokens.match(pattern);
|
|
289
|
+
if (match)
|
|
290
|
+
return match[2] || match[0];
|
|
291
|
+
}
|
|
292
|
+
return null;
|
|
293
|
+
case 'entity':
|
|
294
|
+
case 'text':
|
|
295
|
+
case 'any':
|
|
296
|
+
default:
|
|
297
|
+
// Return first non-common word as potential value
|
|
298
|
+
const commonWords = new Set(['the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for']);
|
|
299
|
+
const significantToken = tokens.find(t => !commonWords.has(t.toLowerCase()));
|
|
300
|
+
return significantToken || null;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Get default regex pattern for slot type
|
|
305
|
+
*/
|
|
306
|
+
getDefaultPatternForType(type) {
|
|
307
|
+
switch (type) {
|
|
308
|
+
case 'number':
|
|
309
|
+
return '\\d+(?:\\.\\d+)?';
|
|
310
|
+
case 'date':
|
|
311
|
+
return '[\\w\\s,/-]+';
|
|
312
|
+
case 'person':
|
|
313
|
+
return '[A-Z][a-z]+(?:\\s+[A-Z][a-z]+)*';
|
|
314
|
+
case 'location':
|
|
315
|
+
return '[A-Z][a-z]+(?:[\\s,]+[A-Z][a-z]+)*';
|
|
316
|
+
case 'entity':
|
|
317
|
+
return '[\\w\\s-]+';
|
|
318
|
+
case 'text':
|
|
319
|
+
case 'any':
|
|
320
|
+
default:
|
|
321
|
+
return '.+';
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Transform value based on type
|
|
326
|
+
*/
|
|
327
|
+
transformByType(value, type) {
|
|
328
|
+
switch (type) {
|
|
329
|
+
case 'number':
|
|
330
|
+
const num = parseFloat(value);
|
|
331
|
+
return isNaN(num) ? value : num;
|
|
332
|
+
case 'date':
|
|
333
|
+
// Simple date parsing
|
|
334
|
+
if (value.toLowerCase() === 'today') {
|
|
335
|
+
return new Date().toISOString().split('T')[0];
|
|
336
|
+
}
|
|
337
|
+
else if (value.toLowerCase() === 'tomorrow') {
|
|
338
|
+
const tomorrow = new Date();
|
|
339
|
+
tomorrow.setDate(tomorrow.getDate() + 1);
|
|
340
|
+
return tomorrow.toISOString().split('T')[0];
|
|
341
|
+
}
|
|
342
|
+
else if (value.toLowerCase() === 'yesterday') {
|
|
343
|
+
const yesterday = new Date();
|
|
344
|
+
yesterday.setDate(yesterday.getDate() - 1);
|
|
345
|
+
return yesterday.toISOString().split('T')[0];
|
|
346
|
+
}
|
|
347
|
+
return value;
|
|
348
|
+
case 'person':
|
|
349
|
+
case 'location':
|
|
350
|
+
case 'entity':
|
|
351
|
+
// Capitalize properly
|
|
352
|
+
return value.split(' ')
|
|
353
|
+
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
|
|
354
|
+
.join(' ');
|
|
355
|
+
default:
|
|
356
|
+
return value.trim();
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Validate slot value against definition
|
|
361
|
+
*/
|
|
362
|
+
validateSlotValue(value, slotDef) {
|
|
363
|
+
if (value === null || value === undefined) {
|
|
364
|
+
return !slotDef.required;
|
|
365
|
+
}
|
|
366
|
+
switch (slotDef.type) {
|
|
367
|
+
case 'number':
|
|
368
|
+
return typeof value === 'number' && !isNaN(value);
|
|
369
|
+
case 'date':
|
|
370
|
+
return typeof value === 'string' && value.length > 0;
|
|
371
|
+
case 'text':
|
|
372
|
+
case 'person':
|
|
373
|
+
case 'location':
|
|
374
|
+
case 'entity':
|
|
375
|
+
return typeof value === 'string' && value.length > 0;
|
|
376
|
+
case 'any':
|
|
377
|
+
return true;
|
|
378
|
+
default:
|
|
379
|
+
return true;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Calculate Levenshtein distance between two strings
|
|
384
|
+
*/
|
|
385
|
+
levenshteinDistance(s1, s2) {
|
|
386
|
+
const len1 = s1.length;
|
|
387
|
+
const len2 = s2.length;
|
|
388
|
+
const matrix = [];
|
|
389
|
+
for (let i = 0; i <= len1; i++) {
|
|
390
|
+
matrix[i] = [i];
|
|
391
|
+
}
|
|
392
|
+
for (let j = 0; j <= len2; j++) {
|
|
393
|
+
matrix[0][j] = j;
|
|
394
|
+
}
|
|
395
|
+
for (let i = 1; i <= len1; i++) {
|
|
396
|
+
for (let j = 1; j <= len2; j++) {
|
|
397
|
+
const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;
|
|
398
|
+
matrix[i][j] = Math.min(matrix[i - 1][j] + 1, // deletion
|
|
399
|
+
matrix[i][j - 1] + 1, // insertion
|
|
400
|
+
matrix[i - 1][j - 1] + cost // substitution
|
|
401
|
+
);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
return matrix[len1][len2];
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Align two strings for slot extraction
|
|
408
|
+
*/
|
|
409
|
+
alignStrings(query, example) {
|
|
410
|
+
const queryTokens = this.tokenize(query);
|
|
411
|
+
const exampleTokens = this.tokenize(example);
|
|
412
|
+
const aligned = [];
|
|
413
|
+
let i = 0, j = 0;
|
|
414
|
+
while (i < queryTokens.length && j < exampleTokens.length) {
|
|
415
|
+
if (queryTokens[i] === exampleTokens[j]) {
|
|
416
|
+
aligned.push([queryTokens[i], exampleTokens[j]]);
|
|
417
|
+
i++;
|
|
418
|
+
j++;
|
|
419
|
+
}
|
|
420
|
+
else {
|
|
421
|
+
// Try to find best match
|
|
422
|
+
const bestMatch = this.findBestTokenMatch(queryTokens[i], exampleTokens.slice(j, j + 3));
|
|
423
|
+
if (bestMatch.index >= 0) {
|
|
424
|
+
j += bestMatch.index;
|
|
425
|
+
aligned.push([queryTokens[i], exampleTokens[j]]);
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
aligned.push([queryTokens[i], exampleTokens[j]]);
|
|
429
|
+
}
|
|
430
|
+
i++;
|
|
431
|
+
j++;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
return aligned;
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Find best token match using fuzzy comparison
|
|
438
|
+
*/
|
|
439
|
+
findBestTokenMatch(token, candidates) {
|
|
440
|
+
let bestIndex = -1;
|
|
441
|
+
let bestSimilarity = 0;
|
|
442
|
+
candidates.forEach((candidate, index) => {
|
|
443
|
+
const distance = this.levenshteinDistance(token.toLowerCase(), candidate.toLowerCase());
|
|
444
|
+
const similarity = 1 - (distance / Math.max(token.length, candidate.length));
|
|
445
|
+
if (similarity > bestSimilarity && similarity > 0.6) {
|
|
446
|
+
bestIndex = index;
|
|
447
|
+
bestSimilarity = similarity;
|
|
448
|
+
}
|
|
449
|
+
});
|
|
450
|
+
return { index: bestIndex, similarity: bestSimilarity };
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Extract slots from string alignment
|
|
454
|
+
*/
|
|
455
|
+
extractSlotsFromAlignment(aligned, _pattern) {
|
|
456
|
+
const slots = {};
|
|
457
|
+
let slotIndex = 1;
|
|
458
|
+
aligned.forEach(([queryToken, exampleToken]) => {
|
|
459
|
+
if (exampleToken.startsWith('$')) {
|
|
460
|
+
slots[`$${slotIndex}`] = queryToken;
|
|
461
|
+
slotIndex++;
|
|
462
|
+
}
|
|
463
|
+
});
|
|
464
|
+
return slots;
|
|
130
465
|
}
|
|
131
466
|
/**
|
|
132
467
|
* Fill template with extracted slots
|
|
@@ -246,7 +581,7 @@ export class PatternLibrary {
|
|
|
246
581
|
/**
|
|
247
582
|
* Helper: Post-process extracted slots
|
|
248
583
|
*/
|
|
249
|
-
postProcessSlots(slots,
|
|
584
|
+
postProcessSlots(slots, _pattern) {
|
|
250
585
|
// Convert string numbers to actual numbers
|
|
251
586
|
for (const [key, value] of Object.entries(slots)) {
|
|
252
587
|
if (typeof value === 'string') {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Static Pattern Matcher - NO runtime initialization, NO
|
|
2
|
+
* Static Pattern Matcher - NO runtime initialization, NO Brainy needed
|
|
3
3
|
*
|
|
4
4
|
* All patterns and embeddings are pre-computed at build time
|
|
5
5
|
* This is pure pattern matching with zero dependencies
|
|
@@ -24,7 +24,7 @@ export declare function matchPatternByRegex(query: string): {
|
|
|
24
24
|
} | null;
|
|
25
25
|
/**
|
|
26
26
|
* Convert natural language to structured query using STATIC patterns
|
|
27
|
-
* NO initialization needed, NO
|
|
27
|
+
* NO initialization needed, NO Brainy required
|
|
28
28
|
*/
|
|
29
29
|
export declare function patternMatchQuery(query: string, queryEmbedding?: Vector): TripleQuery;
|
|
30
30
|
export declare const PATTERN_STATS: {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Static Pattern Matcher - NO runtime initialization, NO
|
|
2
|
+
* Static Pattern Matcher - NO runtime initialization, NO Brainy needed
|
|
3
3
|
*
|
|
4
4
|
* All patterns and embeddings are pre-computed at build time
|
|
5
5
|
* This is pure pattern matching with zero dependencies
|
|
@@ -111,7 +111,7 @@ export function matchPatternByRegex(query) {
|
|
|
111
111
|
}
|
|
112
112
|
/**
|
|
113
113
|
* Convert natural language to structured query using STATIC patterns
|
|
114
|
-
* NO initialization needed, NO
|
|
114
|
+
* NO initialization needed, NO Brainy required
|
|
115
115
|
*/
|
|
116
116
|
export function patternMatchQuery(query, queryEmbedding) {
|
|
117
117
|
// ALWAYS use vector similarity when we have embeddings (which we always do!)
|