@devilsdev/rag-pipeline-utils 2.4.4 → 2.5.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 (225) hide show
  1. package/.ragrc.schema.json +83 -192
  2. package/CHANGELOG.md +345 -0
  3. package/README.md +418 -117
  4. package/SECURITY.md +5 -5
  5. package/dist/experimental.cjs +2 -0
  6. package/dist/experimental.d.ts +1 -0
  7. package/dist/experimental.mjs +5 -0
  8. package/dist/index.cjs +4992 -1242
  9. package/dist/index.d.ts +80 -2
  10. package/dist/index.mjs +1 -1
  11. package/dist/types/agentic/agentic-pipeline.d.ts +103 -0
  12. package/dist/types/agentic/iterative-retriever.d.ts +85 -0
  13. package/dist/types/agentic/query-planner.d.ts +145 -0
  14. package/dist/types/agentic/self-critique.d.ts +45 -0
  15. package/dist/types/ai/adaptive-retrieval.d.ts +44 -0
  16. package/dist/types/ai/federation/federated-learning-coordinator.d.ts +62 -0
  17. package/dist/types/ai/multimodal-processing.d.ts +32 -0
  18. package/dist/types/ai/multimodal.d.ts +39 -0
  19. package/dist/types/ai/retrieval-engine.d.ts +37 -0
  20. package/dist/types/ai/training/model-training-orchestrator.d.ts +31 -0
  21. package/dist/types/chunking/chunking-engine.d.ts +70 -0
  22. package/dist/types/chunking/strategies/fixed-size.d.ts +17 -0
  23. package/dist/types/chunking/strategies/recursive.d.ts +20 -0
  24. package/dist/types/chunking/strategies/semantic.d.ts +19 -0
  25. package/dist/types/chunking/strategies/sentence.d.ts +13 -0
  26. package/dist/types/chunking/strategies/structure-aware.d.ts +19 -0
  27. package/dist/types/citation/citation-tracker.d.ts +64 -0
  28. package/dist/types/citation/hallucination-detector.d.ts +40 -0
  29. package/dist/types/citation/source-mapper.d.ts +37 -0
  30. package/dist/types/connectors/anthropic-connector.d.ts +92 -0
  31. package/dist/types/connectors/base-connector.d.ts +87 -0
  32. package/dist/types/connectors/cohere-connector.d.ts +89 -0
  33. package/dist/types/connectors/connector-utils.d.ts +110 -0
  34. package/dist/types/connectors/local-embedder.d.ts +86 -0
  35. package/dist/types/connectors/memory-retriever.d.ts +91 -0
  36. package/dist/types/connectors/ollama-connector.d.ts +110 -0
  37. package/dist/types/connectors/openai-connector.d.ts +114 -0
  38. package/dist/types/connectors/rag-prompt.d.ts +40 -0
  39. package/dist/types/cost/cost-calculator.d.ts +152 -0
  40. package/dist/types/cost/cost-tracker.d.ts +126 -0
  41. package/dist/types/cost/token-budget.d.ts +110 -0
  42. package/dist/types/dag/core/error-context.d.ts +239 -0
  43. package/dist/types/dag/core/execution-scheduler.d.ts +191 -0
  44. package/dist/types/dag/core/topology-validation.d.ts +226 -0
  45. package/dist/types/dag/dag-engine.d.ts +156 -0
  46. package/dist/types/dag/dag-node.d.ts +37 -0
  47. package/dist/types/dashboard/dashboard-generator.d.ts +127 -0
  48. package/dist/types/dashboard/metrics-aggregator.d.ts +218 -0
  49. package/dist/types/debug/execution-tracer.d.ts +57 -0
  50. package/dist/types/debug/trace-inspector.d.ts +31 -0
  51. package/dist/types/ecosystem/plugin-certification.d.ts +169 -0
  52. package/dist/types/enterprise/data-governance.d.ts +203 -0
  53. package/dist/types/enterprise/multi-tenancy.d.ts +137 -0
  54. package/dist/types/enterprise/sso-integration.d.ts +420 -0
  55. package/dist/types/evaluate/context-metrics.d.ts +55 -0
  56. package/dist/types/evaluate/faithfulness.d.ts +41 -0
  57. package/dist/types/evaluate/groundedness.d.ts +60 -0
  58. package/dist/types/evaluate/pipeline-evaluator.d.ts +88 -0
  59. package/dist/types/evaluate/relevance.d.ts +21 -0
  60. package/dist/types/evaluate/scoring.d.ts +123 -0
  61. package/dist/types/experimental.d.ts +15 -0
  62. package/dist/types/graph/entity-extractor.d.ts +84 -0
  63. package/dist/types/graph/graph-index.d.ts +49 -0
  64. package/dist/types/graph/graph-retriever.d.ts +81 -0
  65. package/dist/types/graph/knowledge-graph.d.ts +129 -0
  66. package/dist/types/guardrails/guardrails-pipeline.d.ts +63 -0
  67. package/dist/types/guardrails/injection-detector.d.ts +47 -0
  68. package/dist/types/guardrails/post-generation-guard.d.ts +61 -0
  69. package/dist/types/guardrails/pre-retrieval-guard.d.ts +64 -0
  70. package/dist/types/guardrails/retrieval-guard.d.ts +57 -0
  71. package/dist/types/mcp/mcp-server.d.ts +85 -0
  72. package/dist/types/mcp/mcp-tool-builder.d.ts +55 -0
  73. package/dist/types/reranker/cascade-reranker.d.ts +40 -0
  74. package/dist/types/reranker/embedding-reranker.d.ts +77 -0
  75. package/dist/types/reranker/scoring-reranker.d.ts +41 -0
  76. package/dist/types/retrieval/bm25-search.d.ts +43 -0
  77. package/dist/types/retrieval/file-vector-store.d.ts +87 -0
  78. package/dist/types/retrieval/hybrid-retriever.d.ts +35 -0
  79. package/dist/types/retrieval/rank-fusion.d.ts +10 -0
  80. package/dist/types/security/jwt-config.d.ts +80 -0
  81. package/dist/types/security/jwt-validator.d.ts +195 -0
  82. package/dist/types/security/plugin-sandbox.d.ts +158 -0
  83. package/dist/types/security/plugin-signature-verifier.d.ts +139 -0
  84. package/dist/types/security/validator.d.ts +5 -0
  85. package/dist/types/streaming/embedding-stream.d.ts +65 -0
  86. package/dist/types/streaming/sse-adapter.d.ts +59 -0
  87. package/dist/types/streaming/stream-router.d.ts +88 -0
  88. package/dist/types/streaming/streaming-embedder.d.ts +99 -0
  89. package/dist/types/streaming/websocket-adapter.d.ts +71 -0
  90. package/dist/types/templates/scaffold.d.ts +55 -0
  91. package/dist/types/templates/template-registry.d.ts +63 -0
  92. package/dist/types/utils/embed-query.d.ts +20 -0
  93. package/dist/types/utils/logger.d.ts +50 -0
  94. package/dist/types/utils/rate-limiter.d.ts +66 -0
  95. package/dist/types/utils/retry.d.ts +27 -0
  96. package/dist/types/utils/run-abort.d.ts +34 -0
  97. package/dist/types/utils/secure-logging.d.ts +51 -0
  98. package/dist/types/utils/structured-logger.d.ts +126 -0
  99. package/package.json +53 -29
  100. package/src/agentic/agentic-pipeline.js +75 -7
  101. package/src/agentic/iterative-retriever.js +47 -10
  102. package/src/agentic/query-planner.js +329 -78
  103. package/src/citation/citation-tracker.js +6 -4
  104. package/src/citation/hallucination-detector.js +2 -2
  105. package/src/citation/source-mapper.js +15 -28
  106. package/src/cli/commands/ai.js +101 -0
  107. package/src/cli/commands/plugin-hub/event-handlers.js +6 -0
  108. package/src/cli/commands/plugin-hub/hub-commands.js +0 -74
  109. package/src/cli/commands/plugin-hub/local-commands.js +143 -0
  110. package/src/cli/commands/plugin-hub.js +96 -36
  111. package/src/cli/diagnostics/config-checker.js +76 -63
  112. package/src/cli/diagnostics/environment-checker.js +62 -31
  113. package/src/cli/diagnostics/plugin-checker.js +36 -89
  114. package/src/cli/doctor-command.js +39 -5
  115. package/src/cli/enhanced-cli-commands.js +72 -217
  116. package/src/cli/handlers/ai-handler.js +364 -0
  117. package/src/cli/handlers/diagnostics-handler.js +78 -31
  118. package/src/cli/handlers/ingest-handler.js +28 -22
  119. package/src/cli/handlers/init-handler.js +148 -25
  120. package/src/cli/handlers/query-handler.js +41 -26
  121. package/src/cli/handlers/run-handler.js +16 -167
  122. package/src/cli/handlers/serve-handler.js +60 -0
  123. package/src/cli/services/bench-stats.js +54 -0
  124. package/src/cli/services/benchmark.js +161 -0
  125. package/src/cli/services/feedback.js +155 -0
  126. package/src/cli/services/rag-service.js +322 -0
  127. package/src/cli/shared/cli-utils.js +24 -7
  128. package/src/cli/shared/config-context.js +21 -0
  129. package/src/cli/wizard/config-builder.js +81 -0
  130. package/src/cli/wizard/init-wizard.js +617 -0
  131. package/src/config/component-factory.js +125 -0
  132. package/src/config/load-config.js +29 -10
  133. package/src/config/load-plugin-config.js +46 -2
  134. package/src/connectors/anthropic-connector.js +93 -55
  135. package/src/connectors/base-connector.js +74 -19
  136. package/src/connectors/cohere-connector.js +88 -32
  137. package/src/connectors/connector-utils.js +302 -0
  138. package/src/connectors/local-embedder.js +43 -5
  139. package/src/connectors/memory-retriever.js +108 -15
  140. package/src/connectors/ollama-connector.js +83 -49
  141. package/src/connectors/openai-connector.js +108 -44
  142. package/src/connectors/rag-prompt.js +88 -0
  143. package/src/core/create-pipeline.js +209 -60
  144. package/src/core/plugin-registry.js +87 -11
  145. package/src/cost/cost-calculator.js +205 -32
  146. package/src/dev/dev-server.js +166 -11
  147. package/src/dev/hot-reload.js +40 -1
  148. package/src/ecosystem/plugin-checks.js +181 -0
  149. package/src/ecosystem/plugin-hub.js +50 -125
  150. package/src/ecosystem/plugin-installer.js +298 -0
  151. package/src/ecosystem/plugin-probe.js +127 -0
  152. package/src/ecosystem/plugin-scanner.js +185 -0
  153. package/src/ecosystem/tar-extract.js +114 -0
  154. package/src/enterprise/audit-logging.js +158 -29
  155. package/src/enterprise/sso-integration.js +715 -228
  156. package/src/evaluate/context-metrics.js +28 -16
  157. package/src/evaluate/evaluator.js +3 -3
  158. package/src/evaluate/faithfulness.js +18 -14
  159. package/src/evaluate/groundedness.js +43 -12
  160. package/src/evaluate/pipeline-evaluator.js +35 -8
  161. package/src/evaluate/scoring.js +251 -3
  162. package/src/experimental.js +71 -0
  163. package/src/guardrails/guardrails-pipeline.js +69 -7
  164. package/src/guardrails/injection-detector.js +283 -0
  165. package/src/guardrails/post-generation-guard.js +19 -0
  166. package/src/guardrails/pre-retrieval-guard.js +36 -36
  167. package/src/guardrails/retrieval-guard.js +58 -8
  168. package/src/index.js +36 -1
  169. package/src/loader/document-reader.js +91 -0
  170. package/src/reranker/cascade-reranker.js +3 -0
  171. package/src/reranker/embedding-reranker.js +136 -21
  172. package/src/reranker/llm-reranker.js +79 -12
  173. package/src/reranker/scoring-reranker.js +3 -0
  174. package/src/retrieval/bm25-search.js +12 -6
  175. package/src/retrieval/file-vector-store.js +212 -0
  176. package/src/retrieval/hybrid-retriever.js +22 -19
  177. package/src/security/jwt-config.js +13 -2
  178. package/src/security/jwt-validator.js +134 -30
  179. package/src/security/plugin-sandbox.js +18 -1
  180. package/src/security/plugin-signature-verifier.js +245 -70
  181. package/src/utils/deprecate.js +69 -0
  182. package/src/utils/embed-query.js +33 -0
  183. package/src/utils/input-sanitizer.js +19 -4
  184. package/src/utils/logger.js +34 -4
  185. package/src/utils/run-abort.js +102 -0
  186. package/src/ai/federated-learning.js +0 -211
  187. package/src/ai/federation.js +0 -71
  188. package/src/ai/index.js +0 -22
  189. package/src/ai/model-trainer.js +0 -217
  190. package/src/ai/model-training.js +0 -202
  191. package/src/ai/multimodal/multi-modal-processor.js +0 -345
  192. package/src/ai/orchestrator.js +0 -65
  193. package/src/ai/retrieval/adaptive-retrieval-engine.js +0 -398
  194. package/src/cli/commands/ai-ml/adaptive-commands.js +0 -178
  195. package/src/cli/commands/ai-ml/federated-commands.js +0 -207
  196. package/src/cli/commands/ai-ml/index.js +0 -17
  197. package/src/cli/commands/ai-ml/multimodal-commands.js +0 -187
  198. package/src/cli/commands/ai-ml/shared.js +0 -51
  199. package/src/cli/commands/ai-ml/training-commands.js +0 -228
  200. package/src/cli/commands/ai-ml.js +0 -386
  201. package/src/cli/commands/docs.js +0 -228
  202. package/src/cli/commands/dx.js +0 -538
  203. package/src/cli/commands/wizard.js +0 -627
  204. package/src/cli/input-sanitization-middleware.js +0 -356
  205. package/src/cli/interactive-wizard.js +0 -373
  206. package/src/cli/templates/development.template.json +0 -64
  207. package/src/cli/templates/minimal.template.json +0 -33
  208. package/src/cli/templates/production.template.json +0 -104
  209. package/src/cli/templates/testing.template.json +0 -45
  210. package/src/cli/wizard/configuration.js +0 -148
  211. package/src/cli/wizard/observability.js +0 -79
  212. package/src/cli/wizard/performance.js +0 -76
  213. package/src/cli/wizard/plugin-selection.js +0 -297
  214. package/src/cli/wizard/preview-save.js +0 -172
  215. package/src/cli/wizard/project-setup.js +0 -66
  216. package/src/core/pipeline-factory.js +0 -59
  217. package/src/dag/enhanced-dag-engine.js +0 -894
  218. package/src/dx/index.js +0 -40
  219. package/src/dx/integration-templates.js +0 -662
  220. package/src/dx/performance-profiler.js +0 -968
  221. package/src/dx/realtime-debugger.js +0 -755
  222. package/src/dx/visual-pipeline-builder.js +0 -578
  223. package/src/ingest.js +0 -59
  224. package/src/pipeline/pipeline.js +0 -18
  225. package/src/query.js +0 -117
