@devilsdev/rag-pipeline-utils 2.6.2 → 2.7.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 (90) hide show
  1. package/BENCHMARKS.md +7 -1
  2. package/CHANGELOG.md +121 -0
  3. package/README.md +35 -24
  4. package/dist/index.cjs +4164 -1825
  5. package/dist/index.d.ts +265 -256
  6. package/dist/index.mjs +1 -1
  7. package/dist/types/cache/memory-cache.d.ts +4 -1
  8. package/dist/types/cache/redis-cache.d.ts +4 -1
  9. package/dist/types/cli/services/instrument.d.ts +14 -0
  10. package/dist/types/cli/services/rag-service.d.ts +140 -0
  11. package/dist/types/cli/shared/config-context.d.ts +9 -0
  12. package/dist/types/config/component-factory.d.ts +57 -0
  13. package/dist/types/config/enhanced-ragrc-schema.d.ts +648 -0
  14. package/dist/types/config/load-config.d.ts +18 -0
  15. package/dist/types/config/normalize-config.d.ts +9 -0
  16. package/dist/types/core/observability/event-logger.d.ts +211 -0
  17. package/dist/types/core/observability/metrics.d.ts +585 -0
  18. package/dist/types/core/performance/parallel-processor.d.ts +92 -0
  19. package/dist/types/core/plugin-registry.d.ts +5 -0
  20. package/dist/types/dag/core/execution-scheduler.d.ts +3 -1
  21. package/dist/types/dag/dag-engine.d.ts +15 -2
  22. package/dist/types/dev/dev-server.d.ts +136 -0
  23. package/dist/types/dev/hot-reload.d.ts +226 -0
  24. package/dist/types/ecosystem/plugin-analytics-dashboard.d.ts +141 -0
  25. package/dist/types/ecosystem/plugin-hub.d.ts +161 -0
  26. package/dist/types/ecosystem/plugin-installer.d.ts +40 -0
  27. package/dist/types/ecosystem/plugin-probe.d.ts +21 -0
  28. package/dist/types/ecosystem/plugin-scanner.d.ts +30 -0
  29. package/dist/types/ecosystem/tar-extract.d.ts +24 -0
  30. package/dist/types/enterprise/audit-logging.d.ts +217 -0
  31. package/dist/types/evaluate/compare.d.ts +140 -0
  32. package/dist/types/evaluate/dataset.d.ts +43 -0
  33. package/dist/types/evaluate/evaluator.d.ts +14 -0
  34. package/dist/types/evaluate/report.d.ts +56 -0
  35. package/dist/types/evaluate/synthetic.d.ts +64 -0
  36. package/dist/types/loader/csv-loader.d.ts +10 -0
  37. package/dist/types/loader/document-reader.d.ts +18 -0
  38. package/dist/types/loader/html-loader.d.ts +21 -0
  39. package/dist/types/loader/markdown-loader.d.ts +21 -0
  40. package/dist/types/retrieval/bm25-search.d.ts +4 -0
  41. package/dist/types/retrieval/file-vector-store.d.ts +4 -1
  42. package/dist/types/retrieval/hybrid-retriever.d.ts +4 -0
  43. package/dist/types/retrieval/pgvector-retriever.d.ts +123 -0
  44. package/dist/types/retrieval/qdrant-retriever.d.ts +106 -0
  45. package/dist/types/security/validator.d.ts +11 -1
  46. package/dist/types/testing.d.ts +2 -0
  47. package/dist/types/utils/batch-processor.d.ts +205 -0
  48. package/dist/types/utils/connection-pool.d.ts +158 -0
  49. package/dist/types/utils/error-formatter.d.ts +312 -0
  50. package/dist/types/utils/logger.d.ts +29 -4
  51. package/dist/types/utils/rate-limiter.d.ts +13 -8
  52. package/dist/types/utils/retry.d.ts +10 -0
  53. package/package.json +12 -2
  54. package/src/cache/memory-cache.js +4 -1
  55. package/src/cache/redis-cache.js +4 -1
  56. package/src/cli/enhanced-cli-commands.js +79 -0
  57. package/src/cli/handlers/ai-handler.js +2 -2
  58. package/src/cli/handlers/eval-handler.js +201 -0
  59. package/src/cli/handlers/generate-handler.js +103 -0
  60. package/src/cli/services/benchmark.js +2 -2
  61. package/src/cli/services/rag-service.js +59 -10
  62. package/src/cli/shared/cli-utils.js +40 -1
  63. package/src/config/component-factory.js +32 -0
  64. package/src/connectors/local-embedder.js +20 -13
  65. package/src/core/observability/event-logger.js +135 -1
  66. package/src/core/observability/metrics.js +223 -5
  67. package/src/core/performance/parallel-processor.js +2 -0
  68. package/src/core/plugin-registry.js +5 -1
  69. package/src/dag/core/execution-scheduler.js +2 -0
  70. package/src/dag/dag-engine.js +13 -0
  71. package/src/dev/dev-server.js +6 -0
  72. package/src/ecosystem/plugin-hub.js +4 -0
  73. package/src/enterprise/audit-logging.js +5 -0
  74. package/src/evaluate/compare.js +395 -0
  75. package/src/evaluate/dataset.js +207 -0
  76. package/src/evaluate/report.js +350 -0
  77. package/src/evaluate/synthetic.js +246 -0
  78. package/src/index.js +17 -0
  79. package/src/retrieval/bm25-search.js +4 -0
  80. package/src/retrieval/file-vector-store.js +4 -1
  81. package/src/retrieval/hybrid-retriever.js +4 -0
  82. package/src/retrieval/pgvector-retriever.js +420 -0
  83. package/src/retrieval/qdrant-retriever.js +361 -0
  84. package/src/security/validator.js +8 -0
  85. package/src/testing.js +2 -0
  86. package/src/utils/batch-processor.js +7 -3
  87. package/src/utils/error-formatter.js +48 -20
  88. package/src/utils/logger.js +31 -1
  89. package/src/utils/rate-limiter.js +9 -4
  90. package/src/utils/retry.js +10 -1
