@devilsdev/rag-pipeline-utils 2.3.0 → 2.4.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 (160) hide show
  1. package/README.md +293 -361
  2. package/contracts/loader-contract.json +11 -6
  3. package/contracts/reranker-contract.json +18 -26
  4. package/dist/index.cjs +21190 -47
  5. package/dist/index.d.ts +298 -68
  6. package/dist/index.mjs +9 -76
  7. package/package.json +20 -8
  8. package/src/agentic/agentic-pipeline.js +235 -0
  9. package/src/agentic/iterative-retriever.js +213 -0
  10. package/src/agentic/query-planner.js +208 -0
  11. package/src/agentic/self-critique.js +102 -0
  12. package/src/ai/adaptive-retrieval.js +0 -3
  13. package/src/ai/federated-learning.js +0 -3
  14. package/src/ai/federation.js +1 -6
  15. package/src/ai/index.js +9 -20
  16. package/src/ai/model-training.js +0 -3
  17. package/src/ai/multimodal-processing.js +0 -3
  18. package/src/ai/multimodal.js +1 -6
  19. package/src/ai/orchestrator.js +1 -6
  20. package/src/ai/retrieval-engine.js +1 -6
  21. package/src/chunking/chunking-engine.js +142 -0
  22. package/src/chunking/strategies/fixed-size.js +54 -0
  23. package/src/chunking/strategies/recursive.js +127 -0
  24. package/src/chunking/strategies/semantic.js +128 -0
  25. package/src/chunking/strategies/sentence.js +32 -0
  26. package/src/chunking/strategies/structure-aware.js +138 -0
  27. package/src/citation/citation-tracker.js +161 -0
  28. package/src/citation/hallucination-detector.js +74 -0
  29. package/src/citation/source-mapper.js +95 -0
  30. package/src/cli/commands/ai-ml/adaptive-commands.js +178 -0
  31. package/src/cli/commands/ai-ml/federated-commands.js +207 -0
  32. package/src/cli/commands/ai-ml/index.js +17 -0
  33. package/src/cli/commands/ai-ml/multimodal-commands.js +187 -0
  34. package/src/cli/commands/ai-ml/shared.js +51 -0
  35. package/src/cli/commands/ai-ml/training-commands.js +228 -0
  36. package/src/cli/commands/ai-ml.js +176 -757
  37. package/src/cli/commands/plugin-hub/certification-commands.js +221 -0
  38. package/src/cli/commands/plugin-hub/event-handlers.js +64 -0
  39. package/src/cli/commands/plugin-hub/hub-commands.js +290 -0
  40. package/src/cli/commands/plugin-hub/review-commands.js +78 -0
  41. package/src/cli/commands/plugin-hub.js +106 -782
  42. package/src/cli/diagnostics/config-checker.js +81 -0
  43. package/src/cli/diagnostics/dependency-checker.js +69 -0
  44. package/src/cli/diagnostics/environment-checker.js +45 -0
  45. package/src/cli/diagnostics/performance-checker.js +51 -0
  46. package/src/cli/diagnostics/plugin-checker.js +106 -0
  47. package/src/cli/diagnostics/security-checker.js +61 -0
  48. package/src/cli/doctor-command.js +70 -369
  49. package/src/cli/enhanced-cli-commands.js +162 -706
  50. package/src/cli/handlers/config-handler.js +126 -0
  51. package/src/cli/handlers/diagnostics-handler.js +113 -0
  52. package/src/cli/handlers/ingest-handler.js +42 -0
  53. package/src/cli/handlers/init-handler.js +51 -0
  54. package/src/cli/handlers/query-handler.js +45 -0
  55. package/src/cli/handlers/run-handler.js +181 -0
  56. package/src/cli/interactive-wizard.js +99 -723
  57. package/src/cli/shared/cli-utils.js +89 -0
  58. package/src/cli/wizard/configuration.js +148 -0
  59. package/src/cli/wizard/observability.js +79 -0
  60. package/src/cli/wizard/performance.js +76 -0
  61. package/src/cli/wizard/plugin-selection.js +297 -0
  62. package/src/cli/wizard/preview-save.js +172 -0
  63. package/src/cli/wizard/project-setup.js +66 -0
  64. package/src/config/memory-optimization.js +3 -3
  65. package/src/connectors/anthropic-connector.js +179 -0
  66. package/src/connectors/base-connector.js +94 -0
  67. package/src/connectors/cohere-connector.js +143 -0
  68. package/src/connectors/local-embedder.js +171 -0
  69. package/src/connectors/memory-retriever.js +150 -0
  70. package/src/connectors/ollama-connector.js +205 -0
  71. package/src/connectors/openai-connector.js +173 -0
  72. package/src/core/create-pipeline.js +21 -1
  73. package/src/core/observability/tracing.js +2 -1
  74. package/src/core/pipeline-factory.js +0 -1
  75. package/src/core/plugin-registry.js +14 -14
  76. package/src/cost/cost-calculator.js +146 -0
  77. package/src/cost/cost-tracker.js +260 -0
  78. package/src/cost/token-budget.js +245 -0
  79. package/src/dag/core/execution-scheduler.js +2 -1
  80. package/src/dag/core/topology-validation.js +0 -3
  81. package/src/dag/dag-engine.js +3 -5
  82. package/src/dag/dag-node.js +0 -1
  83. package/src/dag/enhanced-dag-engine.js +171 -99
  84. package/src/dashboard/dashboard-generator.js +642 -0
  85. package/src/dashboard/metrics-aggregator.js +409 -0
  86. package/src/debug/execution-tracer.js +210 -0
  87. package/src/debug/trace-inspector.js +281 -0
  88. package/src/dev/dev-server.js +5 -5
  89. package/src/dev/hot-reload.js +3 -2
  90. package/src/dx/integration-templates.js +0 -3
  91. package/src/ecosystem/plugin-analytics-dashboard.js +2 -2
  92. package/src/ecosystem/plugin-hub.js +2 -2
  93. package/src/enterprise/audit-logging.js +2 -2
  94. package/src/enterprise/sso-integration.js +52 -32
  95. package/src/evaluate/context-metrics.js +127 -0
  96. package/src/evaluate/evaluator.js +4 -2
  97. package/src/evaluate/faithfulness.js +117 -0
  98. package/src/evaluate/groundedness.js +60 -0
  99. package/src/evaluate/pipeline-evaluator.js +156 -0
  100. package/src/evaluate/relevance.js +129 -0
  101. package/src/evaluate/scoring.js +27 -0
  102. package/src/graph/entity-extractor.js +183 -0
  103. package/src/graph/graph-index.js +113 -0
  104. package/src/graph/graph-retriever.js +244 -0
  105. package/src/graph/knowledge-graph.js +256 -0
  106. package/src/guardrails/guardrails-pipeline.js +136 -0
  107. package/src/guardrails/post-generation-guard.js +170 -0
  108. package/src/guardrails/pre-retrieval-guard.js +161 -0
  109. package/src/guardrails/retrieval-guard.js +126 -0
  110. package/src/index.js +255 -9
  111. package/src/loader/html-loader.js +4 -15
  112. package/src/loader/markdown-loader.js +4 -15
  113. package/src/mcp/mcp-server.js +199 -0
  114. package/src/mcp/mcp-tool-builder.js +121 -0
  115. package/src/observability/audit-logger.js +0 -2
  116. package/src/observability/event-logger.js +2 -1
  117. package/src/observability/security-monitor.js +0 -2
  118. package/src/observability/telemetry.js +0 -2
  119. package/src/reranker/cascade-reranker.js +79 -0
  120. package/src/reranker/embedding-reranker.js +124 -0
  121. package/src/reranker/llm-reranker.js +6 -3
  122. package/src/reranker/scoring-reranker.js +123 -0
  123. package/src/retrieval/bm25-search.js +157 -0
  124. package/src/retrieval/hybrid-retriever.js +111 -0
  125. package/src/retrieval/rank-fusion.js +62 -0
  126. package/src/security/jwt-config.js +4 -3
  127. package/src/security/jwt-validator.js +2 -1
  128. package/src/security/plugin-sandbox.js +0 -3
  129. package/src/security/plugin-signature-verifier.js +4 -6
  130. package/src/security/validator.js +0 -2
  131. package/src/streaming/embedding-stream.js +197 -0
  132. package/src/streaming/sse-adapter.js +168 -0
  133. package/src/streaming/stream-router.js +210 -0
  134. package/src/streaming/streaming-embedder.js +231 -0
  135. package/src/streaming/websocket-adapter.js +171 -0
  136. package/src/templates/scaffold.js +147 -0
  137. package/src/templates/template-registry.js +272 -0
  138. package/src/utils/contract-validator.js +2 -1
  139. package/src/utils/input-sanitizer.js +80 -99
  140. package/src/utils/performance-monitor.js +0 -3
  141. package/src/utils/plugin-scaffolder.js +9 -16
  142. package/src/utils/rate-limiter.js +0 -1
  143. package/src/utils/retry-policy.js +0 -3
  144. package/src/utils/safe-expression-evaluator.js +0 -3
  145. package/src/utils/secure-logger-config.js +2 -4
  146. package/src/utils/secure-logging.js +0 -3
  147. package/src/utils/structured-logger.js +0 -3
  148. package/src/ai/index-fixed.js +0 -509
  149. package/src/ai/module-template.js +0 -37
  150. package/src/ci/workflow-analyzer.js +0 -71
  151. package/src/cli/plugin-marketplace-commands.js +0 -869
  152. package/src/dev/README.md +0 -126
  153. package/src/dev/examples/hot-reload-usage.js +0 -355
  154. package/src/mocks/openai-embedder.js +0 -119
  155. package/src/mocks/openai-llm.js +0 -77
  156. package/src/mocks/pdf-loader.js +0 -21
  157. package/src/mocks/pinecone-retriever.js +0 -106
  158. package/src/scripts/script-utilities.js +0 -36
  159. package/src/utils/ci/diagnostic-reporter.js +0 -57
  160. package/src/utils/examples/error-formatter-usage.js +0 -351
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # rag-pipeline-utils
2
2
 
