@retrivora-ai/rag-engine 2.4.2 → 2.4.5
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/{BatchProcessor-zbQMaZHm.d.mts → BatchProcessor-Csy_K1qQ.d.mts} +2 -0
- package/dist/{BatchProcessor-D42E706a.d.ts → BatchProcessor-Dg18zZGk.d.ts} +2 -0
- package/dist/handlers/index.js +31 -5
- package/dist/handlers/index.mjs +31 -5
- package/dist/index.d.mts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +41 -21
- package/dist/index.min.css +2 -0
- package/dist/index.mjs +41 -21
- package/dist/server.d.mts +2 -2
- package/dist/server.d.ts +2 -2
- package/dist/server.js +32 -5
- package/dist/server.mjs +32 -5
- package/package.json +5 -4
- package/src/LicensedRetrivora.ts +0 -278
- package/src/app/api/chat/route.ts +0 -4
- package/src/app/api/health/route.ts +0 -5
- package/src/app/api/ingest/route.ts +0 -27
- package/src/app/api/suggestions/route.ts +0 -5
- package/src/app/api/upload/route.ts +0 -5
- package/src/app/constants.tsx +0 -270
- package/src/app/favicon.ico +0 -0
- package/src/app/globals.css +0 -449
- package/src/app/layout.tsx +0 -22
- package/src/app/page.tsx +0 -64
- package/src/app/types.ts +0 -30
- package/src/browser.tsx +0 -139
- package/src/components/ChatWidget.tsx +0 -393
- package/src/components/ChatWindow.tsx +0 -952
- package/src/components/CodeViewer.tsx +0 -56
- package/src/components/ConfigProvider.tsx +0 -123
- package/src/components/DocumentUpload.tsx +0 -354
- package/src/components/DynamicChart.tsx +0 -297
- package/src/components/HourglassLoader.tsx +0 -87
- package/src/components/MarkdownComponents.tsx +0 -186
- package/src/components/MessageBubble.tsx +0 -498
- package/src/components/ObservabilityPanel.tsx +0 -374
- package/src/components/ProductCard.tsx +0 -107
- package/src/components/ProductCarousel.tsx +0 -97
- package/src/components/SourceCard.tsx +0 -61
- package/src/components/ThemeProvider.tsx +0 -8
- package/src/components/ThemeToggle.tsx +0 -29
- package/src/components/ThinkingBlock.tsx +0 -75
- package/src/components/UIDispatcher.tsx +0 -342
- package/src/components/VisualizationRenderer.tsx +0 -621
- package/src/components/constants.tsx +0 -503
- package/src/config/ConfigBuilder.ts +0 -285
- package/src/config/EmbeddingStrategy.ts +0 -148
- package/src/config/LicenseConfigResolver.ts +0 -298
- package/src/config/RagConfig.ts +0 -328
- package/src/config/UniversalProfiles.ts +0 -82
- package/src/config/constants.ts +0 -64
- package/src/config/serverConfig.ts +0 -378
- package/src/config/uiConstants.ts +0 -47
- package/src/core/BatchProcessor.ts +0 -385
- package/src/core/CircuitBreaker.ts +0 -118
- package/src/core/ConfigFetcher.ts +0 -220
- package/src/core/ConfigResolver.ts +0 -165
- package/src/core/ConfigValidator.ts +0 -197
- package/src/core/DatabaseStorage.ts +0 -526
- package/src/core/FreeTierLimitsGuard.ts +0 -281
- package/src/core/LLMRouter.ts +0 -79
- package/src/core/LangChainAgent.ts +0 -132
- package/src/core/LicenseValidator.ts +0 -284
- package/src/core/LicenseVerifier.ts +0 -261
- package/src/core/MultiAgentCoordinator.ts +0 -239
- package/src/core/Pipeline.ts +0 -1279
- package/src/core/PluginManager.ts +0 -277
- package/src/core/ProjectSettings.ts +0 -247
- package/src/core/ProviderHealthCheck.ts +0 -133
- package/src/core/ProviderInterfaces.ts +0 -37
- package/src/core/ProviderRegistry.ts +0 -156
- package/src/core/QueryProcessor.ts +0 -399
- package/src/core/Retrivora.ts +0 -98
- package/src/core/VectorPlugin.ts +0 -193
- package/src/core/mcp.ts +0 -261
- package/src/exceptions/index.ts +0 -131
- package/src/handlers/index.ts +0 -1625
- package/src/hooks/useHydrated.ts +0 -13
- package/src/hooks/useProjectSettings.ts +0 -105
- package/src/hooks/useRagChat.ts +0 -436
- package/src/hooks/useStoredMessages.ts +0 -64
- package/src/index.css +0 -4269
- package/src/index.ts +0 -137
- package/src/lib/plugin.ts +0 -24
- package/src/llm/ILLMProvider.ts +0 -60
- package/src/llm/LLMFactory.ts +0 -141
- package/src/llm/providers/AnthropicProvider.ts +0 -215
- package/src/llm/providers/GeminiProvider.ts +0 -311
- package/src/llm/providers/GroqProvider.ts +0 -184
- package/src/llm/providers/OllamaProvider.ts +0 -232
- package/src/llm/providers/OpenAIProvider.ts +0 -188
- package/src/llm/providers/QwenProvider.ts +0 -199
- package/src/llm/providers/UniversalLLMAdapter.ts +0 -422
- package/src/llm/utils.ts +0 -46
- package/src/providers/graphdb/BaseGraphProvider.ts +0 -43
- package/src/providers/graphdb/SimpleGraphProvider.ts +0 -66
- package/src/providers/vectordb/BaseVectorProvider.ts +0 -98
- package/src/providers/vectordb/ChromaDBProvider.ts +0 -130
- package/src/providers/vectordb/MilvusProvider.ts +0 -134
- package/src/providers/vectordb/MongoDBProvider.ts +0 -250
- package/src/providers/vectordb/MultiTablePostgresProvider.ts +0 -461
- package/src/providers/vectordb/PineconeProvider.ts +0 -295
- package/src/providers/vectordb/PostgreSQLProvider.ts +0 -227
- package/src/providers/vectordb/QdrantProvider.ts +0 -294
- package/src/providers/vectordb/RedisProvider.ts +0 -105
- package/src/providers/vectordb/UniversalVectorProvider.ts +0 -221
- package/src/providers/vectordb/WeaviateProvider.ts +0 -172
- package/src/rag/DocumentChunker.ts +0 -144
- package/src/rag/EntityExtractor.ts +0 -90
- package/src/rag/LlamaIndexIngestor.ts +0 -60
- package/src/rag/Reranker.ts +0 -106
- package/src/rendering/IntentClassifier.ts +0 -167
- package/src/rendering/RendererRegistry.ts +0 -164
- package/src/rendering/RuleEngine.ts +0 -67
- package/src/rendering/VisualizationDecisionEngine.ts +0 -164
- package/src/rendering/__tests__/VisualizationDecisionEngine.test.ts +0 -237
- package/src/rendering/index.ts +0 -12
- package/src/rendering/rules/Rule1SpecificInfoRule.ts +0 -28
- package/src/rendering/rules/Rule2ComparisonRule.ts +0 -24
- package/src/rendering/rules/Rule3ProductDiscoveryRule.ts +0 -28
- package/src/rendering/rules/Rule4AnalyticalRule.ts +0 -38
- package/src/rendering/rules/Rule5MixedResponseRule.ts +0 -29
- package/src/rendering/rules/Rule6SmallResultSetRule.ts +0 -24
- package/src/rendering/rules/Rule7LargeTableRule.ts +0 -35
- package/src/rendering/types.ts +0 -96
- package/src/server.ts +0 -156
- package/src/tailwind.css +0 -194
- package/src/telemetry/TelemetryService.ts +0 -330
- package/src/types/chat.ts +0 -89
- package/src/types/index.ts +0 -278
- package/src/types/pdf-parse.d.ts +0 -13
- package/src/types/props.ts +0 -169
- package/src/utils/DocumentParser.ts +0 -111
- package/src/utils/ProductExtractor.ts +0 -350
- package/src/utils/SchemaMapper.ts +0 -176
- package/src/utils/UITransformer.ts +0 -1812
- package/src/utils/synonyms.ts +0 -80
- package/src/utils/templateUtils.ts +0 -78
- package/src/version.ts +0 -6
|
@@ -1,167 +0,0 @@
|
|
|
1
|
-
import { DecisionContext, IntentCategory } from './types';
|
|
2
|
-
|
|
3
|
-
export interface DataSignals {
|
|
4
|
-
rowCount: number;
|
|
5
|
-
hasNumericFields: boolean;
|
|
6
|
-
hasDateFields: boolean;
|
|
7
|
-
hasCategoricalFields: boolean;
|
|
8
|
-
isProductLike: boolean;
|
|
9
|
-
numericFieldCount: number;
|
|
10
|
-
categoricalFieldCount: number;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export class IntentClassifier {
|
|
14
|
-
/**
|
|
15
|
-
* Fast, zero-latency classifier that maps a user query and optional data context
|
|
16
|
-
* into a high-level IntentCategory.
|
|
17
|
-
*/
|
|
18
|
-
static classify(context: DecisionContext): { intent: IntentCategory; signals: DataSignals } {
|
|
19
|
-
const q = (context.userQuery || '').toLowerCase().trim();
|
|
20
|
-
const signals = this.extractDataSignals(context);
|
|
21
|
-
|
|
22
|
-
// Rule A: Specific Information Lookup
|
|
23
|
-
if (this.isInformationLookup(q)) {
|
|
24
|
-
return { intent: 'information_lookup', signals };
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
// Rule B: Comparison Query
|
|
28
|
-
if (this.isComparisonQuery(q)) {
|
|
29
|
-
return { intent: 'comparison', signals };
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
// Rule C: Product Search / Recommendation
|
|
33
|
-
if (this.isProductQuery(q) || (signals.isProductLike && this.isRecommendationQuery(q))) {
|
|
34
|
-
return { intent: 'product_search', signals };
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
// Rule D: Trend Analysis
|
|
38
|
-
if (this.isTrendQuery(q) || (signals.hasDateFields && signals.hasNumericFields && /\b(growth|trend|over time|monthly|yearly|weekly)\b/.test(q))) {
|
|
39
|
-
return { intent: 'trend_analysis', signals };
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
// Rule E: Ranking Query
|
|
43
|
-
if (this.isRankingQuery(q)) {
|
|
44
|
-
return { intent: 'ranking', signals };
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
// Rule F: Analytics Query
|
|
48
|
-
if (this.isAnalyticsQuery(q) || (signals.hasNumericFields && signals.hasCategoricalFields && /\b(sales|revenue|performance|count|total|average|breakdown|share|percentage|correlation)\b/.test(q))) {
|
|
49
|
-
return { intent: 'analytics', signals };
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
// Rule G: Recommendation fallback
|
|
53
|
-
if (this.isRecommendationQuery(q)) {
|
|
54
|
-
return { intent: 'recommendation', signals };
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// Fallback: Default to information lookup for generic queries
|
|
58
|
-
return { intent: 'information_lookup', signals };
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* Extract key data structure signals from retrieved documents.
|
|
63
|
-
*/
|
|
64
|
-
static extractDataSignals(context: DecisionContext): DataSignals {
|
|
65
|
-
const docs = context.retrievedDocuments || [];
|
|
66
|
-
const rowCount = docs.length;
|
|
67
|
-
|
|
68
|
-
let hasNumericFields = false;
|
|
69
|
-
let hasDateFields = false;
|
|
70
|
-
let hasCategoricalFields = false;
|
|
71
|
-
let isProductLike = false;
|
|
72
|
-
let numericFieldCount = 0;
|
|
73
|
-
let categoricalFieldCount = 0;
|
|
74
|
-
|
|
75
|
-
if (docs.length > 0) {
|
|
76
|
-
const keys = new Set<string>();
|
|
77
|
-
let numericKeys = new Set<string>();
|
|
78
|
-
let dateKeys = new Set<string>();
|
|
79
|
-
let catKeys = new Set<string>();
|
|
80
|
-
|
|
81
|
-
let productKeyMatches = 0;
|
|
82
|
-
|
|
83
|
-
docs.forEach(doc => {
|
|
84
|
-
const meta = doc.metadata || {};
|
|
85
|
-
Object.entries(meta).forEach(([key, val]) => {
|
|
86
|
-
keys.add(key);
|
|
87
|
-
const kLower = key.toLowerCase();
|
|
88
|
-
if (['price', 'image', 'brand', 'in_stock', 'rating', 'sku', 'product'].some(p => kLower.includes(p))) {
|
|
89
|
-
productKeyMatches++;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
if (typeof val === 'number') {
|
|
93
|
-
numericKeys.add(key);
|
|
94
|
-
} else if (typeof val === 'string') {
|
|
95
|
-
if (/^\d{4}-\d{2}-\d{2}/.test(val) || !isNaN(Date.parse(val)) && val.length > 5) {
|
|
96
|
-
dateKeys.add(key);
|
|
97
|
-
} else if (val.length < 50 && !val.includes('\n')) {
|
|
98
|
-
catKeys.add(key);
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
});
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
hasNumericFields = numericKeys.size > 0;
|
|
105
|
-
hasDateFields = dateKeys.size > 0;
|
|
106
|
-
hasCategoricalFields = catKeys.size > 0;
|
|
107
|
-
numericFieldCount = numericKeys.size;
|
|
108
|
-
categoricalFieldCount = catKeys.size;
|
|
109
|
-
|
|
110
|
-
if (productKeyMatches >= 2 || docs.some(d => (d?.content ?? '').toLowerCase().includes('price') || (d?.content ?? '').toLowerCase().includes('brand'))) {
|
|
111
|
-
isProductLike = true;
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
return {
|
|
116
|
-
rowCount,
|
|
117
|
-
hasNumericFields,
|
|
118
|
-
hasDateFields,
|
|
119
|
-
hasCategoricalFields,
|
|
120
|
-
isProductLike,
|
|
121
|
-
numericFieldCount,
|
|
122
|
-
categoricalFieldCount,
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
// ─── Intent Heuristic Checkers ─────────────────────────────────────────────
|
|
127
|
-
|
|
128
|
-
private static isInformationLookup(query: string): boolean {
|
|
129
|
-
// Exact single-fact pattern matches e.g. "What is X?", "Explain Y", "Explore Z", "Tell me about A"
|
|
130
|
-
if (/^(what|who|explain|explore|define|where|when|why|how|how does|can|could|does|do|is|are|has|have|will|should|would|meaning of|tell me about|show details of|overview of|summarize)\s+/i.test(query)) {
|
|
131
|
-
// Exclude comparison or analytical phrasing inside "what is the trend..."
|
|
132
|
-
if (!/\b(compare|versus|vs\.?|trend|monthly|revenue|top 10|top selling|best|chart|graph|plot|breakdown|analytics)\b/i.test(query)) {
|
|
133
|
-
return true;
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
// "price of X" / "cost of Y"
|
|
137
|
-
if (/^(what is the )?(price|cost|fee|rate) of\b/i.test(query)) {
|
|
138
|
-
return true;
|
|
139
|
-
}
|
|
140
|
-
return false;
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
private static isComparisonQuery(query: string): boolean {
|
|
144
|
-
return /\b(compare|comparison|vs\.?|versus|difference between|differ|contrast|against)\b/i.test(query);
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
private static isProductQuery(query: string): boolean {
|
|
148
|
-
return /\b(best|recommend|top|buy|shopping|under \$|cheap|shoes|laptops|chairs|headphones|phone|sneakers|apparel|products)\b/i.test(query)
|
|
149
|
-
&& !/\b(compare|chart|sales|revenue|trend)\b/i.test(query);
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
private static isRecommendationQuery(query: string): boolean {
|
|
153
|
-
return /\b(recommend|suggest|what should i (buy|get|choose)|best options|top picks)\b/i.test(query);
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
private static isTrendQuery(query: string): boolean {
|
|
157
|
-
return /\b(trend|trends|growth|over time|historical|timeline|monthly|yearly|weekly|daily|revenue growth|sales growth)\b/i.test(query);
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
private static isRankingQuery(query: string): boolean {
|
|
161
|
-
return /\b(highest|lowest|top\s*\d+|bottom\s*\d+|rank|ranking|top performing|best performing)\b/i.test(query);
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
private static isAnalyticsQuery(query: string): boolean {
|
|
165
|
-
return /\b(sales|revenue|analytics|insights|distribution|percentage|share|breakdown|breakup|scatter|correlation|metrics|performance|by region|by category)\b/i.test(query);
|
|
166
|
-
}
|
|
167
|
-
}
|
|
@@ -1,164 +0,0 @@
|
|
|
1
|
-
import { IRendererStrategy, RenderType } from './types';
|
|
2
|
-
import { UITransformationResponse, VectorMatch } from '../types';
|
|
3
|
-
import { UITransformer } from '../utils/UITransformer';
|
|
4
|
-
|
|
5
|
-
// ── Default Strategy Implementations ───────────────────────────────────────────
|
|
6
|
-
|
|
7
|
-
export class TextRendererStrategy implements IRendererStrategy {
|
|
8
|
-
readonly type = 'text';
|
|
9
|
-
|
|
10
|
-
render(data: unknown, options?: Record<string, unknown>): UITransformationResponse {
|
|
11
|
-
const title = (options?.title as string) || 'Information';
|
|
12
|
-
if (typeof data === 'string') {
|
|
13
|
-
return { type: 'text', title, data: { content: data } };
|
|
14
|
-
}
|
|
15
|
-
const docs = Array.isArray(data) ? (data as VectorMatch[]) : [];
|
|
16
|
-
const text = docs.map(d => d?.content ?? '').join('\n\n');
|
|
17
|
-
return { type: 'text', title, data: { content: text || 'No detailed content available.' } };
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export class TableRendererStrategy implements IRendererStrategy {
|
|
22
|
-
readonly type = 'table';
|
|
23
|
-
|
|
24
|
-
render(data: unknown, options?: Record<string, unknown>): UITransformationResponse {
|
|
25
|
-
const docs = Array.isArray(data) ? (data as VectorMatch[]) : [];
|
|
26
|
-
const query = (options?.query as string) || '';
|
|
27
|
-
return UITransformer.transform(query, docs, undefined, undefined, {
|
|
28
|
-
visualizationHint: 'table',
|
|
29
|
-
recommendedChart: 'table',
|
|
30
|
-
filterInStockOnly: false,
|
|
31
|
-
wantsExplicitTable: true,
|
|
32
|
-
isTemporal: false,
|
|
33
|
-
isComparison: true,
|
|
34
|
-
language: 'en',
|
|
35
|
-
});
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export class CarouselRendererStrategy implements IRendererStrategy {
|
|
40
|
-
readonly type = 'carousel';
|
|
41
|
-
|
|
42
|
-
render(data: unknown, options?: Record<string, unknown>): UITransformationResponse {
|
|
43
|
-
const docs = Array.isArray(data) ? (data as VectorMatch[]) : [];
|
|
44
|
-
const query = (options?.query as string) || '';
|
|
45
|
-
return UITransformer.transform(query, docs, undefined, undefined, {
|
|
46
|
-
visualizationHint: 'product_browse',
|
|
47
|
-
recommendedChart: 'text',
|
|
48
|
-
filterInStockOnly: false,
|
|
49
|
-
wantsExplicitTable: false,
|
|
50
|
-
isTemporal: false,
|
|
51
|
-
isComparison: false,
|
|
52
|
-
language: 'en',
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
export class ChartRendererStrategy implements IRendererStrategy {
|
|
58
|
-
readonly type = 'chart';
|
|
59
|
-
|
|
60
|
-
render(data: unknown, options?: Record<string, unknown>): UITransformationResponse {
|
|
61
|
-
const docs = Array.isArray(data) ? (data as VectorMatch[]) : [];
|
|
62
|
-
const query = (options?.query as string) || '';
|
|
63
|
-
const chartType = (options?.chartType as string) || 'bar';
|
|
64
|
-
|
|
65
|
-
let hint: any = 'comparison';
|
|
66
|
-
let rec: any = 'bar_chart';
|
|
67
|
-
|
|
68
|
-
if (chartType === 'line') {
|
|
69
|
-
hint = 'trend';
|
|
70
|
-
rec = 'line_chart';
|
|
71
|
-
} else if (chartType === 'pie') {
|
|
72
|
-
hint = 'composition';
|
|
73
|
-
rec = 'pie_chart';
|
|
74
|
-
} else if (chartType === 'scatter') {
|
|
75
|
-
hint = 'correlation';
|
|
76
|
-
rec = 'scatter_plot';
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
return UITransformer.transform(query, docs, undefined, undefined, {
|
|
80
|
-
visualizationHint: hint,
|
|
81
|
-
recommendedChart: rec,
|
|
82
|
-
filterInStockOnly: false,
|
|
83
|
-
wantsExplicitTable: false,
|
|
84
|
-
isTemporal: chartType === 'line',
|
|
85
|
-
isComparison: chartType === 'bar',
|
|
86
|
-
language: 'en',
|
|
87
|
-
});
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
export class MixedRendererStrategy implements IRendererStrategy {
|
|
92
|
-
readonly type = 'mixed';
|
|
93
|
-
|
|
94
|
-
render(data: unknown, options?: Record<string, unknown>): UITransformationResponse {
|
|
95
|
-
const docs = Array.isArray(data) ? (data as VectorMatch[]) : [];
|
|
96
|
-
const sections = (options?.sections as Array<{ type: RenderType; chartType?: string; title?: string }>) || [];
|
|
97
|
-
|
|
98
|
-
const sectionPayloads = sections.map(s => {
|
|
99
|
-
const strategy = RendererRegistry.getStrategy(s.type);
|
|
100
|
-
return {
|
|
101
|
-
type: s.type,
|
|
102
|
-
title: s.title,
|
|
103
|
-
payload: strategy.render(data, { ...options, chartType: s.chartType, title: s.title }),
|
|
104
|
-
};
|
|
105
|
-
});
|
|
106
|
-
|
|
107
|
-
return {
|
|
108
|
-
type: 'table', // Fallback container type for compatibility
|
|
109
|
-
title: (options?.title as string) || 'Composite Response',
|
|
110
|
-
description: `Mixed payload containing ${sectionPayloads.length} visual sections`,
|
|
111
|
-
data: { sections: sectionPayloads },
|
|
112
|
-
};
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// ── Renderer Registry Class ───────────────────────────────────────────────────
|
|
117
|
-
|
|
118
|
-
export class RendererRegistry {
|
|
119
|
-
private static strategies = new Map<string, IRendererStrategy>();
|
|
120
|
-
|
|
121
|
-
static {
|
|
122
|
-
// Register default strategies
|
|
123
|
-
this.registerStrategy(new TextRendererStrategy());
|
|
124
|
-
this.registerStrategy(new TableRendererStrategy());
|
|
125
|
-
this.registerStrategy(new CarouselRendererStrategy());
|
|
126
|
-
this.registerStrategy(new ChartRendererStrategy());
|
|
127
|
-
this.registerStrategy(new MixedRendererStrategy());
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
/**
|
|
131
|
-
* Register a new renderer strategy.
|
|
132
|
-
* Enables seamless addition of custom visualizers (Timeline, Maps, Flow Diagrams, etc.).
|
|
133
|
-
*/
|
|
134
|
-
static registerStrategy(strategy: IRendererStrategy): void {
|
|
135
|
-
this.strategies.set(String(strategy.type).toLowerCase(), strategy);
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
/**
|
|
139
|
-
* Retrieve a registered renderer strategy by type string.
|
|
140
|
-
*/
|
|
141
|
-
static getStrategy(type: string): IRendererStrategy {
|
|
142
|
-
const key = type.toLowerCase();
|
|
143
|
-
const strategy = this.strategies.get(key);
|
|
144
|
-
if (!strategy) {
|
|
145
|
-
// Fallback to text strategy if unknown type requested
|
|
146
|
-
return this.strategies.get('text')!;
|
|
147
|
-
}
|
|
148
|
-
return strategy;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* Check if a renderer strategy is registered.
|
|
153
|
-
*/
|
|
154
|
-
static hasStrategy(type: string): boolean {
|
|
155
|
-
return this.strategies.has(type.toLowerCase());
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/**
|
|
159
|
-
* List all registered strategy types.
|
|
160
|
-
*/
|
|
161
|
-
static getRegisteredTypes(): string[] {
|
|
162
|
-
return Array.from(this.strategies.keys());
|
|
163
|
-
}
|
|
164
|
-
}
|
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
import { DecisionContext, IntentCategory, IRenderRule, RenderDecision } from './types';
|
|
2
|
-
import { Rule1SpecificInfoRule } from './rules/Rule1SpecificInfoRule';
|
|
3
|
-
import { Rule2ComparisonRule } from './rules/Rule2ComparisonRule';
|
|
4
|
-
import { Rule3ProductDiscoveryRule } from './rules/Rule3ProductDiscoveryRule';
|
|
5
|
-
import { Rule4AnalyticalRule } from './rules/Rule4AnalyticalRule';
|
|
6
|
-
import { Rule5MixedResponseRule } from './rules/Rule5MixedResponseRule';
|
|
7
|
-
import { Rule6SmallResultSetRule } from './rules/Rule6SmallResultSetRule';
|
|
8
|
-
import { Rule7LargeTableRule } from './rules/Rule7LargeTableRule';
|
|
9
|
-
|
|
10
|
-
export class RuleEngine {
|
|
11
|
-
private rules: IRenderRule[] = [];
|
|
12
|
-
|
|
13
|
-
constructor() {
|
|
14
|
-
this.registerDefaultRules();
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Register standard rules in priority order.
|
|
19
|
-
*/
|
|
20
|
-
private registerDefaultRules() {
|
|
21
|
-
this.registerRule(new Rule6SmallResultSetRule()); // Priority 110 (Small data guardrail)
|
|
22
|
-
this.registerRule(new Rule1SpecificInfoRule()); // Priority 100 (Fact/definition)
|
|
23
|
-
this.registerRule(new Rule5MixedResponseRule()); // Priority 95 (Multi-section)
|
|
24
|
-
this.registerRule(new Rule2ComparisonRule()); // Priority 90 (Comparison)
|
|
25
|
-
this.registerRule(new Rule3ProductDiscoveryRule()); // Priority 85 (Product/carousel)
|
|
26
|
-
this.registerRule(new Rule4AnalyticalRule()); // Priority 80 (Charts)
|
|
27
|
-
this.registerRule(new Rule7LargeTableRule()); // Priority 75 (Large datasets > 5)
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Add or replace a rule in the engine.
|
|
32
|
-
* Automatically keeps rules sorted by descending priority.
|
|
33
|
-
*/
|
|
34
|
-
registerRule(rule: IRenderRule): void {
|
|
35
|
-
// Remove existing rule with same name if present
|
|
36
|
-
this.rules = this.rules.filter(r => r.name !== rule.name);
|
|
37
|
-
this.rules.push(rule);
|
|
38
|
-
this.rules.sort((a, b) => b.priority - a.priority);
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/**
|
|
42
|
-
* Evaluate context against rules in descending priority order.
|
|
43
|
-
* Returns the first non-null RenderDecision.
|
|
44
|
-
*/
|
|
45
|
-
evaluate(context: DecisionContext, intent: IntentCategory): RenderDecision {
|
|
46
|
-
for (const rule of this.rules) {
|
|
47
|
-
const decision = rule.evaluate(context, intent);
|
|
48
|
-
if (decision) {
|
|
49
|
-
return decision;
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
// Default fallback
|
|
54
|
-
return {
|
|
55
|
-
renderType: 'text',
|
|
56
|
-
confidence: 0.70,
|
|
57
|
-
reason: 'Default fallback: No specific visualization rule matched context.',
|
|
58
|
-
};
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* List all registered rules.
|
|
63
|
-
*/
|
|
64
|
-
getRegisteredRules(): Array<{ name: string; priority: number }> {
|
|
65
|
-
return this.rules.map(r => ({ name: r.name, priority: r.priority }));
|
|
66
|
-
}
|
|
67
|
-
}
|
|
@@ -1,164 +0,0 @@
|
|
|
1
|
-
import { DecisionContext, RenderDecision } from './types';
|
|
2
|
-
import { IntentClassifier } from './IntentClassifier';
|
|
3
|
-
import { RuleEngine } from './RuleEngine';
|
|
4
|
-
import { RendererRegistry } from './RendererRegistry';
|
|
5
|
-
import { UITransformationResponse, VectorMatch } from '../types';
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* LRU Cache for visualization decisions to achieve sub-millisecond repeated execution.
|
|
9
|
-
*/
|
|
10
|
-
class LRUDecisionCache {
|
|
11
|
-
private cache = new Map<string, { decision: RenderDecision; timestamp: number }>();
|
|
12
|
-
private maxSize: number;
|
|
13
|
-
|
|
14
|
-
constructor(maxSize = 200) {
|
|
15
|
-
this.maxSize = maxSize;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
private generateKey(context: DecisionContext): string {
|
|
19
|
-
const q = (context.userQuery || '').toLowerCase().trim();
|
|
20
|
-
const docCount = context.retrievedDocuments?.length ?? 0;
|
|
21
|
-
return `${q}::docs:${docCount}`;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
get(context: DecisionContext): RenderDecision | undefined {
|
|
25
|
-
const key = this.generateKey(context);
|
|
26
|
-
const item = this.cache.get(key);
|
|
27
|
-
if (item) {
|
|
28
|
-
// Refresh LRU position
|
|
29
|
-
this.cache.delete(key);
|
|
30
|
-
this.cache.set(key, item);
|
|
31
|
-
return item.decision;
|
|
32
|
-
}
|
|
33
|
-
return undefined;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
set(context: DecisionContext, decision: RenderDecision): void {
|
|
37
|
-
const key = this.generateKey(context);
|
|
38
|
-
if (this.cache.has(key)) {
|
|
39
|
-
this.cache.delete(key);
|
|
40
|
-
} else if (this.cache.size >= this.maxSize) {
|
|
41
|
-
const oldest = this.cache.keys().next().value;
|
|
42
|
-
if (oldest !== undefined) this.cache.delete(oldest);
|
|
43
|
-
}
|
|
44
|
-
this.cache.set(key, { decision, timestamp: Date.now() });
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
clear(): void {
|
|
48
|
-
this.cache.clear();
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
get size(): number {
|
|
52
|
-
return this.cache.size;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* High-Performance Visualization Decision Engine.
|
|
58
|
-
* Intelligently determines whether to render text, table, carousel, chart, or mixed sections
|
|
59
|
-
* BEFORE expensive visual generation or LLM visual calls execute.
|
|
60
|
-
*/
|
|
61
|
-
export class VisualizationDecisionEngine {
|
|
62
|
-
private static ruleEngine = new RuleEngine();
|
|
63
|
-
private static cache = new LRUDecisionCache(200);
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* Evaluate user query, documents, and context to produce a RenderDecision.
|
|
67
|
-
* Execution time is < 1ms for cached or rule-matched queries.
|
|
68
|
-
*/
|
|
69
|
-
static decideVisualization(
|
|
70
|
-
userQuery: string,
|
|
71
|
-
retrievedDocuments?: VectorMatch[],
|
|
72
|
-
llmResponse?: string,
|
|
73
|
-
metadata?: Record<string, unknown>
|
|
74
|
-
): RenderDecision {
|
|
75
|
-
const context: DecisionContext = {
|
|
76
|
-
userQuery,
|
|
77
|
-
retrievedDocuments,
|
|
78
|
-
llmResponse,
|
|
79
|
-
metadata,
|
|
80
|
-
};
|
|
81
|
-
|
|
82
|
-
// Check LRU cache first
|
|
83
|
-
const cached = this.cache.get(context);
|
|
84
|
-
if (cached) {
|
|
85
|
-
return cached;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
// Step 1: Zero-latency Intent Classification
|
|
89
|
-
const { intent } = IntentClassifier.classify(context);
|
|
90
|
-
|
|
91
|
-
// Step 2: Evaluate priority rules
|
|
92
|
-
const decision = this.ruleEngine.evaluate(context, intent);
|
|
93
|
-
|
|
94
|
-
// Cache result
|
|
95
|
-
this.cache.set(context, decision);
|
|
96
|
-
|
|
97
|
-
return decision;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* Convenience helper to decide AND render the data into a UITransformationResponse.
|
|
102
|
-
*/
|
|
103
|
-
static render(
|
|
104
|
-
userQuery: string,
|
|
105
|
-
retrievedDocuments?: VectorMatch[],
|
|
106
|
-
llmResponse?: string,
|
|
107
|
-
metadata?: Record<string, unknown>
|
|
108
|
-
): UITransformationResponse {
|
|
109
|
-
const decision = this.decideVisualization(userQuery, retrievedDocuments, llmResponse, metadata);
|
|
110
|
-
const strategy = RendererRegistry.getStrategy(decision.renderType);
|
|
111
|
-
return strategy.render(retrievedDocuments || [], {
|
|
112
|
-
query: userQuery,
|
|
113
|
-
chartType: decision.chartType,
|
|
114
|
-
sections: decision.sections,
|
|
115
|
-
...metadata,
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
/**
|
|
120
|
-
* Register a custom rule in the rule engine.
|
|
121
|
-
*/
|
|
122
|
-
static registerRule(rule: import('./types').IRenderRule): void {
|
|
123
|
-
this.ruleEngine.registerRule(rule);
|
|
124
|
-
this.cache.clear(); // Clear cache when rules change
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
/**
|
|
128
|
-
* Register a custom renderer strategy.
|
|
129
|
-
*/
|
|
130
|
-
static registerRendererStrategy(strategy: import('./types').IRendererStrategy): void {
|
|
131
|
-
RendererRegistry.registerStrategy(strategy);
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/**
|
|
135
|
-
* Clear the decision cache.
|
|
136
|
-
*/
|
|
137
|
-
static clearCache(): void {
|
|
138
|
-
this.cache.clear();
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
/**
|
|
142
|
-
* Get size of current decision cache.
|
|
143
|
-
*/
|
|
144
|
-
static getCacheSize(): number {
|
|
145
|
-
return this.cache.size;
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/**
|
|
150
|
-
* Top-level function export matching prompt specification.
|
|
151
|
-
*/
|
|
152
|
-
export function decideVisualization(
|
|
153
|
-
userQuery: string,
|
|
154
|
-
retrievedDocuments?: VectorMatch[],
|
|
155
|
-
llmResponse?: string,
|
|
156
|
-
metadata?: Record<string, unknown>
|
|
157
|
-
): RenderDecision {
|
|
158
|
-
return VisualizationDecisionEngine.decideVisualization(
|
|
159
|
-
userQuery,
|
|
160
|
-
retrievedDocuments,
|
|
161
|
-
llmResponse,
|
|
162
|
-
metadata
|
|
163
|
-
);
|
|
164
|
-
}
|