package/dist/index.mjs CHANGED
@@ -8,6 +8,6 @@ const require = createRequire(import.meta.url);
8
8
 
9
9
  const mod = require('./index.cjs');
10
10
 
11
- export const { createRagPipeline, createPipeline, loadConfig, loadRagConfig, validateRagrc, normalizeConfig, pluginRegistry, validatePlugin, logger, errorFormatter, createError, wrapError, ERROR_CODES, BatchProcessor, RateLimiter, retry, withRetry, ConnectionPoolManager, JWTValidator, PluginSandbox, PluginSignatureVerifier, validateInput, MultiModalProcessor, AdaptiveRetrievalEngine, FederatedLearningCoordinator, ModelTrainingOrchestrator, DAGEngine, DAG, evaluateRagDataset, scoreAnswer, computeBLEU, computeROUGE, checkNumericConsistency, extractNumbers, computeFaithfulness, computeSemanticSimilarity, computeAnswerRelevance, computeContextPrecision, computeContextRecall, computeGroundedness, PipelineEvaluator, ChunkingEngine, CitationTracker, checkAnswer, normalizeSources, createAiSdkAdapter, MemoryCache, RedisCache, mapSentenceToSources, buildIDFWeights, detectHallucinations, BM25Search, reciprocalRankFusion, HybridRetriever, FileVectorStore, PreRetrievalGuard, detectInjection, RetrievalGuard, PostGenerationGuard, GuardrailsPipeline, QueryPlanner, IterativeRetriever, SelfCritiqueChecker, AgenticPipeline, CostCalculator, PRICING_METADATA, CostTracker, TokenBudget, ExecutionTracer, TraceInspector, MCPServer, MCPToolBuilder, ProjectScaffolder, TemplateRegistry, SSEAdapter, WebSocketAdapter, StreamRouter, BaseConnector, OllamaConnector, LocalEmbedder, MemoryRetriever, OpenAIConnector, AnthropicConnector, CohereConnector, StreamingEmbedder, createEmbeddingStream, ScoringReranker, EmbeddingReranker, CascadeReranker, KnowledgeGraph, EntityExtractor, GraphRetriever, GraphIndex, DashboardGenerator, MetricsAggregator, ParallelProcessor, eventLogger, metrics, AuditLogger, DataGovernance, DataGovernanceManager, TenantManager, ResourceMonitor, SSOManager, SAMLProvider, OAuth2Provider, ActiveDirectoryProvider, OIDCProvider, PluginHub, PluginAnalytics, PluginCertification, PluginAnalyticsDashboard, HotReloadManager, createHotReloadManager, DevServer, createDevServer } = mod;
11
+ export const { createRagPipeline, createPipeline, loadConfig, loadRagConfig, validateRagrc, normalizeConfig, pluginRegistry, validatePlugin, logger, errorFormatter, createError, wrapError, ERROR_CODES, BatchProcessor, RateLimiter, retry, withRetry, ConnectionPoolManager, JWTValidator, PluginSandbox, PluginSignatureVerifier, validateInput, MultiModalProcessor, AdaptiveRetrievalEngine, FederatedLearningCoordinator, ModelTrainingOrchestrator, DAGEngine, DAG, evaluateRagDataset, scoreAnswer, computeBLEU, computeROUGE, checkNumericConsistency, extractNumbers, computeFaithfulness, computeSemanticSimilarity, validateDataset, generateSyntheticDataset, runEvaluation, compareConfigurations, evaluationVerdict, renderEvaluationReport, computeAnswerRelevance, computeContextPrecision, computeContextRecall, computeGroundedness, PipelineEvaluator, ChunkingEngine, CitationTracker, checkAnswer, normalizeSources, createAiSdkAdapter, MemoryCache, RedisCache, mapSentenceToSources, buildIDFWeights, detectHallucinations, BM25Search, reciprocalRankFusion, HybridRetriever, FileVectorStore, PreRetrievalGuard, detectInjection, RetrievalGuard, PostGenerationGuard, GuardrailsPipeline, QueryPlanner, IterativeRetriever, SelfCritiqueChecker, AgenticPipeline, CostCalculator, PRICING_METADATA, CostTracker, TokenBudget, ExecutionTracer, TraceInspector, MCPServer, MCPToolBuilder, ProjectScaffolder, TemplateRegistry, SSEAdapter, WebSocketAdapter, StreamRouter, BaseConnector, OllamaConnector, LocalEmbedder, MemoryRetriever, PgVectorRetriever, QdrantRetriever, OpenAIConnector, AnthropicConnector, CohereConnector, StreamingEmbedder, createEmbeddingStream, ScoringReranker, EmbeddingReranker, CascadeReranker, KnowledgeGraph, EntityExtractor, GraphRetriever, GraphIndex, DashboardGenerator, MetricsAggregator, ParallelProcessor, eventLogger, metrics, AuditLogger, DataGovernance, DataGovernanceManager, TenantManager, ResourceMonitor, SSOManager, SAMLProvider, OAuth2Provider, ActiveDirectoryProvider, OIDCProvider, PluginHub, PluginAnalytics, PluginCertification, PluginAnalyticsDashboard, HotReloadManager, createHotReloadManager, DevServer, createDevServer } = mod;
12
12
 
