@retrivora-ai/rag-engine 2.0.1 → 2.0.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 (49) hide show
  1. package/FREE_TIER_ARCHITECTURE.md +232 -0
  2. package/README.md +9 -0
  3. package/dist/{ILLMProvider-DMxLyTdq.d.mts → ILLMProvider-0rRBYbVW.d.mts} +133 -1
  4. package/dist/{ILLMProvider-DMxLyTdq.d.ts → ILLMProvider-0rRBYbVW.d.ts} +133 -1
  5. package/dist/handlers/index.d.mts +2 -2
  6. package/dist/handlers/index.d.ts +2 -2
  7. package/dist/handlers/index.js +679 -15
  8. package/dist/handlers/index.mjs +679 -15
  9. package/dist/index-B1wGUlSL.d.mts +532 -0
  10. package/dist/{index-tzwc7UhY.d.ts → index-BIHHp_f6.d.ts} +1 -1
  11. package/dist/{index-DHsFLJXQ.d.mts → index-BvODr57d.d.mts} +1 -1
  12. package/dist/index-DcklhThn.d.ts +532 -0
  13. package/dist/index.css +51 -3
  14. package/dist/index.d.mts +6 -105
  15. package/dist/index.d.ts +6 -105
  16. package/dist/index.js +1918 -8
  17. package/dist/index.mjs +1913 -8
  18. package/dist/server.d.mts +51 -7
  19. package/dist/server.d.ts +51 -7
  20. package/dist/server.js +721 -15
  21. package/dist/server.mjs +704 -15
  22. package/package.json +9 -7
  23. package/src/app/page.tsx +54 -18
  24. package/src/components/ChatWindow.tsx +2 -2
  25. package/src/components/DocumentUpload.tsx +5 -4
  26. package/src/components/MessageBubble.tsx +2 -4
  27. package/src/core/Pipeline.ts +23 -5
  28. package/src/handlers/index.ts +48 -1
  29. package/src/index.ts +22 -4
  30. package/src/rendering/IntentClassifier.ts +167 -0
  31. package/src/rendering/RendererRegistry.ts +164 -0
  32. package/src/rendering/RuleEngine.ts +67 -0
  33. package/src/rendering/VisualizationDecisionEngine.ts +164 -0
  34. package/src/rendering/__tests__/VisualizationDecisionEngine.test.ts +237 -0
  35. package/src/rendering/index.ts +12 -0
  36. package/src/rendering/rules/Rule1SpecificInfoRule.ts +28 -0
  37. package/src/rendering/rules/Rule2ComparisonRule.ts +24 -0
  38. package/src/rendering/rules/Rule3ProductDiscoveryRule.ts +28 -0
  39. package/src/rendering/rules/Rule4AnalyticalRule.ts +38 -0
  40. package/src/rendering/rules/Rule5MixedResponseRule.ts +29 -0
  41. package/src/rendering/rules/Rule6SmallResultSetRule.ts +24 -0
  42. package/src/rendering/rules/Rule7LargeTableRule.ts +35 -0
  43. package/src/rendering/types.ts +96 -0
  44. package/src/server.ts +3 -2
  45. package/src/types/index.ts +48 -0
  46. package/src/utils/DocumentParser.ts +64 -28
  47. package/src/utils/UITransformer.ts +15 -4
  48. package/dist/index-CfkqZd2Y.d.ts +0 -197
  49. package/dist/index-xygonxpW.d.mts +0 -197