@@ -1,202 +0,0 @@
1
- /**
2
- * Model Training Orchestrator
3
- * Lightweight, deterministic in-memory trainer for RAG pipeline models
4
- */
5
-
6
- "use strict";
7
-
8
- // In-memory storage for deterministic behavior
9
- const jobs = new Map();
10
- const optimizations = new Map();
11
- const deployments = new Map();
12
-
13
- // Deterministic ID generation using monotonic counter
14
- let jobCounter = 0;
15
- let optCounter = 0;
16
- let deployCounter = 0;
17
-
18
- /**
19
- * Create a training job
20
- * @param {string} tenantId - Tenant identifier
21
- * @param {object} trainingConfig - Training configuration
22
- * @returns {Promise<string>} Job ID
23
- */
24
- async function createTrainingJob(tenantId, trainingConfig) {
25
- const jobId = `job-${++jobCounter}`;
26
- const job = {
27
- jobId,
28
- tenantId,
29
- trainingConfig,
30
- status: "queued",
31
- createdAt: Date.now(),
32
- metrics: { accuracy: 0.9 },
33
- };
34
- jobs.set(jobId, job);
35
- return jobId;
36
- }
37
-
38
- /**
39
- * Start training for a job
40
- * @param {string} jobId - Job ID
41
- * @returns {Promise<object>} Training result
42
- */
43
- async function startTraining(jobId) {
44
- const job = jobs.get(jobId);
45
- if (!job) {
46
- throw new Error(`Job ${jobId} not found`);
47
- }
48
-
49
- // Transition through states quickly
50
- job.status = "running";
51
- jobs.set(jobId, job);
52
-
53
- // Simulate quick completion
54
- await new Promise((resolve) => setTimeout(resolve, 1));
55
- job.status = "completed";
56
- jobs.set(jobId, job);
57
-
58
- return { started: true };
59
- }
60
-
61
- /**
62
- * Optimize hyperparameters
63
- * @param {string} tenantId - Tenant identifier
64
- * @param {object} optimizationConfig - Optimization configuration
65
- * @returns {Promise<string>} Optimization ID
66
- */
67
- async function optimizeHyperparameters(tenantId, optimizationConfig) {
68
- const optId = `opt-${++optCounter}`;
69
- const optimization = {
70
- optId,
71
- tenantId,
72
- optimizationConfig,
73
- status: "completed",
74
- bestConfiguration: {
75
- learningRate: 0.01,
76
- batchSize: 32,
77
- hiddenSize: 512,
78
- },
79
- trials: [
80
- {
81
- trialId: "trial-1",
82
- params: { learningRate: 0.001 },
83
- metrics: { accuracy: 0.85 },
84
- },
85
- {
86
- trialId: "trial-2",
87
- params: { learningRate: 0.01 },
88
- metrics: { accuracy: 0.92 },
89
- },
90
- {
91
- trialId: "trial-3",
92
- params: { learningRate: 0.1 },
93
- metrics: { accuracy: 0.88 },
94
- },
95
- ],
96
- };
97
- optimizations.set(optId, optimization);
98
- return optId;
99
- }
100
-
101
- /**
102
- * Deploy a trained model
103
- * @param {string} jobId - Training job ID
104
- * @param {object} deployConfig - Deployment configuration
105
- * @returns {Promise<string>} Deployment ID
106
- */
107
- async function deployModel(jobId, deployConfig = {}) {
108
- const deploymentId = `dep-${++deployCounter}`;
109
- const deployment = {
110
- deploymentId,
111
- jobId,
112
- status: "deployed",
113
- endpoint: `https://models.local/${deploymentId}`,
114
- config: deployConfig,
115
- createdAt: Date.now(),
116
- };
117
- deployments.set(deploymentId, deployment);
118
-
119
- return deploymentId;
120
- }
121
-
122
- /**
123
- * Get training status by job ID
124
- * @param {string} jobId - Job ID
125
- * @returns {Promise<object>} Status object with jobId, status, and metrics
126
- */
127
- async function getTrainingStatus(jobId) {
128
- const job = jobs.get(jobId);
129
- if (!job) {
130
- throw new Error(`Job ${jobId} not found`);
131
- }
132
- return {
133
- jobId: job.jobId,
134
- status: job.status,
135
- metrics: job.metrics,
136
- };
137
- }
138
-
139
- /**
140
- * Get training job by ID
141
- * @param {string} jobId - Job ID
142
- * @returns {object|null} Job object or null if not found
143
- */
144
- function getJob(jobId) {
145
- return jobs.get(jobId) || null;
146
- }
147
-
148
- /**
149
- * Get optimization by ID
150
- * @param {string} optId - Optimization ID
151
- * @returns {object|null} Optimization object or null if not found
152
- */
153
- function getOptimization(optId) {
154
- return optimizations.get(optId) || null;
155
- }
156
-
157
- /**
158
- * Get deployment by ID
159
- * @param {string} deploymentId - Deployment ID
160
- * @returns {object} Deployment object with deploymentId, jobId, status, endpoint
161
- */
162
- function getDeployment(deploymentId) {
163
- const deployment = deployments.get(deploymentId);
164
- if (!deployment) {
165
- throw new Error(`Deployment ${deploymentId} not found`);
166
- }
167
- return {
168
- deploymentId: deployment.deploymentId,
169
- jobId: deployment.jobId,
170
- status: deployment.status,
171
- endpoint: deployment.endpoint,
172
- };
173
- }
174
-
175
- /**
176
- * Clear all stored data (for testing)
177
- */
178
- function clear() {
179
- jobs.clear();
180
- optimizations.clear();
181
- deployments.clear();
182
- jobCounter = 0;
183
- optCounter = 0;
184
- deployCounter = 0;
185
- }
186
-
187
- // Singleton object with required methods
188
- const modelTrainingOrchestrator = {
189
- createTrainingJob,
190
- startTraining,
191
- optimizeHyperparameters,
192
- getTrainingStatus,
193
- deployModel,
194
- // Additional utility methods
195
- getJob,
196
- getOptimization,
197
- getDeployment,
198
- clear,
199
- };
200
-
201
- // Export singleton as default
202
- module.exports = modelTrainingOrchestrator;
@@ -1,345 +0,0 @@
1
- /**
2
- * Multi-Modal Processor - Extracted from monolithic AI module
3
- * Handles processing and embedding of text, image, audio, and video content
4
- */
5
-
6
- const { EventEmitter } = require("events");
7
- const crypto = require("crypto");
8
-
9
- class MultiModalProcessor extends EventEmitter {
10
- constructor(options = {}) {
11
- super();
12
- this.config = {
13
- supportedModalities: ["text", "image", "audio", "video"],
14
- embeddingDimension: options.embeddingDimension || 768,
15
- ...options,
16
- };
17
- this.processors = new Map();
18
- this.contentStore = new Map(); // Store processed content by tenant
19
- this.embeddings = new Map(); // Store embeddings by tenant
20
- }
21
-
22
- // API that matches test expectations: processContent(tenantId, content, options)
23
- async processContent(tenantId, content, options = {}) {
24
- const processingId = crypto.randomUUID();
25
-
26
- // Determine modality from content object
27
- let modalityType = "text"; // default
28
- if (content && typeof content === "object") {
29
- const contentType = content.type || content._type;
30
- if (contentType) {
31
- // Extract modality from MIME type or content type
32
- if (contentType.startsWith("image/")) modalityType = "image";
33
- else if (contentType.startsWith("audio/")) modalityType = "audio";
34
- else if (contentType.startsWith("video/")) modalityType = "video";
35
- else if (contentType.startsWith("text/")) modalityType = "text";
36
- }
37
- }
38
-
39
- this.emit("processingStarted", {
40
- processingId,
41
- tenantId,
42
- modality: modalityType,
43
- });
44
-
45
- // Process based on modality
46
- let result;
47
- switch (modalityType) {
48
- case "text":
49
- result = await this._processText(content, options);
50
- break;
51
- case "image":
52
- result = await this._processImage(content, options);
53
- break;
54
- case "audio":
55
- result = await this._processAudio(content, options);
56
- break;
57
- case "video":
58
- result = await this._processVideo(content, options);
59
- break;
60
- default:
61
- throw new Error(`Unsupported modality: ${modalityType}`);
62
- }
63
-
64
- // Store processed content and embeddings by tenant
65
- if (!this.contentStore.has(tenantId)) {
66
- this.contentStore.set(tenantId, []);
67
- this.embeddings.set(tenantId, []);
68
- }
69
-
70
- // Create the response structure that tests expect
71
- const response = {
72
- id: processingId,
73
- tenantId,
74
- modalities: {
75
- [modalityType]: {
76
- embedding: result.embedding,
77
- features: result.features,
78
- processed: result.processed,
79
- confidence: 0.9 + Math.random() * 0.1,
80
- },
81
- },
82
- // Create unified embedding by combining modality-specific embeddings
83
- unifiedEmbedding: result.embedding, // For single modality, use the same embedding
84
- metadata: {
85
- processingTime: Date.now() - Date.now(),
86
- modality: modalityType,
87
- contentType: content._type || "unknown",
88
- },
89
- processed: true,
90
- };
91
-
92
- this.contentStore.get(tenantId).push({
93
- id: processingId,
94
- content,
95
- result: response,
96
- modality: modalityType,
97
- });
98
- this.embeddings.get(tenantId).push({
99
- id: processingId,
100
- embedding: result.embedding,
101
- modality: modalityType,
102
- });
103
-
104
- this.emit("processingCompleted", {
105
- processingId,
106
- tenantId,
107
- modality: modalityType,
108
- result: response,
109
- });
110
- return response;
111
- }
112
-
113
- // Multi-modal search API that tests expect
114
- async multiModalSearch(tenantId, query, options = {}) {
115
- const maxResults = options.maxResults || 10;
116
- const tenantEmbeddings = this.embeddings.get(tenantId) || [];
117
-
118
- if (tenantEmbeddings.length === 0) {
119
- return { results: [], total: 0 };
120
- }
121
-
122
- // Simulate search by returning stored content with similarity scores
123
- const results = tenantEmbeddings
124
- .slice(0, maxResults)
125
- .map((item, index) => ({
126
- id: item.id,
127
- score: 0.9 - index * 0.1, // Simulate decreasing relevance
128
- modality: item.modality,
129
- content: this.contentStore.get(tenantId).find((c) => c.id === item.id)
130
- ?.content,
131
- }));
132
-
133
- this.emit("searchCompleted", {
134
- tenantId,
135
- query,
136
- resultsCount: results.length,
137
- });
138
- return {
139
- results,
140
- total: results.length,
141
- metadata: {
142
- tenantId,
143
- query,
144
- searchTimestamp: Date.now(),
145
- totalEmbeddings: tenantEmbeddings.length,
146
- searchStrategy: "similarity_based",
147
- modalitiesSearched: [
148
- ...new Set(tenantEmbeddings.map((e) => e.modality)),
149
- ],
150
- },
151
- };
152
- }
153
-
154
- async findSimilarContent(contentId, options = {}) {
155
- const { threshold = 0.5, limit = 10 } = options;
156
-
157
- // Find the reference content by searching through all tenants
158
- let referenceContent = null;
159
- let referenceTenant = null;
160
-
161
- for (const [tenantId, tenantEmbeddings] of this.embeddings.entries()) {
162
- const found = tenantEmbeddings.find((e) => e.id === contentId);
163
- if (found) {
164
- referenceContent = found;
165
- referenceTenant = tenantId;
166
- break;
167
- }
168
- }
169
-
170
- if (!referenceContent) {
171
- return [];
172
- }
173
-
174
- // Calculate similarities with all other content across all tenants
175
- const allEmbeddings = [];
176
- for (const [tenantId, tenantEmbeddings] of this.embeddings.entries()) {
177
- allEmbeddings.push(...tenantEmbeddings.map((e) => ({ ...e, tenantId })));
178
- }
179
-
180
- const similarities = allEmbeddings
181
- .filter((e) => e.id !== contentId) // Exclude the reference content itself
182
- .map((embedding) => {
183
- // Simple cosine similarity simulation
184
- const similarity = Math.random() * 0.4 + 0.6; // Simulate 0.6-1.0 range
185
-
186
- return {
187
- id: embedding.id,
188
- content: this.contentStore
189
- .get(embedding.tenantId)
190
- ?.find((c) => c.id === embedding.id)?.content,
191
- modality: embedding.modality,
192
- similarity,
193
- score: similarity,
194
- };
195
- })
196
- .filter((item) => item.similarity >= threshold)
197
- .sort((a, b) => b.similarity - a.similarity)
198
- .slice(0, limit);
199
-
200
- this.emit("similaritySearchCompleted", {
201
- referenceId: contentId,
202
- foundSimilar: similarities.length,
203
- threshold,
204
- });
205
-
206
- return similarities;
207
- }
208
-
209
- async generateContentDescription(contentId) {
210
- // Find the content by searching through all tenants
211
- let contentItem = null;
212
-
213
- for (const [tenantId, tenantContent] of this.contentStore.entries()) {
214
- const found = tenantContent.find((c) => c.id === contentId);
215
- if (found) {
216
- contentItem = found;
217
- break;
218
- }
219
- }
220
-
221
- if (!contentItem) {
222
- throw new Error(`Content with ID ${contentId} not found`);
223
- }
224
-
225
- const { content, modality } = contentItem;
226
-
227
- // Generate descriptions based on modality
228
- const descriptions = {
229
- unified: `This is ${modality} content with rich semantic features and contextual information.`,
230
- };
231
-
232
- // Add modality-specific descriptions
233
- switch (modality) {
234
- case "text": {
235
- const textContent =
236
- typeof content === "string"
237
- ? content
238
- : content.text || content.content || "text content";
239
- const wordCount = textContent.split(" ").length;
240
- descriptions.text = `Text content containing ${wordCount} words with semantic meaning and contextual relevance.`;
241
- break;
242
- }
243
- case "image":
244
- descriptions.image =
245
- "Visual content depicting scenes, objects, and visual elements with rich spatial and semantic information.";
246
- break;
247
- case "audio":
248
- descriptions.audio =
249
- "Audio content with temporal features, including speech patterns, music, or environmental sounds.";
250
- break;
251
- case "video":
252
- descriptions.video =
253
- "Video content combining visual and temporal elements, including scenes, actions, and narrative structure.";
254
- break;
255
- default:
256
- descriptions[modality] =
257
- `${modality} content with specialized features and semantic properties.`;
258
- }
259
-
260
- // Add unified description that combines all aspects
261
- descriptions.unified = `Multi-modal ${modality} content with comprehensive semantic understanding, featuring contextual relevance and rich feature extraction for enhanced retrieval and analysis.`;
262
-
263
- this.emit("descriptionGenerated", { contentId, modality });
264
-
265
- return descriptions;
266
- }
267
-
268
- async _processText(content, options) {
269
- await new Promise((resolve) => setTimeout(resolve, 50));
270
-
271
- // Handle both string and object content
272
- let textContent = "";
273
- if (typeof content === "string") {
274
- textContent = content;
275
- } else if (content && typeof content === "object") {
276
- textContent = content.text || content.content || JSON.stringify(content);
277
- }
278
-
279
- return {
280
- modality: "text",
281
- embedding: Array.from({ length: this.config.embeddingDimension }, () =>
282
- Math.random(),
283
- ),
284
- features: {
285
- length: textContent.length,
286
- wordCount: textContent.split(" ").length,
287
- originalType: typeof content,
288
- },
289
- processed: true,
290
- };
291
- }
292
-
293
- async _processImage(content, options) {
294
- await new Promise((resolve) => setTimeout(resolve, 100));
295
- return {
296
- modality: "image",
297
- embedding: Array.from({ length: this.config.embeddingDimension }, () =>
298
- Math.random(),
299
- ),
300
- features: { width: 1024, height: 768, channels: 3 },
301
- processed: true,
302
- };
303
- }
304
-
305
- async _processAudio(content, options) {
306
- await new Promise((resolve) => setTimeout(resolve, 75));
307
- return {
308
- modality: "audio",
309
- embedding: Array.from({ length: this.config.embeddingDimension }, () =>
310
- Math.random(),
311
- ),
312
- features: {
313
- duration: content.duration || 30,
314
- sampleRate: 44100,
315
- channels: 2,
316
- transcript:
317
- content.transcript ||
318
- content.audioTranscript ||
319
- "Generated transcript",
320
- },
321
- processed: true,
322
- };
323
- }
324
-
325
- async _processVideo(content, options) {
326
- await new Promise((resolve) => setTimeout(resolve, 150));
327
- return {
328
- modality: "video",
329
- embedding: Array.from({ length: this.config.embeddingDimension }, () =>
330
- Math.random(),
331
- ),
332
- features: {
333
- duration: content.duration || 60,
334
- fps: 30,
335
- resolution: "1920x1080",
336
- scenes: ["scene1", "scene2", "scene3"],
337
- actions: ["action1", "action2"],
338
- audioTranscript: content.audioTranscript || "Video audio transcript",
339
- },
340
- processed: true,
341
- };
342
- }
343
- }
344
-
345
- module.exports = { MultiModalProcessor };
@@ -1,65 +0,0 @@
1
- /**
2
- * Model Training Orchestrator
3
- * Provides model training coordination and job management
4
- * Extracted from ai/index.js per CLAUDE.md decomposition requirements
5
- */
6
-
7
- "use strict";
8
-
9
- // Import the existing model training implementation
10
- const modelTraining = require("./model-training");
11
-
12
- /**
13
- * ModelTrainingOrchestrator class
14
- * Coordinates and manages model training jobs across tenants
15
- */
16
- class ModelTrainingOrchestrator {
17
- constructor() {
18
- this.jobs = new Map();
19
- this.optimizations = new Map();
20
- this.deployments = new Map();
21
- this.jobCounter = 0;
22
- this.optCounter = 0;
23
- this.deployCounter = 0;
24
- }
25
-
26
- /**
27
- * Create a training job
28
- * @param {string} tenantId - Tenant identifier
29
- * @param {object} trainingConfig - Training configuration
30
- * @returns {Promise<string>} Job ID
31
- */
32
- async createTrainingJob(tenantId, trainingConfig) {
33
- return await modelTraining.createTrainingJob(tenantId, trainingConfig);
34
- }
35
-
36
- /**
37
- * Get training job status
38
- * @param {string} jobId - Job identifier
39
- * @returns {Promise<object>} Job status
40
- */
41
- async getJobStatus(jobId) {
42
- return await modelTraining.getJobStatus(jobId);
43
- }
44
-
45
- /**
46
- * Optimize model configuration
47
- * @param {object} modelConfig - Model configuration
48
- * @returns {Promise<object>} Optimized configuration
49
- */
50
- async optimizeModel(modelConfig) {
51
- return await modelTraining.optimizeModel(modelConfig);
52
- }
53
-
54
- /**
55
- * Deploy trained model
56
- * @param {string} jobId - Training job identifier
57
- * @param {object} deployConfig - Deployment configuration
58
- * @returns {Promise<string>} Deployment ID
59
- */
60
- async deployModel(jobId, deployConfig) {
61
- return await modelTraining.deployModel(jobId, deployConfig);
62
- }
63
- }
64
-
65
- module.exports = { ModelTrainingOrchestrator };