rag-lite-ts 1.0.2 → 2.0.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.
Files changed (202) hide show
  1. package/README.md +606 -93
  2. package/dist/cli/indexer.js +192 -4
  3. package/dist/cli/search.js +50 -11
  4. package/dist/cli.js +183 -26
  5. package/dist/core/abstract-embedder.d.ts +125 -0
  6. package/dist/core/abstract-embedder.js +264 -0
  7. package/dist/core/actionable-error-messages.d.ts +60 -0
  8. package/dist/core/actionable-error-messages.js +397 -0
  9. package/dist/core/batch-processing-optimizer.d.ts +155 -0
  10. package/dist/core/batch-processing-optimizer.js +541 -0
  11. package/dist/core/chunker.d.ts +2 -0
  12. package/dist/core/cli-database-utils.d.ts +53 -0
  13. package/dist/core/cli-database-utils.js +239 -0
  14. package/dist/core/config.js +10 -3
  15. package/dist/core/content-errors.d.ts +111 -0
  16. package/dist/core/content-errors.js +362 -0
  17. package/dist/core/content-manager.d.ts +343 -0
  18. package/dist/core/content-manager.js +1504 -0
  19. package/dist/core/content-performance-optimizer.d.ts +150 -0
  20. package/dist/core/content-performance-optimizer.js +516 -0
  21. package/dist/core/content-resolver.d.ts +104 -0
  22. package/dist/core/content-resolver.js +285 -0
  23. package/dist/core/cross-modal-search.d.ts +164 -0
  24. package/dist/core/cross-modal-search.js +342 -0
  25. package/dist/core/database-connection-manager.d.ts +109 -0
  26. package/dist/core/database-connection-manager.js +304 -0
  27. package/dist/core/db.d.ts +141 -2
  28. package/dist/core/db.js +631 -89
  29. package/dist/core/embedder-factory.d.ts +176 -0
  30. package/dist/core/embedder-factory.js +338 -0
  31. package/dist/core/index.d.ts +3 -1
  32. package/dist/core/index.js +4 -1
  33. package/dist/core/ingestion.d.ts +85 -15
  34. package/dist/core/ingestion.js +510 -45
  35. package/dist/core/lazy-dependency-loader.d.ts +152 -0
  36. package/dist/core/lazy-dependency-loader.js +453 -0
  37. package/dist/core/mode-detection-service.d.ts +150 -0
  38. package/dist/core/mode-detection-service.js +565 -0
  39. package/dist/core/mode-model-validator.d.ts +92 -0
  40. package/dist/core/mode-model-validator.js +203 -0
  41. package/dist/core/model-registry.d.ts +120 -0
  42. package/dist/core/model-registry.js +415 -0
  43. package/dist/core/model-validator.d.ts +217 -0
  44. package/dist/core/model-validator.js +782 -0
  45. package/dist/core/polymorphic-search-factory.d.ts +154 -0
  46. package/dist/core/polymorphic-search-factory.js +344 -0
  47. package/dist/core/raglite-paths.d.ts +121 -0
  48. package/dist/core/raglite-paths.js +145 -0
  49. package/dist/core/reranking-config.d.ts +42 -0
  50. package/dist/core/reranking-config.js +156 -0
  51. package/dist/core/reranking-factory.d.ts +92 -0
  52. package/dist/core/reranking-factory.js +591 -0
  53. package/dist/core/reranking-strategies.d.ts +325 -0
  54. package/dist/core/reranking-strategies.js +720 -0
  55. package/dist/core/resource-cleanup.d.ts +163 -0
  56. package/dist/core/resource-cleanup.js +371 -0
  57. package/dist/core/resource-manager.d.ts +212 -0
  58. package/dist/core/resource-manager.js +564 -0
  59. package/dist/core/search.d.ts +28 -1
  60. package/dist/core/search.js +83 -5
  61. package/dist/core/streaming-operations.d.ts +145 -0
  62. package/dist/core/streaming-operations.js +409 -0
  63. package/dist/core/types.d.ts +3 -0
  64. package/dist/core/universal-embedder.d.ts +177 -0
  65. package/dist/core/universal-embedder.js +139 -0
  66. package/dist/core/validation-messages.d.ts +99 -0
  67. package/dist/core/validation-messages.js +334 -0
  68. package/dist/core/vector-index.js +7 -8
  69. package/dist/factories/index.d.ts +1 -1
  70. package/dist/factories/text-factory.d.ts +128 -34
  71. package/dist/factories/text-factory.js +346 -97
  72. package/dist/file-processor.d.ts +88 -2
  73. package/dist/file-processor.js +720 -17
  74. package/dist/index.d.ts +9 -0
  75. package/dist/index.js +11 -0
  76. package/dist/ingestion.d.ts +16 -0
  77. package/dist/ingestion.js +21 -0
  78. package/dist/mcp-server.d.ts +35 -3
  79. package/dist/mcp-server.js +1107 -31
  80. package/dist/multimodal/clip-embedder.d.ts +314 -0
  81. package/dist/multimodal/clip-embedder.js +945 -0
  82. package/dist/multimodal/index.d.ts +6 -0
  83. package/dist/multimodal/index.js +6 -0
  84. package/dist/run-error-recovery-tests.d.ts +7 -0
  85. package/dist/run-error-recovery-tests.js +101 -0
  86. package/dist/search.d.ts +26 -0
  87. package/dist/search.js +54 -1
  88. package/dist/test-utils.d.ts +8 -26
  89. package/dist/text/chunker.d.ts +1 -0
  90. package/dist/text/embedder.js +15 -8
  91. package/dist/text/index.d.ts +1 -0
  92. package/dist/text/index.js +1 -0
  93. package/dist/text/reranker.d.ts +1 -2
  94. package/dist/text/reranker.js +17 -47
  95. package/dist/text/sentence-transformer-embedder.d.ts +96 -0
  96. package/dist/text/sentence-transformer-embedder.js +340 -0
  97. package/dist/types.d.ts +39 -0
  98. package/dist/utils/vector-math.d.ts +31 -0
  99. package/dist/utils/vector-math.js +70 -0
  100. package/package.json +15 -3
  101. package/dist/api-errors.d.ts.map +0 -1
  102. package/dist/api-errors.js.map +0 -1
  103. package/dist/cli/indexer.d.ts.map +0 -1
  104. package/dist/cli/indexer.js.map +0 -1
  105. package/dist/cli/search.d.ts.map +0 -1
  106. package/dist/cli/search.js.map +0 -1
  107. package/dist/cli.d.ts.map +0 -1
  108. package/dist/cli.js.map +0 -1
  109. package/dist/config.d.ts.map +0 -1
  110. package/dist/config.js.map +0 -1
  111. package/dist/core/adapters.d.ts.map +0 -1
  112. package/dist/core/adapters.js.map +0 -1
  113. package/dist/core/chunker.d.ts.map +0 -1
  114. package/dist/core/chunker.js.map +0 -1
  115. package/dist/core/config.d.ts.map +0 -1
  116. package/dist/core/config.js.map +0 -1
  117. package/dist/core/db.d.ts.map +0 -1
  118. package/dist/core/db.js.map +0 -1
  119. package/dist/core/error-handler.d.ts.map +0 -1
  120. package/dist/core/error-handler.js.map +0 -1
  121. package/dist/core/index.d.ts.map +0 -1
  122. package/dist/core/index.js.map +0 -1
  123. package/dist/core/ingestion.d.ts.map +0 -1
  124. package/dist/core/ingestion.js.map +0 -1
  125. package/dist/core/interfaces.d.ts.map +0 -1
  126. package/dist/core/interfaces.js.map +0 -1
  127. package/dist/core/path-manager.d.ts.map +0 -1
  128. package/dist/core/path-manager.js.map +0 -1
  129. package/dist/core/search-example.d.ts +0 -25
  130. package/dist/core/search-example.d.ts.map +0 -1
  131. package/dist/core/search-example.js +0 -138
  132. package/dist/core/search-example.js.map +0 -1
  133. package/dist/core/search-pipeline-example.d.ts +0 -21
  134. package/dist/core/search-pipeline-example.d.ts.map +0 -1
  135. package/dist/core/search-pipeline-example.js +0 -188
  136. package/dist/core/search-pipeline-example.js.map +0 -1
  137. package/dist/core/search-pipeline.d.ts.map +0 -1
  138. package/dist/core/search-pipeline.js.map +0 -1
  139. package/dist/core/search.d.ts.map +0 -1
  140. package/dist/core/search.js.map +0 -1
  141. package/dist/core/types.d.ts.map +0 -1
  142. package/dist/core/types.js.map +0 -1
  143. package/dist/core/vector-index.d.ts.map +0 -1
  144. package/dist/core/vector-index.js.map +0 -1
  145. package/dist/dom-polyfills.d.ts.map +0 -1
  146. package/dist/dom-polyfills.js.map +0 -1
  147. package/dist/examples/clean-api-examples.d.ts +0 -44
  148. package/dist/examples/clean-api-examples.d.ts.map +0 -1
  149. package/dist/examples/clean-api-examples.js +0 -206
  150. package/dist/examples/clean-api-examples.js.map +0 -1
  151. package/dist/factories/index.d.ts.map +0 -1
  152. package/dist/factories/index.js.map +0 -1
  153. package/dist/factories/text-factory.d.ts.map +0 -1
  154. package/dist/factories/text-factory.js.map +0 -1
  155. package/dist/file-processor.d.ts.map +0 -1
  156. package/dist/file-processor.js.map +0 -1
  157. package/dist/index-manager.d.ts.map +0 -1
  158. package/dist/index-manager.js.map +0 -1
  159. package/dist/index.d.ts.map +0 -1
  160. package/dist/index.js.map +0 -1
  161. package/dist/indexer.d.ts.map +0 -1
  162. package/dist/indexer.js.map +0 -1
  163. package/dist/ingestion.d.ts.map +0 -1
  164. package/dist/ingestion.js.map +0 -1
  165. package/dist/mcp-server.d.ts.map +0 -1
  166. package/dist/mcp-server.js.map +0 -1
  167. package/dist/preprocess.d.ts.map +0 -1
  168. package/dist/preprocess.js.map +0 -1
  169. package/dist/preprocessors/index.d.ts.map +0 -1
  170. package/dist/preprocessors/index.js.map +0 -1
  171. package/dist/preprocessors/mdx.d.ts.map +0 -1
  172. package/dist/preprocessors/mdx.js.map +0 -1
  173. package/dist/preprocessors/mermaid.d.ts.map +0 -1
  174. package/dist/preprocessors/mermaid.js.map +0 -1
  175. package/dist/preprocessors/registry.d.ts.map +0 -1
  176. package/dist/preprocessors/registry.js.map +0 -1
  177. package/dist/search-standalone.d.ts.map +0 -1
  178. package/dist/search-standalone.js.map +0 -1
  179. package/dist/search.d.ts.map +0 -1
  180. package/dist/search.js.map +0 -1
  181. package/dist/test-utils.d.ts.map +0 -1
  182. package/dist/test-utils.js.map +0 -1
  183. package/dist/text/chunker.d.ts.map +0 -1
  184. package/dist/text/chunker.js.map +0 -1
  185. package/dist/text/embedder.d.ts.map +0 -1
  186. package/dist/text/embedder.js.map +0 -1
  187. package/dist/text/index.d.ts.map +0 -1
  188. package/dist/text/index.js.map +0 -1
  189. package/dist/text/preprocessors/index.d.ts.map +0 -1
  190. package/dist/text/preprocessors/index.js.map +0 -1
  191. package/dist/text/preprocessors/mdx.d.ts.map +0 -1
  192. package/dist/text/preprocessors/mdx.js.map +0 -1
  193. package/dist/text/preprocessors/mermaid.d.ts.map +0 -1
  194. package/dist/text/preprocessors/mermaid.js.map +0 -1
  195. package/dist/text/preprocessors/registry.d.ts.map +0 -1
  196. package/dist/text/preprocessors/registry.js.map +0 -1
  197. package/dist/text/reranker.d.ts.map +0 -1
  198. package/dist/text/reranker.js.map +0 -1
  199. package/dist/text/tokenizer.d.ts.map +0 -1
  200. package/dist/text/tokenizer.js.map +0 -1
  201. package/dist/types.d.ts.map +0 -1
  202. package/dist/types.js.map +0 -1