13
13
  export default mod;
@@ -41,7 +41,10 @@ export class MemoryCache {
41
41
  set(key: string, value: unknown, { ttlSeconds }?: {
42
42
  ttlSeconds?: number;
43
43
  }): Promise<void>;
44
- /** @param {string} key */
44
+ /**
45
+ * Removes a key.
46
+ * @param {string} key
47
+ */
45
48
  delete(key: string): Promise<void>;
46
49
  /** Remove every entry. */
47
50
  clear(): Promise<void>;
@@ -36,7 +36,10 @@ export class RedisCache {
36
36
  set(key: string, value: unknown, { ttlSeconds }?: {
37
37
  ttlSeconds?: number;
38
38
  }): Promise<void>;
39
- /** @param {string} key */
39
+ /**
40
+ * Removes a key.
41
+ * @param {string} key
42
+ */
40
43
  delete(key: string): Promise<void>;
41
44
  /** Hits and misses seen by this instance (size is not tracked). */
42
45
  stats(): Promise<{
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @param {Object} components - { embedder, retriever, reranker, llm }
3
+ * @returns {{ components: Object, timings: Array<{stage: string, ms: number}>, captured: { results: Array|null } }}
4
+ */
5
+ export function instrumentComponents(components: any): {
6
+ components: any;
7
+ timings: Array<{
8
+ stage: string;
9
+ ms: number;
10
+ }>;
11
+ captured: {
12
+ results: any[] | null;
13
+ };
14
+ };
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Load documents from a file or directory, embed their chunks and store them.
3
+ * Re-ingesting a source replaces its previous chunks.
4
+ *
5
+ * @param {object} params
6
+ * @param {object} params.config - Normalized config
7
+ * @param {string} params.configDir - Directory of the config file
8
+ * @param {string} params.inputPath - File or directory to ingest
9
+ * @param {boolean} [params.rebuild=false] - Discard the existing index first
10
+ * @returns {Promise<{files: number, chunks: number, totalChunks: number, sources: string[]}>}
11
+ */
12
+ export function ingest({ config, configDir, inputPath, rebuild }: {
13
+ config: object;
14
+ configDir: string;
15
+ inputPath: string;
16
+ rebuild?: boolean;
17
+ }): Promise<{
18
+ files: number;
19
+ chunks: number;
20
+ totalChunks: number;
21
+ sources: string[];
22
+ }>;
23
+ /**
24
+ * Refit a corpus-trained embedder (only the built-in `local` TF-IDF embedder)
25
+ * and re-embed every stored chunk with the new model.
26
+ *
27
+ * Without `inputPath` the embedder is fitted on the indexed chunks. With it,
28
+ * the embedder is fitted on the documents read from that path only (they are
29
+ * not added to the index); indexed chunks that share no term with the new
30
+ * vocabulary embed to all-zero vectors and are counted in `zeroVectors`.
31
+ *
32
+ * @param {object} params
33
+ * @param {object} params.config
34
+ * @param {string} params.configDir
35
+ * @param {string} [params.inputPath] - Optional training corpus
36
+ * @returns {Promise<{trainedOn: string, trainingDocuments: number, vocabularySize: number,
37
+ * previousVocabularySize: number|null, reembedded: number, zeroVectors: number}>}
38
+ */
39
+ export function retrain({ config, configDir, inputPath }: {
40
+ config: object;
41
+ configDir: string;
42
+ inputPath?: string;
43
+ }): Promise<{
44
+ trainedOn: string;
45
+ trainingDocuments: number;
46
+ vocabularySize: number;
47
+ previousVocabularySize: number | null;
48
+ reembedded: number;
49
+ zeroVectors: number;
50
+ }>;
51
+ /**
52
+ * Answer a question from the index. Without an llm stage this returns the
53
+ * retrieved passages only (answer: null) instead of a placeholder answer.
54
+ *
55
+ * @param {object} params
56
+ * @param {object} params.config
57
+ * @param {string} params.configDir
58
+ * @param {string} params.question
59
+ * @param {number} [params.topK=3]
60
+ * @param {object} [params.components] - Prebuilt components (loadComponents)
61
+ * @param {number} [params.timeout] - Abort the run after this many ms
62
+ * @param {function(string): void} [params.onToken] - Stream the answer: called
63
+ * with each token (only with an llm stage)
64
+ * @returns {Promise<{answer: string|null, results: Array, citations?: object,
65
+ * timings: Array<{stage: string, ms: number}>, durationMs: number}>}
66
+ */
67
+ export function query({ config, configDir, question, topK, components, timeout, onToken, }: {
68
+ config: object;
69
+ configDir: string;
70
+ question: string;
71
+ topK?: number;
72
+ components?: object;
73
+ timeout?: number;
74
+ onToken?: (arg0: string) => void;
75
+ }): Promise<{
76
+ answer: string | null;
77
+ results: any[];
78
+ citations?: object;
79
+ timings: Array<{
80
+ stage: string;
81
+ ms: number;
82
+ }>;
83
+ durationMs: number;
84
+ }>;
85
+ /**
86
+ * A createRagPipeline() pipeline over the configured components and index,
87
+ * for running many questions (rag-pipeline eval).
88
+ *
89
+ * @param {object} params
90
+ * @param {object} params.config
91
+ * @param {string} params.configDir
92
+ * @returns {{ pipeline: object, hasLlm: boolean }}
93
+ */
94
+ export function createPipeline({ config, configDir }: {
95
+ config: object;
96
+ configDir: string;
97
+ }): {
98
+ pipeline: object;
99
+ hasLlm: boolean;
100
+ };
101
+ /**
102
+ * Retrieval only (no llm): embed the question, retrieve and, if configured,
103
+ * rerank.
104
+ *
105
+ * @param {object} params
106
+ * @param {object} [params.components] - Prebuilt components (loadComponents)
107
+ * @param {object} [params.config]
108
+ * @param {string} [params.configDir]
109
+ * @param {string} params.question
110
+ * @param {number} [params.topK=3]
111
+ * @returns {Promise<Array<{id: string, score: number, content: string, metadata: object}>>}
112
+ */
113
+ export function retrieve({ components, config, configDir, question, topK }: {
114
+ components?: object;
115
+ config?: object;
116
+ configDir?: string;
117
+ question: string;
118
+ topK?: number;
119
+ }): Promise<Array<{
120
+ id: string;
121
+ score: number;
122
+ content: string;
123
+ metadata: object;
124
+ }>>;
125
+ /**
126
+ * Build the configured components once and restore the embedder state saved
127
+ * with the index, so they can be reused across several retrieve()/query()
128
+ * calls (e.g. by `ai benchmark`).
129
+ *
130
+ * @returns {object} Components as returned by buildComponents()
131
+ */
132
+ export function loadComponents({ config, configDir }: {
133
+ config: any;
134
+ configDir: any;
135
+ }): object;
136
+ /**
137
+ * Restore embedder state saved with the index (e.g. LocalEmbedder's
138
+ * vocabulary), so queries embed into the same vector space as ingestion.
139
+ */
140
+ export function restoreEmbedder(embedder: any, retriever: any): void;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @param {object} globalOptions - program.opts(); uses globalOptions.config
3
+ * @returns {{config: object, configPath: string, configDir: string}}
4
+ */
5
+ export function loadCliConfig(globalOptions?: object): {
6
+ config: object;
7
+ configPath: string;
8
+ configDir: string;
9
+ };
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Turn a normalized .ragrc.json config into component instances.
3
+ *
4
+ * Each `pipeline` entry `{ stage, name, config }` is resolved in order:
5
+ * 1. a built-in name (see BUILT_INS),
6
+ * 2. a custom module path under `plugins.<stage>.<name>`,
7
+ * 3. a plugin registered on the shared pluginRegistry.
8
+ *
9
+ * @param {object} config - Output of loadRagConfig()/validateRagrc().normalized
10
+ * @param {object} [options]
11
+ * @param {string} [options.configDir=process.cwd()] - Paths resolve relative to this
12
+ * @returns {{embedder?: object, retriever?: object, llm?: object, reranker?: object, loader?: object, names: object}}
13
+ */
14
+ export function buildComponents(config: object, options?: {
15
+ configDir?: string;
16
+ }): {
17
+ embedder?: object;
18
+ retriever?: object;
19
+ llm?: object;
20
+ reranker?: object;
21
+ loader?: object;
22
+ names: object;
23
+ };
24
+ /**
25
+ * Instantiate a custom plugin from `plugins.<stage>.<name>` in the config.
26
+ * The module may export a class (constructed with the entry config), an
27
+ * instance, or either of those as `default`.
28
+ */
29
+ export function loadPluginModule(modulePath: any, entryConfig: any, configDir: any): any;
30
+ export namespace BUILT_INS {
31
+ namespace loader {
32
+ function auto(): typeof import("../loader/document-reader");
33
+ }
34
+ namespace embedder {
35
+ function local(cfg: any): import("../connectors/local-embedder").LocalEmbedder;
36
+ function openai(cfg: any): import("../connectors/openai-connector").OpenAIConnector;
37
+ function ollama(cfg: any): import("../connectors/ollama-connector").OllamaConnector;
38
+ function cohere(cfg: any): import("../connectors/cohere-connector").CohereConnector;
39
+ }
40
+ let retriever: {
41
+ "file-store": (cfg: any, configDir: any) => import("../retrieval/file-vector-store").FileVectorStore;
42
+ memory: (cfg: any) => import("../connectors/memory-retriever").MemoryRetriever;
43
+ pgvector: (cfg: any) => import("../retrieval/pgvector-retriever").PgVectorRetriever;
44
+ qdrant: (cfg: any) => import("../retrieval/qdrant-retriever").QdrantRetriever;
45
+ };
46
+ namespace llm {
47
+ export function openai_1(cfg: any): import("../connectors/openai-connector").OpenAIConnector;
48
+ export { openai_1 as openai };
49
+ export function anthropic(cfg: any): import("../connectors/anthropic-connector").AnthropicConnector;
50
+ export function ollama_1(cfg: any): import("../connectors/ollama-connector").OllamaConnector;
51
+ export { ollama_1 as ollama };
52
+ }
53
+ namespace reranker {
54
+ function scoring(cfg: any): import("../reranker/scoring-reranker").ScoringReranker;
55
+ }
56
+ }
57
+ export const STAGES: string[];