3
- **Modular toolkit for building production-ready RAG pipelines in Node.js**
3
+ **The comprehensive Node.js toolkit for building production-ready RAG pipelines — with built-in evaluation, citation tracking, agentic reasoning, guardrails, and 7 provider connectors.**
4
4
 
5
5
  [![CI](https://github.com/DevilsDev/rag-pipeline-utils/actions/workflows/ci.yml/badge.svg)](https://github.com/DevilsDev/rag-pipeline-utils/actions)
6
6
  [![npm version](https://badge.fury.io/js/%40devilsdev%2Frag-pipeline-utils.svg)](https://www.npmjs.com/package/@devilsdev/rag-pipeline-utils)
@@ -8,468 +8,418 @@
8
8
  [![License: GPL-3.0](https://img.shields.io/badge/License-GPL%203.0-blue.svg)](https://opensource.org/licenses/GPL-3.0)
9
9
  [![Node.js Version](https://img.shields.io/node/v/@devilsdev/rag-pipeline-utils.svg)](https://nodejs.org/)
10
10
  [![Downloads](https://img.shields.io/npm/dm/@devilsdev/rag-pipeline-utils.svg)](https://www.npmjs.com/package/@devilsdev/rag-pipeline-utils)
11
- [![GitHub Discussions](https://img.shields.io/github/discussions/DevilsDev/rag-pipeline-utils)](https://github.com/DevilsDev/rag-pipeline-utils/discussions)
12
11
 
13
12
  ---
14
13
 
15
14
  ## Why This Exists
16
15
 
17
- Building Retrieval-Augmented Generation (RAG) systems is harder than it should be. Most solutions lock you into specific vendors, force opinionated architectures, or sacrifice observability for simplicity.
16
+ Building RAG systems in Node.js shouldn't require stitching together Python tools or reinventing every component. **rag-pipeline-utils** gives you the complete stack in one package: loaders, embedders, retrievers, LLM connectors, rerankers, evaluation, citation tracking, guardrails, and agentic reasoning.
18
17
 
19
- **rag-pipeline-utils** takes a different approach: it provides the building blocks—loaders, embedders, retrievers, LLM connectors, and rerankers—that you compose into pipelines that fit your needs. Every component follows clear contracts. Every integration is optional. Every decision is yours.
18
+ Every component follows clear contracts. Every integration is optional. Every decision is yours.
20
19
 
21
- We built this toolkit because we believe infrastructure should be:
22
-
23
- - **Modular** – swap any component without rewriting your pipeline
24
- - **Observable** – metrics, tracing, and audit logs built in from day one
25
- - **Secure** – hardened JWT validation with replay protection, multi-layer path traversal defense, and enterprise-grade defaults
26
- - **Open** – no vendor lock-in, no proprietary APIs, just JavaScript
27
-
28
- Whether you're prototyping a document Q&A system or scaling a production knowledge base, this toolkit grows with you.
20
+ - **Modular** -- swap any component without rewriting your pipeline
21
+ - **Evaluated** -- built-in faithfulness, relevance, and groundedness metrics on every run
22
+ - **Safe** -- 3-layer guardrails with prompt injection detection, PII filtering, and source grounding
23
+ - **Observable** -- OpenTelemetry tracing, Prometheus metrics, and compliance-grade audit logs
24
+ - **Connected** -- OpenAI, Anthropic, Cohere, Ollama, or bring your own
29
25
 
30
26
  ---
31
27
 
32
28
  ## Quick Start
33
29
 
34
- Here's a complete RAG pipeline in 15 lines:
35
-
36
- ```javascript
37
- const { createRagPipeline } = require("@devilsdev/rag-pipeline-utils");
38
-
39
- // Implement your plugins (or use existing ones)
40
- const pipeline = createRagPipeline({
41
- loader: new MyPDFLoader(),
42
- embedder: new MyOpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY }),
43
- retriever: new MyVectorDBRetriever({ url: "http://localhost:8000" }),
44
- llm: new MyLLMConnector({ model: "gpt-4" }),
45
- });
46
-
47
- // Ingest documents
48
- await pipeline.ingest("./company-docs.pdf");
49
-
50
- // Query with natural language
51
- const answer = await pipeline.query("What is the vacation policy?");
52
- console.log(answer.text);
53
- // Output: "Based on the company handbook, employees receive 20 days of vacation per year..."
54
- ```
55
-
56
- **Requirements:** Node.js >= 18.0.0
57
-
58
- Install with:
59
-
60
30
  ```bash
61
31
  npm install @devilsdev/rag-pipeline-utils
62
32
  ```
63
33
 
64
- ### What's New in v2.3.0 (Released November 7, 2025)
34
+ Build a RAG pipeline with built-in connectors:
65
35
 
66
- **Major Security Enhancements:**
36
+ ```javascript
37
+ const {
38
+ createRagPipeline,
39
+ OpenAIConnector,
40
+ MemoryRetriever,
41
+ } = require("@devilsdev/rag-pipeline-utils");
67
42
 
68
- - **Advanced JWT replay protection** with self-signed token reusability
69
- - **Hardened path traversal defense** with iterative URL decoding
70
- - **Consistent validation behavior** eliminating duplicate checks
71
- - **Race condition mitigation** in concurrent token verification
43
+ const llm = new OpenAIConnector({ apiKey: process.env.OPENAI_API_KEY });
44
+ const retriever = new MemoryRetriever();
72
45
 
73
- **All security tests passing:** 113 security-focused tests with 100% coverage on critical paths.
46
+ const pipeline = createRagPipeline({ retriever, llm });
74
47
 
75
- [See full security details below](#security-and-quality) | [Migration guide](#upgrading-from-v22x)
48
+ const result = await pipeline.run({
49
+ query: "What is the vacation policy?",
50
+ options: { citations: true, evaluate: true },
51
+ });
76
52
 
77
- ---
53
+ console.log(result.results);
54
+ // Retrieved documents
55
+ console.log(result.citations?.groundednessScore);
56
+ // 0.85 -- how well the answer is grounded in sources
57
+ console.log(result.evaluation?.scores);
58
+ // { faithfulness: 0.9, relevance: 0.8, contextPrecision: 0.7, ... }
59
+ ```
78
60
 
79
- ## How It Works
61
+ **Requirements:** Node.js >= 18.0.0
80
62
 
81
- **rag-pipeline-utils** orchestrates data through a clear, predictable flow:
63
+ ---
64
+
65
+ ## Architecture
82
66
 
83
67
  ```mermaid
84
68
  graph LR
85
- A[Documents] --> B[Loader]
69
+ A[Documents] --> B[Chunking Engine]
86
70
  B --> C[Embedder]
87
71
  C --> D[Vector Store]
88
- D --> E[Retriever]
89
- F[User Query] --> C
90
- F --> E
91
- E --> G[Reranker]
92
- G --> H[LLM]
93
- H --> I[Response]
72
+
73
+ F[User Query] --> G{Guardrails}
74
+ G --> H[Query Planner]
75
+ H --> E[Retriever + BM25]
76
+ E --> I[Reranker]
77
+ I --> J[LLM]
78
+ J --> K{Citation Tracker}
79
+ K --> L{Evaluator}
80
+ L --> M[Response]
94
81
 
95
82
  style B fill:#e1f5e1
96
- style C fill:#e1f5e1
97
83
  style E fill:#e1f5e1
98
84
  style G fill:#fff4e1
99
- style H fill:#e1f5e1
100
- style I fill:#e3f2fd
85
+ style H fill:#fff4e1
86
+ style K fill:#e3f2fd
87
+ style L fill:#e3f2fd
101
88
  ```
102
89
 
103
- 1. **Loader** – Parse documents (PDF, HTML, Markdown, etc.)
104
- 2. **Embedder** – Convert text to vector embeddings
105
- 3. **Vector Store** – Index and persist embeddings
106
- 4. **Retriever** – Find semantically similar content
107
- 5. **Reranker** (optional) – Refine retrieval results
108
- 6. **LLM** – Generate contextual responses
90
+ **Pipeline stages:** Chunk --> Embed --> Store --> Retrieve --> Rerank --> Generate --> Cite --> Evaluate
109
91
 
110
- Every component is replaceable. Every step is observable.
92
+ Each stage is optional, pluggable, and observable. Enable citation tracking and evaluation with a single option flag.
111
93
 
112
94
  ---
113
95
 
114
96
  ## Features
115
97
 
116
- ### Modular Plugin Architecture
117
-
118
- Swap any component without rewriting your pipeline. Use OpenAI embeddings with Pinecone storage, or mix Hugging Face models with PostgreSQL—your choice.
119
-
120
- ### Enterprise Observability
121
-
122
- Built-in structured logging, Prometheus metrics, OpenTelemetry tracing, and audit logs for compliance-grade transparency.
123
-
124
- ### DAG Workflow Engine
125
-
126
- Chain complex multi-step operations with retry logic, parallel execution, and graceful error handling. Perfect for batch ingestion or multi-stage transformations.
127
-
128
- ### Type-Safe Contracts
98
+ ### Plugin Architecture
129
99
 
130
- Complete TypeScript interfaces for all plugin types. Full IDE autocomplete and compile-time validation.
131
-
132
- ### Production-Ready Security
133
-
134
- Hardened security with defense-in-depth: JWT replay protection with race condition mitigation, multi-layer path traversal defense with iterative URL decoding, validated JSON parsing, algorithm whitelisting, automatic secret redaction, and comprehensive audit logging.
135
-
136
- ### Streaming & Batching
137
-
138
- Stream LLM responses in real-time. Batch embed thousands of documents efficiently with parallel processing and backpressure control.
139
-
140
- ### Framework Agnostic
141
-
142
- Works with Express, Fastify, Next.js, or any Node.js runtime. Deploy to AWS Lambda, Vercel, Docker, or bare metal.
143
-
144
- ---
100
+ Five plugin types with JSON Schema contracts: **loader**, **embedder**, **retriever**, **llm**, and **reranker**. Register, validate, and swap components at runtime.
145
101
 
146
- ## Join the Community
147
-
148
- We're building this together.
149
-
150
- Whether you're implementing a new retriever, writing documentation, reporting bugs, or sharing ideas—every contribution makes this toolkit better for everyone.
151
-
152
- **Getting Started:**
153
-
154
- - [GitHub Discussions](https://github.com/DevilsDev/rag-pipeline-utils/discussions) – Ask questions, share use cases, propose features
155
- - [Issue Tracker](https://github.com/DevilsDev/rag-pipeline-utils/issues) – Report bugs or request features
156
- - [Contributing Guide](https://github.com/DevilsDev/rag-pipeline-utils/blob/main/docs/CONTRIBUTING.md) – Learn how to submit pull requests
157
- - [Code of Conduct](https://github.com/DevilsDev/rag-pipeline-utils/blob/main/CODE_OF_CONDUCT.md) – Our community standards
158
-
159
- **Good First Issues:** Look for issues tagged `good first issue` to find beginner-friendly contributions.
160
-
161
- **Office Hours:** Join our monthly community calls to discuss roadmap priorities and architectural decisions.
162
-
163
- ---
164
-
165
- ## Security and Quality
166
-
167
- Security isn't optional. This toolkit is built with defense in depth:
168
-
169
- ### Core Security Features
170
-
171
- - **Validated Inputs** – All JSON parsed through schema validation (AJV)
172
- - **Secure Logging** – Automatic redaction of 36 sensitive field patterns (API keys, JWTs, tokens)
173
- - **JWT Best Practices** – Algorithm whitelisting, issuer/audience validation, expiration enforcement
174
- - **Dependency Scanning** – Weekly Dependabot updates, CI blocks on critical vulnerabilities
175
- - **Audit Trail** – Immutable compliance-grade logs for all security-sensitive operations
176
- - **Plugin Sandboxing** – Third-party plugins run with declared permissions and resource limits
177
- - **Supply Chain Security** – All GitHub Actions pinned to commit SHAs, SBOM generation available
178
-
179
- ### Recent Security Enhancements (v2.3.0)
180
-
181
- #### Hardened JWT Validation
182
-
183
- **Advanced Replay Protection:**
184
-
185
- - Self-signed tokens can be verified multiple times (essential for refresh flows and load balancer retries)
186
- - External tokens are tracked and blocked on replay attempts
187
- - Race condition mitigation with optimized check-then-set pattern
188
- - Separate tracking for reusable vs. single-use tokens
189
-
190
- **Consistent Validation Behavior:**
102
+ ```javascript
103
+ const { pluginRegistry } = require("@devilsdev/rag-pipeline-utils");
104
+ pluginRegistry.register("llm", "my-model", MyCustomLLM);
105
+ ```
191
106
 
192
- - `strictValidation` flag now consistently controls issuer/audience validation
193
- - Eliminated duplicate validation logic to prevent configuration confusion
194
- - Clear separation of concerns: jsonwebtoken handles cryptographic validation, custom logic handles business rules
107
+ ### Smart Chunking
195
108
 
196
- **Example:**
109
+ Five built-in strategies for document splitting: `sentence`, `fixed-size`, `recursive` (default, 512 chars), `semantic` (topic-boundary detection), and `structure-aware` (respects Markdown headers, HTML sections, code blocks).
197
110
 
198
111
  ```javascript
199
- const { JWTValidator } = require("@devilsdev/rag-pipeline-utils");
200
-
201
- const validator = new JWTValidator({
202
- secret: process.env.JWT_SECRET,
203
- algorithm: "HS256",
204
- issuer: "my-app",
205
- audience: "api-users",
206
- strictValidation: true, // Enforces iss/aud validation
207
- enableJtiTracking: true, // Prevents replay attacks
112
+ const { ChunkingEngine } = require("@devilsdev/rag-pipeline-utils");
113
+ const engine = new ChunkingEngine({
114
+ strategy: "recursive",
115
+ chunkSize: 512,
116
+ chunkOverlap: 50,
208
117
  });
209
-
210
- // Self-signed tokens can be verified multiple times
211
- const token = validator.sign({ sub: "user-123" });
212
- validator.verify(token); // First verification
213
- validator.verify(token); // Still works (refresh flow)
214
-
215
- // External tokens are blocked on replay
216
- const externalToken = getTokenFromThirdParty();
217
- validator.verify(externalToken); // First use
218
- validator.verify(externalToken); // Throws "Token replay detected"
118
+ const chunks = engine.chunk(documentText);
219
119
  ```
220
120
 
221
- #### Path Traversal Defense
222
-
223
- **Multi-Layer Protection:**
121
+ ### Hybrid Retrieval
224
122
 
225
- - Iterative URL decoding (up to 5 passes) to catch sophisticated encoding attacks
226
- - Detects double-encoded paths: `%252e%252e%252f` → `%2e%2e%2f` → `../`
227
- - Malformed encoding treated as attack indicator (throws error)
228
- - Critical security violations always throw, regardless of configuration
229
-
230
- **Attack Vectors Blocked:**
231
-
232
- - Standard traversal: `../../../etc/passwd`
233
- - Windows paths: `..\..\windows\system32`
234
- - URL encoded: `%2e%2e%2f`, `%2e%2e%5c`
235
- - Double encoded: `%252e%252e%252f`
236
- - Mixed encoding: combinations of above
237
-
238
- **Example:**
123
+ Combine vector similarity with BM25 keyword search using Reciprocal Rank Fusion. Run multiple retrievers in parallel with graceful degradation.
239
124
 
240
125
  ```javascript
241
- const { sanitizePath } = require("@devilsdev/rag-pipeline-utils");
242
-
243
- // Safe paths are normalized
244
- sanitizePath("docs/README.md"); // Returns: "docs/README.md"
245
-
246
- // Dangerous paths throw errors
247
- sanitizePath("../../../etc/passwd"); // Throws
248
- sanitizePath("%2e%2e%2f%2e%2e%2fpasswd"); // Throws
249
- sanitizePath("%252e%252e%252fconfig"); // Throws (double-encoded)
126
+ const {
127
+ BM25Search,
128
+ HybridRetriever,
129
+ } = require("@devilsdev/rag-pipeline-utils");
130
+ const bm25 = new BM25Search();
131
+ bm25.index(documents);
132
+
133
+ const hybrid = new HybridRetriever([
134
+ { retriever: vectorRetriever, weight: 0.7, name: "vector" },
135
+ { retriever: bm25, weight: 0.3, name: "keyword" },
136
+ ]);
137
+ const results = await hybrid.retrieve({ query });
250
138
  ```
251
139
 
252
- #### Defense-in-Depth Architecture
253
-
254
- **Critical Security Errors:**
140
+ ### RAG Evaluation
255
141
 
256
- - Path traversal violations **always throw**, even if `throwOnInvalid=false`
257
- - Object depth limit violations **always throw** to prevent DoS
258
- - Security-critical operations are prioritized over configuration flexibility
142
+ Measure pipeline quality with five built-in metrics: **faithfulness**, **answer relevance**, **context precision**, **context recall**, and **groundedness**. Run automatically on every pipeline execution or standalone.
259
143
 
260
- **Security Monitoring:**
144
+ ```javascript
145
+ const { PipelineEvaluator } = require("@devilsdev/rag-pipeline-utils");
146
+ const evaluator = new PipelineEvaluator();
147
+ const metrics = evaluator.evaluate({ query, answer, results: retrievedDocs });
148
+ // metrics.scores.faithfulness, metrics.scores.relevance, etc.
149
+ ```
261
150
 
262
- - All blocked attempts tracked in `stats.blocked` counter
263
- - Audit events emitted for replay detection, algorithm mismatches, and validation failures
264
- - Structured logging with security event correlation
151
+ Or inline: `pipeline.run({ query, options: { evaluate: true } })`
265
152
 
266
- ### Quality Metrics
153
+ ### Citation & Grounding
267
154
 
268
- **Zero Production Vulnerabilities:** `npm audit --production` returns clean on every release.
155
+ Track which source documents support each claim. Detect hallucinations automatically. Get a groundedness score for every answer.
269
156
 
270
- **Test Coverage:** 113 security-focused tests across 2 dedicated security suites:
157
+ ```javascript
158
+ const { CitationTracker } = require("@devilsdev/rag-pipeline-utils");
159
+ const tracker = new CitationTracker();
160
+ const result = tracker.track(answer, retrievedDocs);
161
+ // result.groundednessScore, result.citations, result.hallucinationReport
162
+ ```
271
163
 
272
- - JWT Validator: 44 tests covering algorithm confusion, replay attacks, and validation edge cases
273
- - Input Sanitizer: 69 tests covering XSS, SQL injection, command injection, and path traversal
164
+ ### Agentic RAG
274
165
 
275
- **Supported Node Versions:** 18.x, 20.x, 22.x (tested in CI)
166
+ Multi-step retrieval with query decomposition, iterative search, and self-critique. The agent splits complex questions into sub-queries, retrieves evidence in parallel via the DAG engine, and validates its own answer before returning.
276
167
 
277
- ---
168
+ ```javascript
169
+ const { AgenticPipeline } = require("@devilsdev/rag-pipeline-utils");
170
+ const agent = new AgenticPipeline({
171
+ enableCritique: true,
172
+ enablePlanning: true,
173
+ });
174
+ const result = await agent.run({
175
+ query: "Compare all three competitors",
176
+ retriever,
177
+ llm,
178
+ });
179
+ // result.subQueries, result.critique, result.answer
180
+ ```
278
181
 
279
- ## Installation & Development
182
+ ### 3-Layer Guardrails
280
183
 
281
- ### Install
184
+ Wrap any pipeline with production safety: **pre-retrieval** (prompt injection detection, topic filtering), **retrieval-time** (relevance threshold, ACL filtering, freshness), and **post-generation** (PII detection, groundedness check, length validation).
282
185
 
283
- ```bash
284
- npm install @devilsdev/rag-pipeline-utils
186
+ ```javascript
187
+ const { GuardrailsPipeline } = require("@devilsdev/rag-pipeline-utils");
188
+ const safePipeline = new GuardrailsPipeline(pipeline, {
189
+ preRetrieval: { enableInjectionDetection: true },
190
+ retrieval: { minRelevanceScore: 0.6 },
191
+ postGeneration: { enablePIIDetection: true, enableGroundednessCheck: true },
192
+ });
193
+ const result = await safePipeline.run({ query });
285
194
  ```
286
195
 
287
- ### Development Setup
196
+ ### Streaming
288
197
 
289
- ```bash
290
- # Clone the repository
291
- git clone https://github.com/DevilsDev/rag-pipeline-utils.git
292
- cd rag-pipeline-utils
198
+ Stream LLM responses in real-time via Server-Sent Events or WebSocket. The `StreamRouter` auto-detects transport and handles backpressure.
293
199
 
294
- # Install dependencies
295
- npm install
200
+ ```javascript
201
+ const { StreamRouter } = require("@devilsdev/rag-pipeline-utils");
202
+ const router = new StreamRouter();
296
203
 
297
- # Run tests
298
- npm test
204
+ // Express example
205
+ app.get("/api/stream", async (req, res) => {
206
+ await router.streamSSE(pipeline, req.query.q, res);
207
+ });
208
+ ```
299
209
 
300
- # Run linter
301
- npm run lint
210
+ ### Provider Connectors
302
211
 
303
- # Build distribution
304
- npm run build
212
+ Seven built-in connectors -- drop into any pipeline with zero configuration:
305
213
 
306
- # Run development tools
307
- npm run dev
214
+ ```javascript
215
+ const {
216
+ OpenAIConnector, // GPT-4, GPT-3.5, text-embedding-3
217
+ AnthropicConnector, // Claude 3 Opus, Sonnet, Haiku
218
+ CohereConnector, // Embed + Rerank
219
+ OllamaConnector, // Llama 3, Mistral (local)
220
+ LocalEmbedder, // TF-IDF (offline, no API)
221
+ MemoryRetriever, // In-memory cosine similarity
222
+ } = require("@devilsdev/rag-pipeline-utils");
223
+
224
+ const ollama = new OllamaConnector({
225
+ model: "llama3",
226
+ baseURL: "http://localhost:11434",
227
+ });
228
+ const openai = new OpenAIConnector({ apiKey: process.env.OPENAI_API_KEY });
308
229
  ```
309
230
 
310
- ### Common Commands
231
+ ### Cost Management
311
232
 
312
- ```bash
313
- npm test # Run test suite
314
- npm run test:watch # Watch mode for TDD
315
- npm run lint # Check code style
316
- npm run lint:fix # Auto-fix linting issues
317
- npm run security:audit # Scan dependencies
318
- npm run docs:api # Generate API documentation
319
- npm run benchmark # Performance benchmarks
320
- ```
233
+ Track token spend per provider, estimate costs before execution, and enforce budgets with hard and soft limits.
321
234
 
322
- ---
235
+ ```javascript
236
+ const {
237
+ CostCalculator,
238
+ TokenBudget,
239
+ } = require("@devilsdev/rag-pipeline-utils");
240
+ const calc = new CostCalculator();
241
+ const cost = calc.estimate("gpt-4", 2000, 500);
242
+ // cost.totalCost = 0.09 (USD)
243
+
244
+ const budget = new TokenBudget({ maxTokens: 100000 });
245
+ budget.record(2500);
246
+ budget.check(1000); // { allowed: true, remaining: { tokens: 96500 } }
247
+ ```
323
248
 
324
- ## Roadmap
249
+ ### Pipeline Debugging
325
250
 
326
- ### v2.3.0 (Q2 2025)
251
+ Trace every execution step with timing, bottleneck detection, and optimization recommendations.
327
252
 
328
- - **Enhanced CLI** – Interactive wizard for pipeline setup, validation commands, and migration tools
329
- - **Plugin Marketplace** – Curated registry of community-contributed plugins with ratings and verification
330
- - **Streaming Embeddings** – Real-time embedding generation with backpressure control
331
- - **Multi-Tenant Support** – Workspace isolation, resource quotas, and tenant-specific configurations
253
+ ```javascript
254
+ const {
255
+ ExecutionTracer,
256
+ TraceInspector,
257
+ } = require("@devilsdev/rag-pipeline-utils");
258
+ const tracer = new ExecutionTracer();
259
+ const traced = tracer.trace(pipeline);
260
+ const result = await traced.run({ query });
261
+
262
+ const inspector = new TraceInspector();
263
+ const analysis = inspector.analyze(tracer.getTraces()[0]);
264
+ // analysis.bottleneck, analysis.recommendations
265
+ ```
332
266
 
333
- ### v2.4.0 (Q3 2025)
267
+ ### MCP Integration
334
268
 
335
- - **GraphRAG Support** – Native knowledge graph integration for entity-relationship retrieval
336
- - **Federated Learning** – Privacy-preserving model training across distributed datasets
337
- - **Advanced Reranking** – Cross-encoder models and learned ranking functions
338
- - **Performance Dashboard** – Web UI for monitoring pipeline health and cost metrics
269
+ Expose any pipeline as a Model Context Protocol tool, callable from Claude Desktop, IDE extensions, or any MCP-compatible client.
339
270
 
340
- ### Beyond
271
+ ```javascript
272
+ const { MCPServer } = require("@devilsdev/rag-pipeline-utils");
273
+ const server = MCPServer.fromPipeline(pipeline, { name: "knowledge-base" });
274
+ const tools = server.getToolDefinitions();
275
+ const result = await server.handleToolUse("knowledge-base", {
276
+ query: "How does auth work?",
277
+ });
278
+ ```
341
279
 
342
- - Native Rust bindings for performance-critical paths
343
- - Kubernetes operator for production deployments
344
- - Real-time collaboration features for team-based pipelines
280
+ ### Quick Start Templates
345
281
 
346
- **Vote on features:** Share your priorities in [GitHub Discussions](https://github.com/DevilsDev/rag-pipeline-utils/discussions/categories/roadmap).
282
+ Scaffold complete projects from four built-in templates: `document-qa`, `chatbot`, `code-search`, and `customer-support`.
347
283
 
348
- ---
284
+ ```javascript
285
+ const { ProjectScaffolder } = require("@devilsdev/rag-pipeline-utils");
286
+ const scaffolder = new ProjectScaffolder();
287
+ scaffolder.create("chatbot", "./my-chatbot");
288
+ // Creates: package.json, index.js, .ragrc.json, README.md
289
+ ```
349
290
 
350
- ## Upgrading from v2.2.x
291
+ ### Streaming Embeddings
351
292
 
352
- The v2.3.0 release includes important security enhancements that are **100% backward compatible** for most use cases. However, there are a few behavioral changes to be aware of:
293
+ Generate embeddings in real-time with backpressure control and memory management. Process millions of documents without running out of memory.
353
294
 
354
- ### JWT Validator Changes
295
+ ```javascript
296
+ const { StreamingEmbedder } = require("@devilsdev/rag-pipeline-utils");
297
+ const streamer = new StreamingEmbedder(myEmbedder, {
298
+ batchSize: 50,
299
+ maxMemoryMB: 512,
300
+ });
301
+ for await (const { id, vector, progress } of streamer.embedStream(documents)) {
302
+ console.log(`${(progress * 100).toFixed(0)}% — embedded ${id}`);
303
+ }
304
+ ```
355
305
 
356
- #### No Action Required (Recommended Use Case)
306
+ ### GraphRAG
357
307
 
358
- If you're using the default configuration with `strictValidation: true` (the default), everything works the same:
308
+ Build knowledge graphs from documents and retrieve using entity-relationship traversal. Combines graph-based scoring with text matching for superior retrieval on entity-heavy content.
359
309
 
360
310
  ```javascript
361
- const validator = new JWTValidator({
362
- secret: process.env.JWT_SECRET,
363
- algorithm: "HS256",
364
- issuer: "my-app",
365
- audience: "api-users",
366
- // strictValidation defaults to true
367
- });
368
-
369
- // Behavior unchanged - tokens validated correctly
311
+ const { GraphRetriever } = require("@devilsdev/rag-pipeline-utils");
312
+ const retriever = new GraphRetriever({ traversalDepth: 2 });
313
+ await retriever.store(documents); // Extracts entities + builds graph
314
+ const results = await retriever.retrieve("Who founded OpenAI?", 5);
315
+ // Results ranked by entity graph traversal + text relevance
370
316
  ```
371
317
 
372
- #### Behavior Change (Advanced Use Case)
373
-
374
- If you explicitly set `strictValidation: false`, the behavior has changed for consistency:
318
+ ### Advanced Reranking
375
319
 
376
- **Before v2.3.0:**
320
+ Three reranking strategies beyond LLM-based: BM25 scoring, embedding cosine similarity, and cascaded multi-stage reranking.
377
321
 
378
322
  ```javascript
379
- const validator = new JWTValidator({
380
- secret: process.env.JWT_SECRET,
381
- strictValidation: false,
382
- issuer: "my-app", // These were still validated
383
- audience: "api-users", // even with strictValidation=false
384
- });
323
+ const {
324
+ ScoringReranker,
325
+ EmbeddingReranker,
326
+ CascadeReranker,
327
+ } = require("@devilsdev/rag-pipeline-utils");
328
+ const cascade = new CascadeReranker([
329
+ new ScoringReranker(), // Stage 1: BM25 keyword scoring
330
+ new EmbeddingReranker(embedder), // Stage 2: semantic similarity
331
+ ]);
332
+ const ranked = await cascade.rerank(query, documents);
385
333
  ```
386
334
 
387
- **After v2.3.0:**
335
+ ### Performance Dashboard
336
+
337
+ Generate standalone HTML dashboards from pipeline metrics. No external dependencies — open in any browser.
388
338
 
389
339
  ```javascript
390
- const validator = new JWTValidator({
391
- secret: process.env.JWT_SECRET,
392
- strictValidation: false,
393
- issuer: "my-app", // Now properly ignored
394
- audience: "api-users", // when strictValidation=false
395
- });
396
- // issuer/audience validation is now truly disabled
340
+ const {
341
+ MetricsAggregator,
342
+ DashboardGenerator,
343
+ } = require("@devilsdev/rag-pipeline-utils");
344
+ const aggregator = new MetricsAggregator();
345
+ aggregator.recordQuery({ duration: 250, cost: 0.003, success: true });
346
+
347
+ const dashboard = new DashboardGenerator();
348
+ const html = dashboard.generate(aggregator.getSnapshot());
349
+ // Write to file: fs.writeFileSync('dashboard.html', html);
397
350
  ```
398
351
 
399
- **Migration:** If you were relying on the old inconsistent behavior, set `strictValidation: true` explicitly.
352
+ ### Enterprise
400
353
 
401
- #### Enhanced Behavior (Self-Signed Tokens)
354
+ Multi-tenant isolation, SSO integration (SAML, OAuth2, Active Directory, OIDC), compliance-grade audit logging, and data governance with classification and retention policies.
402
355
 
403
- Self-signed tokens can now be verified multiple times, which is essential for:
404
-
405
- - Refresh token flows
406
- - Load balancer retries
407
- - Distributed systems with eventual consistency
356
+ ### DAG Workflow Engine
408
357
 
409
- ```javascript
410
- const token = validator.sign({ sub: "user-123" });
358
+ Chain complex multi-step operations with topological execution, retry logic, parallel processing via semaphore-based concurrency, graceful degradation, and checkpoint/resume.
411
359
 
412
- // Before v2.3.0: Second verification would throw "replay detected"
413
- // After v2.3.0: Works correctly for self-signed tokens
414
- validator.verify(token); // Works
415
- validator.verify(token); // Now works!
416
- ```
360
+ ### Security
417
361
 
418
- External tokens (not signed by your validator) are still correctly blocked on replay.
362
+ Defense-in-depth: JWT replay protection, algorithm whitelisting, plugin sandboxing with isolated-vm, multi-layer path traversal defense (5-pass iterative URL decoding), input validation, and automatic secret redaction (36+ patterns).
419
363
 
420
- ### Input Sanitizer Changes
364
+ ### Observability
421
365
 
422
- #### Path Traversal Now Always Throws
366
+ OpenTelemetry distributed tracing, Prometheus metrics export, structured Pino logging, SLO monitoring, and security event tracking.
423
367
 
424
- Path traversal attempts now **always throw errors**, even with `throwOnInvalid: false`:
368
+ ---
425
369
 
426
- **Before v2.3.0:**
370
+ ## Installation
427
371
 
428
- ```javascript
429
- const sanitizer = new InputSanitizer({ throwOnInvalid: false });
430
- const result = sanitizePath("../../../etc/passwd");
431
- // Returned: null (silent failure)
372
+ ```bash
373
+ npm install @devilsdev/rag-pipeline-utils
432
374
  ```
433
375
 
434
- **After v2.3.0:**
376
+ ### Development
435
377
 
436
- ```javascript
437
- const sanitizer = new InputSanitizer({ throwOnInvalid: false });
438
- const result = sanitizePath("../../../etc/passwd");
439
- // Throws: "Potential path traversal detected"
378
+ ```bash
379
+ git clone https://github.com/DevilsDev/rag-pipeline-utils.git
380
+ cd rag-pipeline-utils
381
+ npm install
382
+ npm test # 92 suites, 2050+ tests
383
+ npm run build # CJS + ESM + TypeScript definitions
384
+ npm run lint # ESLint
385
+ npm run dev # Interactive development tools
440
386
  ```
441
387
 
442
- **Rationale:** Path traversal is a critical security violation that should never be silently ignored.
443
-
444
- **Migration:** Wrap path sanitization in try-catch if you need to handle errors gracefully:
388
+ ### Useful Commands
445
389
 
446
- ```javascript
447
- try {
448
- const safePath = sanitizePath(userInput);
449
- // Use safePath
450
- } catch (error) {
451
- if (error.message.includes("path traversal")) {
452
- // Handle attack attempt
453
- logger.warn("Path traversal blocked", { input: userInput });
454
- return res.status(400).json({ error: "Invalid path" });
455
- }
456
- throw error;
457
- }
390
+ ```bash
391
+ npm run benchmark # Performance benchmarks
392
+ npm run security:audit # Dependency scanning
393
+ npm run docs:api # Generate API documentation
394
+ npm run docs:validate # Verify README code examples
395
+ npm run verify:esm # Validate ESM build
458
396
  ```
459
397
 
460
- ### Breaking Changes
398
+ ---
461
399
 
462
- **None.** All changes are security enhancements that improve correctness without breaking existing valid use cases.
400
+ ## Roadmap
463
401
 
464
- ### Testing Your Upgrade
402
+ ### v2.4.0 (Current)
465
403
 
466
- Run your test suite after upgrading:
404
+ - 104 public exports
405
+ - Streaming embeddings with backpressure control
406
+ - GraphRAG -- knowledge graph construction, entity extraction, graph-based retrieval
407
+ - Advanced reranking -- BM25 scoring, embedding-based, cascade rerankers
408
+ - Performance dashboard -- HTML dashboard generator, metrics aggregation
409
+ - Smart chunking, citation tracking, RAG evaluation, agentic RAG, hybrid retrieval
410
+ - 3-layer guardrails, cost management, MCP integration, streaming adapters
411
+ - 7 provider connectors (OpenAI, Anthropic, Cohere, Ollama, LocalEmbedder, MemoryRetriever)
412
+ - 92 test suites, 2050+ tests
467
413
 
468
- ```bash
469
- npm test
470
- ```
414
+ ### What's Next (v3.0.0)
471
415
 
472
- If you encounter issues, please [open an issue](https://github.com/DevilsDev/rag-pipeline-utils/issues) with details about your configuration.
416
+ - **Intelligent Caching** -- embedding cache with TTL and invalidation strategies
417
+ - **Native Rust Bindings** -- performance-critical paths compiled to native code
418
+ - **Kubernetes Operator** -- production deployments with auto-scaling
419
+ - **Edge Deployment** -- Cloudflare Workers, Deno Deploy, Vercel Edge
420
+ - **Real-time Collaboration** -- team-based pipeline editing and sharing
421
+
422
+ **Vote on features:** [GitHub Discussions](https://github.com/DevilsDev/rag-pipeline-utils/discussions/categories/roadmap)
473
423
 
474
424
  ---
475
425
 
@@ -477,43 +427,25 @@ If you encounter issues, please [open an issue](https://github.com/DevilsDev/rag
477
427
 
478
428
  We welcome contributions of all kinds:
479
429
 
480
- - **Code** – Fix bugs, add features, improve performance
481
- - **Documentation** – Write guides, improve examples, clarify concepts
482
- - **Testing** – Expand test coverage, add integration tests, report edge cases
483
- - **Design** – Propose API improvements, suggest architectural patterns
484
- - **Community** – Answer questions, review pull requests, mentor new contributors
430
+ - **Code** -- fix bugs, add features, improve performance
431
+ - **Documentation** -- write guides, improve examples, clarify concepts
432
+ - **Testing** -- expand test coverage, add integration tests, report edge cases
433
+ - **Design** -- propose API improvements, suggest architectural patterns
434
+ - **Community** -- answer questions, review pull requests, mentor new contributors
485
435
 
486
- **Before You Start:**
436
+ **Before you start:**
487
437
 
488
438
  1. Read the [Contributing Guide](https://github.com/DevilsDev/rag-pipeline-utils/blob/main/docs/CONTRIBUTING.md)
489
439
  2. Check existing [Issues](https://github.com/DevilsDev/rag-pipeline-utils/issues) and [Discussions](https://github.com/DevilsDev/rag-pipeline-utils/discussions)
490
440
  3. Open an issue to discuss major changes before coding
491
441
  4. Follow our [Code of Conduct](https://github.com/DevilsDev/rag-pipeline-utils/blob/main/CODE_OF_CONDUCT.md)
492
442
 
493
- **Pull Request Checklist:**
494
-
495
- - [ ] Tests pass (`npm test`)
496
- - [ ] Linter passes (`npm run lint`)
497
- - [ ] Documentation updated
498
- - [ ] Changelog entry added
499
- - [ ] Type definitions updated (if applicable)
500
-
501
443
  ---
502
444
 
503
445
  ## License
504
446
 
505
- **GPL-3.0** – See [LICENSE](https://github.com/DevilsDev/rag-pipeline-utils/blob/main/LICENSE) for full terms.
506
-
507
- This is free software: you are free to change and redistribute it under the terms of the GNU General Public License version 3.
447
+ **GPL-3.0** -- See [LICENSE](https://github.com/DevilsDev/rag-pipeline-utils/blob/main/LICENSE) for full terms.
508
448
 
509
449
  ---
510
450
 
511
- ## What's Next?
512
-
513
- **Star this repository** if you find it useful—it helps others discover the project.
514
-
515
- **Share your use case** in [Discussions](https://github.com/DevilsDev/rag-pipeline-utils/discussions/categories/show-and-tell) to inspire the community.
516
-
517
- **Contribute** your first pull request—check out issues tagged [good first issue](https://github.com/DevilsDev/rag-pipeline-utils/labels/good%20first%20issue).
518
-
519
- Happy building.
451
+ **Star this repo** if you find it useful. **Share your use case** in [Discussions](https://github.com/DevilsDev/rag-pipeline-utils/discussions/categories/show-and-tell). **Contribute** your first PR -- check [good first issues](https://github.com/DevilsDev/rag-pipeline-utils/labels/good%20first%20issue).