@@ -0,0 +1,334 @@
1
+ /**
2
+ * CORE MODULE — Validation Messages and Error Descriptions
3
+ * Comprehensive error messages and user guidance for model validation
4
+ * Provides helpful, actionable error messages with troubleshooting steps
5
+ */
6
+ import { ModelRegistry } from './model-registry.js';
7
+ // =============================================================================
8
+ // ERROR MESSAGE TEMPLATES
9
+ // =============================================================================
10
+ /**
11
+ * Error message templates for different validation scenarios
12
+ */
13
+ export const ERROR_MESSAGES = {
14
+ MODEL_NOT_FOUND: (modelName, suggestions) => ({
15
+ title: `Model '${modelName}' not found`,
16
+ description: `The specified model is not supported by the Chameleon architecture.`,
17
+ details: [
18
+ `Model '${modelName}' is not in the supported models registry.`,
19
+ `This could be due to a typo in the model name or the model not being compatible with transformers.js.`
20
+ ],
21
+ suggestions: suggestions.length > 0 ? [
22
+ `Did you mean one of these models?`,
23
+ ...suggestions.map(s => ` • ${s}`)
24
+ ] : [
25
+ `Available models:`,
26
+ ...ModelRegistry.getSupportedModels().map(s => ` • ${s}`)
27
+ ],
28
+ actions: [
29
+ `Check the model name for typos`,
30
+ `Use 'ModelRegistry.getSupportedModels()' to see all available models`,
31
+ `Visit the documentation for the latest supported models list`
32
+ ]
33
+ }),
34
+ TRANSFORMERS_VERSION_INCOMPATIBLE: (modelName, required, current) => ({
35
+ title: `Transformers.js version incompatible`,
36
+ description: `Model '${modelName}' requires a newer version of transformers.js.`,
37
+ details: [
38
+ `Required version: ${required}`,
39
+ `Current version: ${current}`,
40
+ `The model uses features not available in the current transformers.js version.`
41
+ ],
42
+ suggestions: [
43
+ `Upgrade transformers.js to the latest version:`,
44
+ ` npm install @huggingface/transformers@latest`,
45
+ ``,
46
+ `Or install a specific compatible version:`,
47
+ ` npm install @huggingface/transformers@${required.replace(/[>=<~^]/g, '')}`
48
+ ],
49
+ actions: [
50
+ `Update your package.json dependencies`,
51
+ `Run npm install to update transformers.js`,
52
+ `Restart your application after updating`
53
+ ]
54
+ }),
55
+ INSUFFICIENT_MEMORY: (modelName, required, available) => ({
56
+ title: `Insufficient memory for model`,
57
+ description: `Model '${modelName}' requires more memory than available.`,
58
+ details: [
59
+ `Required memory: ${required}MB`,
60
+ `Available memory: ${available}MB`,
61
+ `Shortfall: ${required - available}MB`
62
+ ],
63
+ suggestions: [
64
+ `Consider using a smaller model variant:`,
65
+ ...ModelRegistry.getSupportedModels().filter(name => {
66
+ const info = ModelRegistry.getModelInfo(name);
67
+ return info &&
68
+ info.requirements.minimumMemory &&
69
+ info.requirements.minimumMemory <= available;
70
+ }).map(name => ` • ${name}`),
71
+ ``,
72
+ `Or increase available memory by:`,
73
+ ` • Closing other applications`,
74
+ ` • Increasing Node.js memory limit: --max-old-space-size=${required + 512}`,
75
+ ` • Using a machine with more RAM`
76
+ ],
77
+ actions: [
78
+ `Free up system memory`,
79
+ `Choose a more memory-efficient model`,
80
+ `Consider using model quantization if available`
81
+ ]
82
+ }),
83
+ PLATFORM_UNSUPPORTED: (modelName, currentPlatform, supportedPlatforms) => ({
84
+ title: `Platform not supported`,
85
+ description: `Model '${modelName}' is not supported on ${currentPlatform}.`,
86
+ details: [
87
+ `Current platform: ${currentPlatform}`,
88
+ `Supported platforms: ${supportedPlatforms.join(', ')}`,
89
+ `The model may use platform-specific features or optimizations.`
90
+ ],
91
+ suggestions: [
92
+ `Try running on a supported platform:`,
93
+ ...supportedPlatforms.map(platform => ` • ${platform}`),
94
+ ``,
95
+ `Or use a platform-agnostic model:`,
96
+ ...ModelRegistry.getSupportedModels().filter(name => {
97
+ const info = ModelRegistry.getModelInfo(name);
98
+ return info &&
99
+ info.requirements.platformSupport &&
100
+ info.requirements.platformSupport.includes(currentPlatform);
101
+ }).slice(0, 3).map(name => ` • ${name}`)
102
+ ],
103
+ actions: [
104
+ `Switch to a supported platform`,
105
+ `Use a different model that supports your platform`,
106
+ `Check if there are platform-specific installation instructions`
107
+ ]
108
+ }),
109
+ FEATURES_MISSING: (modelName, missingFeatures) => ({
110
+ title: `Required features not available`,
111
+ description: `Model '${modelName}' requires features not available in current transformers.js version.`,
112
+ details: [
113
+ `Missing features: ${missingFeatures.join(', ')}`,
114
+ `These features are required for the model to function properly.`
115
+ ],
116
+ suggestions: [
117
+ `Upgrade transformers.js to get missing features:`,
118
+ ` npm install @huggingface/transformers@latest`,
119
+ ``,
120
+ `Or use a model that doesn't require these features:`,
121
+ ...ModelRegistry.getSupportedModels().filter(name => {
122
+ const info = ModelRegistry.getModelInfo(name);
123
+ return info &&
124
+ (!info.requirements.requiredFeatures ||
125
+ info.requirements.requiredFeatures.every(f => !missingFeatures.includes(f)));
126
+ }).slice(0, 3).map(name => ` • ${name}`)
127
+ ],
128
+ actions: [
129
+ `Update transformers.js to the latest version`,
130
+ `Check the transformers.js changelog for feature availability`,
131
+ `Use an alternative model with fewer feature requirements`
132
+ ]
133
+ }),
134
+ CONTENT_TYPE_UNSUPPORTED: (contentType, modelName, supportedTypes) => ({
135
+ title: `Content type not supported`,
136
+ description: `Model '${modelName}' does not support '${contentType}' content.`,
137
+ details: [
138
+ `Requested content type: ${contentType}`,
139
+ `Supported content types: ${supportedTypes.join(', ')}`,
140
+ `The model was not trained to handle this type of content.`
141
+ ],
142
+ suggestions: [
143
+ `Use a model that supports '${contentType}' content:`,
144
+ ...ModelRegistry.getModelsByContentType(contentType).slice(0, 3).map(name => ` • ${name}`),
145
+ ``,
146
+ `Or convert your content to a supported type:`,
147
+ ...supportedTypes.map(type => ` • Convert to ${type}`)
148
+ ],
149
+ actions: [
150
+ `Choose a multimodal model for mixed content types`,
151
+ `Preprocess your content to match supported types`,
152
+ `Use separate models for different content types`
153
+ ]
154
+ })
155
+ };
156
+ // =============================================================================
157
+ // WARNING MESSAGE TEMPLATES
158
+ // =============================================================================
159
+ /**
160
+ * Warning message templates for non-critical issues
161
+ */
162
+ export const WARNING_MESSAGES = {
163
+ HIGH_MEMORY_USAGE: (modelName, memoryMB) => ({
164
+ title: `High memory usage`,
165
+ message: `Model '${modelName}' requires ${memoryMB}MB of memory, which may impact performance.`,
166
+ suggestions: [
167
+ `Monitor system memory usage during operation`,
168
+ `Consider using a smaller model variant if performance is affected`,
169
+ `Ensure sufficient swap space is available`
170
+ ]
171
+ }),
172
+ LIMITED_BATCH_SIZE: (modelName, maxBatchSize) => ({
173
+ title: `Limited batch processing`,
174
+ message: `Model '${modelName}' supports maximum batch size of ${maxBatchSize}.`,
175
+ suggestions: [
176
+ `Use smaller batch sizes for optimal performance`,
177
+ `Process large datasets in smaller chunks`,
178
+ `Consider parallel processing with multiple model instances`
179
+ ]
180
+ }),
181
+ EXPERIMENTAL_FEATURES: (modelName, features) => ({
182
+ title: `Experimental features in use`,
183
+ message: `Model '${modelName}' uses experimental features: ${features.join(', ')}.`,
184
+ suggestions: [
185
+ `Test thoroughly before using in production`,
186
+ `Monitor for unexpected behavior or errors`,
187
+ `Have fallback options ready`,
188
+ `Check for updates that may stabilize these features`
189
+ ]
190
+ }),
191
+ PERFORMANCE_IMPACT: (modelName, reason) => ({
192
+ title: `Potential performance impact`,
193
+ message: `Model '${modelName}' may have reduced performance: ${reason}.`,
194
+ suggestions: [
195
+ `Monitor processing times and resource usage`,
196
+ `Consider using GPU acceleration if available`,
197
+ `Optimize batch sizes for your use case`,
198
+ `Profile your application to identify bottlenecks`
199
+ ]
200
+ })
201
+ };
202
+ // =============================================================================
203
+ // MESSAGE FORMATTING UTILITIES
204
+ // =============================================================================
205
+ /**
206
+ * Format an error message for console output
207
+ */
208
+ export function formatErrorMessage(error) {
209
+ const lines = [];
210
+ lines.push(`❌ ${error.title}`);
211
+ lines.push('');
212
+ lines.push(error.description);
213
+ if (error.details.length > 0) {
214
+ lines.push('');
215
+ lines.push('Details:');
216
+ error.details.forEach(detail => lines.push(` ${detail}`));
217
+ }
218
+ if (error.suggestions.length > 0) {
219
+ lines.push('');
220
+ lines.push('Suggestions:');
221
+ error.suggestions.forEach(suggestion => lines.push(` ${suggestion}`));
222
+ }
223
+ if (error.actions.length > 0) {
224
+ lines.push('');
225
+ lines.push('Actions:');
226
+ error.actions.forEach((action, index) => lines.push(` ${index + 1}. ${action}`));
227
+ }
228
+ return lines.join('\n');
229
+ }
230
+ /**
231
+ * Format a warning message for console output
232
+ */
233
+ export function formatWarningMessage(warning) {
234
+ const lines = [];
235
+ lines.push(`⚠️ ${warning.title}`);
236
+ lines.push('');
237
+ lines.push(warning.message);
238
+ if (warning.suggestions.length > 0) {
239
+ lines.push('');
240
+ lines.push('Suggestions:');
241
+ warning.suggestions.forEach(suggestion => lines.push(` • ${suggestion}`));
242
+ }
243
+ return lines.join('\n');
244
+ }
245
+ /**
246
+ * Create a comprehensive error message for model validation failure
247
+ */
248
+ export function createValidationErrorMessage(modelName, errorType, context = {}) {
249
+ switch (errorType) {
250
+ case 'not_found':
251
+ return formatErrorMessage(ERROR_MESSAGES.MODEL_NOT_FOUND(modelName, context.suggestions || []));
252
+ case 'version_incompatible':
253
+ return formatErrorMessage(ERROR_MESSAGES.TRANSFORMERS_VERSION_INCOMPATIBLE(modelName, context.required || 'unknown', context.current || 'unknown'));
254
+ case 'insufficient_memory':
255
+ return formatErrorMessage(ERROR_MESSAGES.INSUFFICIENT_MEMORY(modelName, context.required || 0, context.available || 0));
256
+ case 'platform_unsupported':
257
+ return formatErrorMessage(ERROR_MESSAGES.PLATFORM_UNSUPPORTED(modelName, context.currentPlatform || 'unknown', context.supportedPlatforms || []));
258
+ case 'features_missing':
259
+ return formatErrorMessage(ERROR_MESSAGES.FEATURES_MISSING(modelName, context.missingFeatures || []));
260
+ case 'content_type_unsupported':
261
+ return formatErrorMessage(ERROR_MESSAGES.CONTENT_TYPE_UNSUPPORTED(context.contentType || 'unknown', modelName, context.supportedTypes || []));
262
+ default:
263
+ return `❌ Validation failed for model '${modelName}': ${errorType}`;
264
+ }
265
+ }
266
+ /**
267
+ * Create helpful suggestions based on model type and use case
268
+ */
269
+ export function createModelSuggestions(modelType, contentTypes, memoryLimit) {
270
+ const suggestions = [];
271
+ if (modelType === 'sentence-transformer') {
272
+ suggestions.push('For text-only tasks, sentence-transformers are most efficient');
273
+ suggestions.push('all-MiniLM-L6-v2 offers the best balance of speed and accuracy');
274
+ suggestions.push('all-mpnet-base-v2 provides higher accuracy but uses more memory');
275
+ }
276
+ if (modelType === 'clip') {
277
+ suggestions.push('CLIP models support both text and image content');
278
+ suggestions.push('clip-vit-base-patch32 is recommended for most use cases');
279
+ suggestions.push('patch16 variants are more accurate but slower');
280
+ }
281
+ if (contentTypes?.includes('image')) {
282
+ suggestions.push('Multimodal content requires CLIP models');
283
+ suggestions.push('Ensure images are in supported formats (jpg, png, webp)');
284
+ suggestions.push('Consider image preprocessing for better results');
285
+ }
286
+ if (memoryLimit && memoryLimit < 1024) {
287
+ suggestions.push('Low memory environments should use smaller models');
288
+ suggestions.push('Consider model quantization to reduce memory usage');
289
+ suggestions.push('Process content in smaller batches');
290
+ }
291
+ return suggestions;
292
+ }
293
+ /**
294
+ * Get troubleshooting steps for common issues
295
+ */
296
+ export function getTroubleshootingSteps(issue) {
297
+ const steps = {
298
+ 'model_loading_failed': [
299
+ 'Check internet connection for model download',
300
+ 'Verify model name spelling and availability',
301
+ 'Ensure sufficient disk space for model cache',
302
+ 'Try clearing the model cache and re-downloading',
303
+ 'Check transformers.js version compatibility'
304
+ ],
305
+ 'out_of_memory': [
306
+ 'Reduce batch size for processing',
307
+ 'Use a smaller model variant',
308
+ 'Increase Node.js memory limit with --max-old-space-size',
309
+ 'Close other memory-intensive applications',
310
+ 'Consider using model quantization'
311
+ ],
312
+ 'slow_performance': [
313
+ 'Use GPU acceleration if available',
314
+ 'Optimize batch sizes for your hardware',
315
+ 'Consider using a smaller, faster model',
316
+ 'Profile your code to identify bottlenecks',
317
+ 'Use appropriate hardware for your model size'
318
+ ],
319
+ 'compatibility_issues': [
320
+ 'Update transformers.js to the latest version',
321
+ 'Check model requirements against your environment',
322
+ 'Verify platform compatibility (Node.js vs browser)',
323
+ 'Test with a known working model first',
324
+ 'Check for conflicting dependencies'
325
+ ]
326
+ };
327
+ return steps[issue] || [
328
+ 'Check the documentation for your specific issue',
329
+ 'Search for similar issues in the project repository',
330
+ 'Ensure all dependencies are up to date',
331
+ 'Try with a minimal test case to isolate the problem'
332
+ ];
333
+ }
334
+ //# sourceMappingURL=validation-messages.js.map
@@ -5,6 +5,7 @@
5
5
  import { readFileSync, writeFileSync, existsSync } from 'fs';