@@ -1,197 +0,0 @@
1
- import { k as RagConfig, I as ILLMProvider, g as IngestDocument, C as ChatMessage, d as ChatResponse, u as RetrievalResult, n as UniversalRagConfig } from './ILLMProvider-DMxLyTdq.js';
2
-
3
- /**
4
- * DocumentChunker — splits long text into overlapping chunks
5
- * suitable for vector embedding and retrieval.
6
- *
7
- * Strategy: sentence-aware sliding window
8
- * 1. Split on sentence boundaries
9
- * 2. Accumulate sentences into chunks up to `chunkSize` characters
10
- * 3. Carry over `chunkOverlap` characters from the previous chunk
11
- */
12
- interface Chunk {
13
- id: string;
14
- content: string;
15
- metadata?: Record<string, unknown>;
16
- }
17
- interface ChunkOptions {
18
- /** Target chunk size in characters (default 1000) */
19
- chunkSize?: number;
20
- /** Overlap between consecutive chunks in characters (default 200) */
21
- chunkOverlap?: number;
22
- /** Source document identifier used as ID prefix */
23
- docId?: string | number;
24
- /** Extra metadata to attach to every chunk */
25
- metadata?: Record<string, unknown>;
26
- /** Characters used to split text, in order of priority */
27
- separators?: string[];
28
- }
29
- declare class DocumentChunker {
30
- private readonly chunkSize;
31
- private readonly chunkOverlap;
32
- private readonly separators;
33
- constructor(chunkSize?: number, chunkOverlap?: number, separators?: string[]);
34
- /**
35
- * Split a single text string into overlapping chunks using a recursive strategy.
36
- * Preserves structural boundaries (Markdown headers) where possible.
37
- */
38
- chunk(text: string, options?: ChunkOptions): Chunk[];
39
- private recursiveSplit;
40
- chunkMany(documents: Array<{
41
- content: string;
42
- docId?: string | number;
43
- metadata?: Record<string, unknown>;
44
- }>): Chunk[];
45
- }
46
-
47
- /**
48
- * Pipeline — orchestrates the RAG flow: Embed → Search → Augment → Generate.
49
- *
50
- * Features:
51
- * - Lazy initialization of providers
52
- * - Batch processing with retry logic
53
- * - Smart embedding strategy (integrated / separate / external)
54
- * - Error recovery for transient failures
55
- * - Multi-tenancy support via namespacing
56
- * - LRU-bounded embedding cache (max 500 entries, prevents memory leaks)
57
- * - Full observability tracing (latency, tokens, hallucination scoring)
58
- */
59
- declare class Pipeline {
60
- private config;
61
- private vectorDB;
62
- private graphDB?;
63
- private llmProvider;
64
- private embeddingProvider;
65
- private llmRouter;
66
- private chunker;
67
- private llamaIngestor?;
68
- private entityExtractor?;
69
- private reranker;
70
- private agent?;
71
- private mcpRegistry?;
72
- private multiAgentCoordinator?;
73
- /** LRU-bounded cache: avoids re-embedding identical queries within the same process. */
74
- private embeddingCache;
75
- private initialised;
76
- /** Namespace-specific static cold context cache for CAG */
77
- private coldContexts;
78
- constructor(config: RagConfig);
79
- /**
80
- * Expose the underlying LLM provider (set after initialize()).
81
- * Used by the stream handler to pass to UITransformer.analyzeAndDecide().
82
- */
83
- getLLMProvider(): ILLMProvider | undefined;
84
- initialize(): Promise<void>;
85
- private loadColdContext;
86
- /**
87
- * Ingest documents with automatic chunking, embedding, and batch upsert.
88
- */
89
- ingest(documents: IngestDocument[], namespace?: string): Promise<Array<{
90
- docId: string | number;
91
- chunksIngested: number;
92
- }>>;
93
- /** Step 1: Chunk the document content. */
94
- private prepareChunks;
95
- /**
96
- * Step 2: Generate embeddings for chunks with retry logic.
97
- * Uses batchEmbed when available for efficiency; falls back to sequential embedding.
98
- */
99
- private processEmbeddings;
100
- /** Step 3: Upsert chunks to vector database with retry logic. */
101
- private processUpserts;
102
- /** Step 4: Optional graph-based entity extraction and ingestion. */
103
- private processGraphIngestion;
104
- runNormalQuery(question: string, history?: ChatMessage[], namespace?: string): Promise<{
105
- reply: string;
106
- sources: any[];
107
- }>;
108
- ask(question: string, history?: ChatMessage[], namespace?: string): Promise<ChatResponse>;
109
- askStream(question: string, history?: ChatMessage[], namespace?: string): AsyncIterable<string | ChatResponse>;
110
- /**
111
- * High-performance streaming RAG flow.
112
- * Yields text chunks first, then the retrieval metadata + observability trace at the end.
113
- *
114
- * Latency optimizations:
115
- * - Strategy classification runs in parallel with query embedding (saves ~400ms)
116
- * - Hallucination scoring is fire-and-forget (doesn't block metadata yield)
117
- * - UITransformation is computed after text streaming and emitted with metadata
118
- * - SchemaMapper.train runs while answer generation streams
119
- */
120
- askStreamInternal(question: string, history?: ChatMessage[], namespace?: string): AsyncIterable<string | ChatResponse>;
121
- /**
122
- * Universal retrieval method combining all enabled providers.
123
- * Uses an LRU-bounded embedding cache to avoid re-embedding the same query.
124
- */
125
- private generateUiTransformation;
126
- private applyStructuredFilters;
127
- private resolveNumericPredicateValue;
128
- private extractNumericValueFromContent;
129
- private matchesNumericPredicate;
130
- private normalizeComparableField;
131
- private fieldSimilarityScore;
132
- private fieldTokens;
133
- private toFiniteNumber;
134
- retrieve(query: string, options: {
135
- namespace?: string;
136
- topK?: number;
137
- filter?: Record<string, unknown>;
138
- }): Promise<RetrievalResult>;
139
- /** Rewrite the user query for better retrieval performance. */
140
- private rewriteQuery;
141
- /** Generate 3-5 short, relevant questions based on the vector database content. */
142
- getSuggestions(query: string, namespace?: string): Promise<string[]>;
143
- }
144
-
145
- /**
146
- * Public SDK facade matching the prompt-level Retrivora API.
147
- *
148
- * It keeps provider details behind configuration and delegates execution to the
149
- * existing Pipeline implementation.
150
- */
151
- declare class Retrivora {
152
- private readonly pipeline;
153
- readonly config: RagConfig;
154
- constructor(config?: UniversalRagConfig);
155
- initialize(): Promise<void>;
156
- ingest(documents: IngestDocument[], namespace?: string): Promise<Array<{
157
- docId: string | number;
158
- chunksIngested: number;
159
- }>>;
160
- ask(question: string, history?: ChatMessage[], namespace?: string): Promise<ChatResponse>;
161
- askStream(question: string, history?: ChatMessage[], namespace?: string): AsyncIterable<string | ChatResponse>;
162
- getPipeline(): Pipeline;
163
- }
164
-
165
- /**
166
- * Named SDK exceptions make failures machine-readable for host applications.
167
- */
168
- type RetrivoraErrorCode = 'PROVIDER_NOT_FOUND' | 'EMBEDDING_FAILED' | 'RETRIEVAL_FAILED' | 'RATE_LIMITED' | 'CONFIGURATION_ERROR' | 'AUTHENTICATION_ERROR';
169
- declare class RetrivoraError extends Error {
170
- readonly code: RetrivoraErrorCode;
171
- readonly details?: unknown;
172
- constructor(message: string, code: RetrivoraErrorCode, details?: unknown);
173
- }
174
- declare class ProviderNotFoundException extends RetrivoraError {
175
- constructor(providerType: string, provider: string, details?: unknown);
176
- }
177
- declare class EmbeddingFailedException extends RetrivoraError {
178
- constructor(message?: string, details?: unknown);
179
- }
180
- declare class RetrievalException extends RetrivoraError {
181
- constructor(message?: string, details?: unknown);
182
- }
183
- declare class RateLimitException extends RetrivoraError {
184
- constructor(message?: string, details?: unknown);
185
- }
186
- declare class ConfigurationException extends RetrivoraError {
187
- constructor(message: string, details?: unknown);
188
- }
189
- declare class AuthenticationException extends RetrivoraError {
190
- constructor(message?: string, details?: unknown);
191
- }
192
- /**
193
- * Wraps any unknown error into an appropriate RetrivoraError subclass.
194
- */
195
- declare function wrapError(err: unknown, defaultCode: RetrivoraErrorCode, defaultMessage?: string): RetrivoraError;
196
-
197
- export { AuthenticationException as A, type Chunk as C, DocumentChunker as D, EmbeddingFailedException as E, ProviderNotFoundException as P, RateLimitException as R, type ChunkOptions as a, ConfigurationException as b, RetrievalException as c, Retrivora as d, RetrivoraError as e, type RetrivoraErrorCode as f, Pipeline as g, wrapError as w };
@@ -1,197 +0,0 @@
1
- import { k as RagConfig, I as ILLMProvider, g as IngestDocument, C as ChatMessage, d as ChatResponse, u as RetrievalResult, n as UniversalRagConfig } from './ILLMProvider-DMxLyTdq.mjs';
2
-
3
- /**
4
- * DocumentChunker — splits long text into overlapping chunks
5
- * suitable for vector embedding and retrieval.
6
- *
7
- * Strategy: sentence-aware sliding window
8
- * 1. Split on sentence boundaries
9
- * 2. Accumulate sentences into chunks up to `chunkSize` characters
10
- * 3. Carry over `chunkOverlap` characters from the previous chunk
11
- */
12
- interface Chunk {
13
- id: string;
14
- content: string;
15
- metadata?: Record<string, unknown>;
16
- }
17
- interface ChunkOptions {
18
- /** Target chunk size in characters (default 1000) */
19
- chunkSize?: number;
20
- /** Overlap between consecutive chunks in characters (default 200) */
21
- chunkOverlap?: number;
22
- /** Source document identifier used as ID prefix */
23
- docId?: string | number;
24
- /** Extra metadata to attach to every chunk */
25
- metadata?: Record<string, unknown>;
26
- /** Characters used to split text, in order of priority */
27
- separators?: string[];
28
- }
29
- declare class DocumentChunker {
30
- private readonly chunkSize;
31
- private readonly chunkOverlap;
32
- private readonly separators;
33
- constructor(chunkSize?: number, chunkOverlap?: number, separators?: string[]);
34
- /**
35
- * Split a single text string into overlapping chunks using a recursive strategy.
36
- * Preserves structural boundaries (Markdown headers) where possible.
37
- */
38
- chunk(text: string, options?: ChunkOptions): Chunk[];
39
- private recursiveSplit;
40
- chunkMany(documents: Array<{
41
- content: string;
42
- docId?: string | number;
43
- metadata?: Record<string, unknown>;
44
- }>): Chunk[];
45
- }
46
-
47
- /**
48
- * Pipeline — orchestrates the RAG flow: Embed → Search → Augment → Generate.
49
- *
50
- * Features:
51
- * - Lazy initialization of providers
52
- * - Batch processing with retry logic
53
- * - Smart embedding strategy (integrated / separate / external)
54
- * - Error recovery for transient failures
55
- * - Multi-tenancy support via namespacing
56
- * - LRU-bounded embedding cache (max 500 entries, prevents memory leaks)
57
- * - Full observability tracing (latency, tokens, hallucination scoring)
58
- */
59
- declare class Pipeline {
60
- private config;
61
- private vectorDB;
62
- private graphDB?;
63
- private llmProvider;
64
- private embeddingProvider;
65
- private llmRouter;
66
- private chunker;
67
- private llamaIngestor?;
68
- private entityExtractor?;
69
- private reranker;
70
- private agent?;
71
- private mcpRegistry?;
72
- private multiAgentCoordinator?;
73
- /** LRU-bounded cache: avoids re-embedding identical queries within the same process. */
74
- private embeddingCache;
75
- private initialised;
76
- /** Namespace-specific static cold context cache for CAG */
77
- private coldContexts;
78
- constructor(config: RagConfig);
79
- /**
80
- * Expose the underlying LLM provider (set after initialize()).
81
- * Used by the stream handler to pass to UITransformer.analyzeAndDecide().
82
- */
83
- getLLMProvider(): ILLMProvider | undefined;
84
- initialize(): Promise<void>;
85
- private loadColdContext;
86
- /**
87
- * Ingest documents with automatic chunking, embedding, and batch upsert.
88
- */
89
- ingest(documents: IngestDocument[], namespace?: string): Promise<Array<{
90
- docId: string | number;
91
- chunksIngested: number;
92
- }>>;
93
- /** Step 1: Chunk the document content. */
94
- private prepareChunks;
95
- /**
96
- * Step 2: Generate embeddings for chunks with retry logic.
97
- * Uses batchEmbed when available for efficiency; falls back to sequential embedding.
98
- */
99
- private processEmbeddings;
100
- /** Step 3: Upsert chunks to vector database with retry logic. */
101
- private processUpserts;
102
- /** Step 4: Optional graph-based entity extraction and ingestion. */
103
- private processGraphIngestion;
104
- runNormalQuery(question: string, history?: ChatMessage[], namespace?: string): Promise<{
105
- reply: string;
106
- sources: any[];
107
- }>;
108
- ask(question: string, history?: ChatMessage[], namespace?: string): Promise<ChatResponse>;
109
- askStream(question: string, history?: ChatMessage[], namespace?: string): AsyncIterable<string | ChatResponse>;
110
- /**
111
- * High-performance streaming RAG flow.
112
- * Yields text chunks first, then the retrieval metadata + observability trace at the end.
113
- *
114
- * Latency optimizations:
115
- * - Strategy classification runs in parallel with query embedding (saves ~400ms)
116
- * - Hallucination scoring is fire-and-forget (doesn't block metadata yield)
117
- * - UITransformation is computed after text streaming and emitted with metadata
118
- * - SchemaMapper.train runs while answer generation streams
119
- */
120
- askStreamInternal(question: string, history?: ChatMessage[], namespace?: string): AsyncIterable<string | ChatResponse>;
121
- /**
122
- * Universal retrieval method combining all enabled providers.
123
- * Uses an LRU-bounded embedding cache to avoid re-embedding the same query.
124
- */
125
- private generateUiTransformation;
126
- private applyStructuredFilters;
127
- private resolveNumericPredicateValue;
128
- private extractNumericValueFromContent;
129
- private matchesNumericPredicate;
130
- private normalizeComparableField;
131
- private fieldSimilarityScore;
132
- private fieldTokens;
133
- private toFiniteNumber;
134
- retrieve(query: string, options: {
135
- namespace?: string;
136
- topK?: number;
137
- filter?: Record<string, unknown>;
138
- }): Promise<RetrievalResult>;
139
- /** Rewrite the user query for better retrieval performance. */
140
- private rewriteQuery;
141
- /** Generate 3-5 short, relevant questions based on the vector database content. */
142
- getSuggestions(query: string, namespace?: string): Promise<string[]>;
143
- }
144
-
145
- /**
146
- * Public SDK facade matching the prompt-level Retrivora API.
147
- *
148
- * It keeps provider details behind configuration and delegates execution to the
149
- * existing Pipeline implementation.
150
- */
151
- declare class Retrivora {
152
- private readonly pipeline;
153
- readonly config: RagConfig;
154
- constructor(config?: UniversalRagConfig);
155
- initialize(): Promise<void>;
156
- ingest(documents: IngestDocument[], namespace?: string): Promise<Array<{
157
- docId: string | number;
158
- chunksIngested: number;
159
- }>>;
160
- ask(question: string, history?: ChatMessage[], namespace?: string): Promise<ChatResponse>;
161
- askStream(question: string, history?: ChatMessage[], namespace?: string): AsyncIterable<string | ChatResponse>;
162
- getPipeline(): Pipeline;
163
- }
164
-
165
- /**
166
- * Named SDK exceptions make failures machine-readable for host applications.
167
- */
168
- type RetrivoraErrorCode = 'PROVIDER_NOT_FOUND' | 'EMBEDDING_FAILED' | 'RETRIEVAL_FAILED' | 'RATE_LIMITED' | 'CONFIGURATION_ERROR' | 'AUTHENTICATION_ERROR';
169
- declare class RetrivoraError extends Error {
170
- readonly code: RetrivoraErrorCode;
171
- readonly details?: unknown;
172
- constructor(message: string, code: RetrivoraErrorCode, details?: unknown);
173
- }
174
- declare class ProviderNotFoundException extends RetrivoraError {
175
- constructor(providerType: string, provider: string, details?: unknown);
176
- }
177
- declare class EmbeddingFailedException extends RetrivoraError {
178
- constructor(message?: string, details?: unknown);
179
- }
180
- declare class RetrievalException extends RetrivoraError {
181
- constructor(message?: string, details?: unknown);
182
- }
183
- declare class RateLimitException extends RetrivoraError {
184
- constructor(message?: string, details?: unknown);
185
- }
186
- declare class ConfigurationException extends RetrivoraError {
187
- constructor(message: string, details?: unknown);
188
- }
189
- declare class AuthenticationException extends RetrivoraError {
190
- constructor(message?: string, details?: unknown);
191
- }
192
- /**
193
- * Wraps any unknown error into an appropriate RetrivoraError subclass.
194
- */
195
- declare function wrapError(err: unknown, defaultCode: RetrivoraErrorCode, defaultMessage?: string): RetrivoraError;
196
-
197
- export { AuthenticationException as A, type Chunk as C, DocumentChunker as D, EmbeddingFailedException as E, ProviderNotFoundException as P, RateLimitException as R, type ChunkOptions as a, ConfigurationException as b, RetrievalException as c, Retrivora as d, RetrivoraError as e, type RetrivoraErrorCode as f, Pipeline as g, wrapError as w };