6
6
  import { JSDOM } from 'jsdom';
7
7
  import { ErrorCategory, ErrorSeverity, safeExecute } from './error-handler.js';
8
+ import { createMissingFileError, createDimensionMismatchError } from './actionable-error-messages.js';
8
9
  // Set up browser-like environment for hnswlib-wasm
9
10
  if (typeof window === 'undefined') {
10
11
  const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', {
@@ -103,7 +104,9 @@ export class VectorIndex {
103
104
  */
104
105
  async loadIndex() {
105
106
  if (!existsSync(this.indexPath)) {
106
- throw new Error(`Index file not found: ${this.indexPath}`);
107
+ throw createMissingFileError(this.indexPath, 'index', {
108
+ operationContext: 'VectorIndex.loadIndex'
109
+ });
107
110
  }
108
111
  try {
109
112
  // Load the hnswlib module
@@ -162,11 +165,7 @@ export class VectorIndex {
162
165
  if (stored.vectors && stored.vectors.length > 0) {
163
166
  console.log(` Actual vector length: ${stored.vectors[0].vector.length}`);
164
167
  }
165
- throw new Error(`Vector dimension mismatch!\n` +
166
- `Index was created with ${stored.dimensions} dimensions\n` +
167
- `Current model expects ${this.options.dimensions} dimensions\n` +
168
- `This indicates the embedding model has changed.\n` +
169
- `Please rebuild the index with the current model.`);
168
+ throw createDimensionMismatchError(this.options.dimensions, stored.dimensions, 'vector index loading', { operationContext: 'VectorIndex.loadIndex' });
170
169
  }
171
170
  // Update options from stored data
172
171
  this.options.maxElements = stored.maxElements || this.options.maxElements;
@@ -227,7 +226,7 @@ export class VectorIndex {
227
226
  throw new Error('Index not initialized');
228
227
  }
229
228
  if (vector.length !== this.options.dimensions) {
230
- throw new Error(`Vector dimension mismatch: expected ${this.options.dimensions}, got ${vector.length}`);
229
+ throw createDimensionMismatchError(this.options.dimensions, vector.length, 'vector addition', { operationContext: 'VectorIndex.addVector' });
231
230
  }
232
231
  try {
233
232
  this.index.addPoint(vector, embeddingId, false);
@@ -255,7 +254,7 @@ export class VectorIndex {
255
254
  throw new Error('Index not initialized');
256
255
  }
257
256
  if (queryVector.length !== this.options.dimensions) {
258
- throw new Error(`Query vector dimension mismatch: expected ${this.options.dimensions}, got ${queryVector.length}`);
257
+ throw createDimensionMismatchError(this.options.dimensions, queryVector.length, 'vector search', { operationContext: 'VectorIndex.search' });
259
258
  }
260
259
  if (this.currentSize === 0) {
261
260
  return { neighbors: [], distances: [] };
@@ -36,7 +36,7 @@
36
36
  * ```
37
37
  */
38
38
  export { TextSearchFactory, TextIngestionFactory, TextRAGFactory, TextFactoryHelpers } from './text-factory.js';
39
- export type { TextSearchOptions, TextIngestionOptions } from './text-factory.js';
39
+ export type { TextSearchOptions, TextIngestionOptions, ContentSystemConfig } from './text-factory.js';
40
40
  export { TextSearchFactory as SearchFactory } from './text-factory.js';
41
41
  export { TextIngestionFactory as IngestionFactory } from './text-factory.js';
42
42
  export { TextRAGFactory as RAGFactory } from './text-factory.js';
@@ -5,10 +5,21 @@
5
5
  * FACTORY PATTERN BENEFITS:
6
6
  * - Abstracts complex initialization (model loading, database setup, index initialization)
7
7
  * - Provides simple API for common use cases while preserving access to dependency injection
8
- * - Handles error recovery and validation
8
+ * - Clear validation and error handling without fallback mechanisms
9
9
  * - Supports different embedding models and configurations
10
10
  * - Enables clean separation between simple usage and advanced customization
11
11
  *
12
+ * MODE SELECTION GUIDE:
13
+ * - Text Mode (default): Optimized for text-only content
14
+ * - Uses sentence-transformer models (fast, accurate for text)
15
+ * - Images converted to text descriptions
16
+ * - Best for: document search, text clustering, semantic similarity
17
+ *
18
+ * - Multimodal Mode: Optimized for mixed text/image content
19
+ * - Uses CLIP models (unified embedding space)
20
+ * - True cross-modal search (text finds images, images find text)
21
+ * - Best for: image search, visual QA, multimodal retrieval
22
+ *
12
23
  * USAGE PATTERNS:
13
24
  *
14
25
  * 1. Simple Search Setup:
@@ -43,15 +54,31 @@
43
54
  * const results = await searchEngine.search('query');
44
55
  * ```
45
56
  *
46
- * 4. Error Recovery:
57
+ * 4. Clear Error Handling:
47
58
  * ```typescript
48
- * // Create with automatic fallback options
49
- * const search = await TextFactoryHelpers.createSearchWithFallback(
59
+ * // Create with clear validation and error reporting
60
+ * const search = await TextFactoryHelpers.createSearchWithValidation(
50
61
  * './index.bin',
51
62
  * './db.sqlite',
52
- * { enableReranking: true } // Will fallback to disabled if reranking fails
63
+ * { enableReranking: true } // Clear errors if issues occur
53
64
  * );
54
65
  * ```
66
+ *
67
+ * 5. Mode Selection:
68
+ * ```typescript
69
+ * // Text mode (default) - optimized for text-only content
70
+ * const textIngestion = await TextIngestionFactory.create('./db.sqlite', './index.bin', {
71
+ * mode: 'text',
72
+ * embeddingModel: 'sentence-transformers/all-MiniLM-L6-v2'
73
+ * });
74
+ *
75
+ * // Multimodal mode - enables cross-modal search
76
+ * const multimodalIngestion = await TextIngestionFactory.create('./db.sqlite', './index.bin', {
77
+ * mode: 'multimodal',
78
+ * embeddingModel: 'Xenova/clip-vit-base-patch32',
79
+ * rerankingStrategy: 'text-derived'
80
+ * });
81
+ * ```
55
82
  */
56
83
  import { SearchEngine } from '../core/search.js';
57
84
  import { IngestionPipeline } from '../core/ingestion.js';
@@ -70,6 +97,21 @@ export interface TextSearchOptions {
70
97
  /** Top-k results to return (default: from config) */
71
98
  topK?: number;
72
99
  }
100
+ /**
101
+ * Content system configuration options
102
+ */
103
+ export interface ContentSystemConfig {
104
+ /** Content directory path (default: '.raglite/content') */
105
+ contentDir?: string;
106
+ /** Maximum file size in bytes (default: 50MB) */
107
+ maxFileSize?: number;
108
+ /** Maximum content directory size in bytes (default: 2GB) */
109
+ maxContentDirSize?: number;
110
+ /** Enable content deduplication (default: true) */
111
+ enableDeduplication?: boolean;
112
+ /** Enable storage tracking (default: true) */
113
+ enableStorageTracking?: boolean;
114
+ }
73
115
  /**
74
116
  * Options for text ingestion factory
75
117
  */
@@ -84,17 +126,30 @@ export interface TextIngestionOptions {
84
126
  chunkOverlap?: number;
85
127
  /** Whether to force rebuild the index */
86
128
  forceRebuild?: boolean;
129
+ /** Mode for the ingestion pipeline (text or multimodal) */
130
+ mode?: 'text' | 'multimodal';
131
+ /** Reranking strategy for multimodal mode */
132
+ rerankingStrategy?: 'cross-encoder' | 'text-derived' | 'metadata' | 'hybrid' | 'disabled';
133
+ /** Content system configuration */
134
+ contentSystemConfig?: ContentSystemConfig;
87
135
  }
88
136
  /**
89
137
  * Factory for creating text-based SearchEngine instances
90
138
  * Handles model loading, database initialization, and index setup
91
139
  *
92
140
  * This factory abstracts the complex initialization process required for text search:
93
- * 1. Loads and validates text embedding models
94
- * 2. Optionally loads reranking models with fallback handling
95
- * 3. Establishes database connections and initializes schema
96
- * 4. Loads vector indexes with proper model compatibility checking
97
- * 5. Creates SearchEngine with proper dependency injection
141
+ * 1. Auto-detects embedding model from database configuration
142
+ * 2. Validates mode-model compatibility (no fallback mechanisms)
143
+ * 3. Loads embedding models with clear error reporting
144
+ * 4. Optionally loads reranking models based on configuration
145
+ * 5. Establishes database connections and initializes schema
146
+ * 6. Loads vector indexes with proper model compatibility checking
147
+ * 7. Creates SearchEngine with proper dependency injection
148
+ *
149
+ * Mode Support:
150
+ * - Automatically detects mode from database (text or multimodal)
151
+ * - Each mode uses its optimal implementation without fallbacks
152
+ * - Clear validation ensures mode-model compatibility
98
153
  *
99
154
  * @example
100
155
  * ```typescript
@@ -122,7 +177,7 @@ export declare class TextSearchFactory {
122
177
  * This method handles the complete initialization process:
123
178
  * - Validates that required files exist
124
179
  * - Loads text embedding model (with lazy initialization)
125
- * - Optionally loads reranking model (with graceful fallback)
180
+ * - Optionally loads reranking model (with clear error reporting)
126
181
  * - Opens database connection and initializes schema
127
182
  * - Loads vector index with compatibility validation
128
183
  * - Creates SearchEngine with dependency injection
@@ -187,10 +242,18 @@ export declare class TextSearchFactory {
187
242
  *
188
243
  * This factory abstracts the complex initialization process required for text ingestion:
189
244
  * 1. Creates necessary directories if they don't exist
190
- * 2. Loads and validates text embedding models
191
- * 3. Establishes database connections and initializes schema
192
- * 4. Creates or loads vector indexes with proper configuration
193
- * 5. Creates IngestionPipeline with proper dependency injection
245
+ * 2. Validates mode-model compatibility (no fallback mechanisms)
246
+ * 3. Loads and validates embedding models with clear error reporting
247
+ * 4. Establishes database connections and initializes schema
248
+ * 5. Stores mode configuration in database for automatic detection
249
+ * 6. Creates or loads vector indexes with proper configuration
250
+ * 7. Creates IngestionPipeline with proper dependency injection
251
+ *
252
+ * Mode Configuration:
253
+ * - Text Mode (default): Uses sentence-transformer models for text-only content
254
+ * - Multimodal Mode: Uses CLIP models for mixed text/image content
255
+ * - Mode is stored in database and auto-detected during search
256
+ * - Clear validation prevents mode-model mismatches
194
257
  *
195
258
  * @example
196
259
  * ```typescript
@@ -232,20 +295,39 @@ export declare class TextIngestionFactory {
232
295
  * @param options.chunkSize - Override chunk size (default: from config)
233
296
  * @param options.chunkOverlap - Override chunk overlap (default: from config)
234
297
  * @param options.forceRebuild - Force rebuild of existing index (default: false)
298
+ * @param options.contentSystemConfig - Content system configuration options
299
+ * @param options.contentSystemConfig.contentDir - Content directory path (default: '.raglite/content')
300
+ * @param options.contentSystemConfig.maxFileSize - Maximum file size in bytes (default: 50MB)
301
+ * @param options.contentSystemConfig.maxContentDirSize - Maximum content directory size (default: 2GB)
302
+ * @param options.contentSystemConfig.enableDeduplication - Enable content deduplication (default: true)
303
+ * @param options.contentSystemConfig.enableStorageTracking - Enable storage tracking (default: true)
235
304
  * @returns Promise resolving to configured IngestionPipeline
236
305
  * @throws {Error} If initialization fails
237
306
  *
238
307
  * @example
239
308
  * ```typescript
240
- * // Create ingestion pipeline
309
+ * // Create ingestion pipeline with default content system
241
310
  * const ingestion = await TextIngestionFactory.create('./my-db.sqlite', './my-index.bin');
242
311
  *
312
+ * // Create with custom content system configuration
313
+ * const ingestion = await TextIngestionFactory.create('./my-db.sqlite', './my-index.bin', {
314
+ * contentSystemConfig: {
315
+ * contentDir: './custom-content',
316
+ * maxFileSize: 100 * 1024 * 1024, // 100MB
317
+ * maxContentDirSize: 5 * 1024 * 1024 * 1024, // 5GB
318
+ * enableDeduplication: true
319
+ * }
320
+ * });
321
+ *
243
322
  * // Ingest documents from directory
244
323
  * const result = await ingestion.ingestDirectory('./documents');
245
324
  * console.log(`Processed ${result.documentsProcessed} documents`);
246
325
  *
247
- * // Ingest single file
248
- * await ingestion.ingestFile('./document.pdf');
326
+ * // Ingest content from memory (MCP integration)
327
+ * const contentId = await ingestion.ingestFromMemory(buffer, {
328
+ * displayName: 'uploaded-file.pdf',
329
+ * contentType: 'application/pdf'
330
+ * });
249
331
  *
250
332
  * // Clean up when done
251
333
  * await ingestion.cleanup();
@@ -259,6 +341,22 @@ export declare class TextIngestionFactory {
259
341
  * @returns Promise resolving to configured IngestionPipeline
260
342
  */
261
343
  static createWithDefaults(options?: TextIngestionOptions): Promise<IngestionPipeline>;
344
+ /**
345
+ * Handles mode storage during ingestion
346
+ * Creates or validates system info based on the provided mode and options
347
+ * @private
348
+ */
349
+ private static handleModeStorage;
350
+ /**
351
+ * Updates system info in the database
352
+ * @private
353
+ */
354
+ private static updateSystemInfo;
355
+ /**
356
+ * Validates and prepares content system configuration
357
+ * @private
358
+ */
359
+ private static validateAndPrepareContentSystemConfig;
262
360
  }
263
361
  /**
264
362
  * Convenience factory to create both search and ingestion instances
@@ -365,9 +463,9 @@ export declare class TextRAGFactory {
365
463
  * const { searchOptions, ingestionOptions } = TextFactoryHelpers.getRecommendedConfig('quality');
366
464
  * const search = await TextSearchFactory.create('./index.bin', './db.sqlite', searchOptions);
367
465
  *
368
- * // Create with automatic error recovery
369
- * const search = await TextFactoryHelpers.createSearchWithFallback('./index.bin', './db.sqlite', {
370
- * enableReranking: true // Will fallback to disabled if reranking fails
466
+ * // Create with clear validation and error reporting
467
+ * const search = await TextFactoryHelpers.createSearchWithValidation('./index.bin', './db.sqlite', {
468
+ * enableReranking: true // Will fail clearly if reranking has issues
371
469
  * });
372
470
  * ```
373
471
  */
@@ -433,34 +531,30 @@ export declare class TextFactoryHelpers {
433
531
  ingestionOptions: TextIngestionOptions;
434
532
  };
435
533
  /**
436
- * Create a search engine with automatic error recovery
534
+ * Create a search engine with clear error reporting
437
535
  *
438
- * This method attempts to create a search engine with the provided options,
439
- * and if that fails, it tries again with fallback options (primarily
440
- * disabling reranking, which is a common source of initialization failures).
441
- * This provides a more robust way to create search engines in environments
442
- * where reranking models might not be available or might fail to load.
536
+ * This method creates a search engine with the provided options and fails
537
+ * clearly if there are any issues, providing actionable error messages.
443
538
  *
444
539
  * @param indexPath - Path to vector index file
445
540
  * @param dbPath - Path to database file
446
- * @param options - Initial options to try
447
- * @returns Promise resolving to SearchEngine (possibly with fallback options)
448
- * @throws {Error} If both original and fallback creation attempts fail
541
+ * @param options - Configuration options
542
+ * @returns Promise resolving to SearchEngine
543
+ * @throws {Error} If creation fails with clear error message
449
544
  *
450
545
  * @example
451
546
  * ```typescript
452
- * // Try to create with reranking, fallback to without if it fails
453
- * const search = await TextFactoryHelpers.createSearchWithFallback(
547
+ * // Create search engine with clear error handling
548
+ * const search = await TextFactoryHelpers.createSearchWithValidation(
454
549
  * './index.bin',
455
550
  * './db.sqlite',
456
551
  * { enableReranking: true, topK: 20 }
457
552
  * );
458
553
  *
459
- * // The search engine will work even if reranking model fails to load
460
554
  * const results = await search.search('query');
461
555
  * console.log(`Search created successfully with ${results.length} results`);
462
556
  * ```
463
557
  */
464
- static createSearchWithFallback(indexPath: string, dbPath: string, options?: TextSearchOptions): Promise<SearchEngine>;
558
+ static createSearchWithValidation(indexPath: string, dbPath: string, options?: TextSearchOptions): Promise<SearchEngine>;
465
559
  }
466
560
  //# sourceMappingURL=text-factory.d.ts.map