@devilsdev/rag-pipeline-utils 2.4.5 → 2.6.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 (258) hide show
  1. package/.ragrc.schema.json +83 -192
  2. package/CHANGELOG.md +431 -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 +6442 -1355
  9. package/dist/index.d.ts +129 -2
  10. package/dist/index.mjs +1 -1
  11. package/dist/testing.cjs +2 -0
  12. package/dist/testing.d.ts +1 -0
  13. package/dist/testing.mjs +5 -0
  14. package/dist/types/adapters/ai-sdk.d.ts +53 -0
  15. package/dist/types/agentic/agentic-pipeline.d.ts +103 -0
  16. package/dist/types/agentic/iterative-retriever.d.ts +85 -0
  17. package/dist/types/agentic/query-planner.d.ts +145 -0
  18. package/dist/types/agentic/self-critique.d.ts +45 -0
  19. package/dist/types/ai/adaptive-retrieval.d.ts +44 -0
  20. package/dist/types/ai/federation/federated-learning-coordinator.d.ts +62 -0
  21. package/dist/types/ai/multimodal-processing.d.ts +32 -0
  22. package/dist/types/ai/multimodal.d.ts +39 -0
  23. package/dist/types/ai/retrieval-engine.d.ts +37 -0
  24. package/dist/types/ai/training/model-training-orchestrator.d.ts +31 -0
  25. package/dist/types/cache/component-keys.d.ts +7 -0
  26. package/dist/types/cache/memory-cache.d.ts +54 -0
  27. package/dist/types/cache/pipeline-cache.d.ts +66 -0
  28. package/dist/types/cache/redis-cache.d.ts +46 -0
  29. package/dist/types/chunking/chunking-engine.d.ts +70 -0
  30. package/dist/types/chunking/strategies/fixed-size.d.ts +17 -0
  31. package/dist/types/chunking/strategies/recursive.d.ts +20 -0
  32. package/dist/types/chunking/strategies/semantic.d.ts +19 -0
  33. package/dist/types/chunking/strategies/sentence.d.ts +13 -0
  34. package/dist/types/chunking/strategies/structure-aware.d.ts +19 -0
  35. package/dist/types/citation/citation-tracker.d.ts +64 -0
  36. package/dist/types/citation/hallucination-detector.d.ts +40 -0
  37. package/dist/types/citation/source-mapper.d.ts +37 -0
  38. package/dist/types/connectors/anthropic-connector.d.ts +97 -0
  39. package/dist/types/connectors/base-connector.d.ts +87 -0
  40. package/dist/types/connectors/cohere-connector.d.ts +94 -0
  41. package/dist/types/connectors/connector-utils.d.ts +110 -0
  42. package/dist/types/connectors/local-embedder.d.ts +95 -0
  43. package/dist/types/connectors/memory-retriever.d.ts +99 -0
  44. package/dist/types/connectors/ollama-connector.d.ts +115 -0
  45. package/dist/types/connectors/openai-connector.d.ts +129 -0
  46. package/dist/types/connectors/rag-prompt.d.ts +40 -0
  47. package/dist/types/core/create-pipeline.d.ts +8 -0
  48. package/dist/types/core/plugin-registry.d.ts +136 -0
  49. package/dist/types/core/stage-contracts.d.ts +36 -0
  50. package/dist/types/core/validate-plugin.d.ts +45 -0
  51. package/dist/types/cost/cost-calculator.d.ts +152 -0
  52. package/dist/types/cost/cost-tracker.d.ts +126 -0
  53. package/dist/types/cost/token-budget.d.ts +110 -0
  54. package/dist/types/dag/core/error-context.d.ts +239 -0
  55. package/dist/types/dag/core/execution-scheduler.d.ts +191 -0
  56. package/dist/types/dag/core/topology-validation.d.ts +226 -0
  57. package/dist/types/dag/dag-engine.d.ts +156 -0
  58. package/dist/types/dag/dag-node.d.ts +37 -0
  59. package/dist/types/dashboard/dashboard-generator.d.ts +127 -0
  60. package/dist/types/dashboard/metrics-aggregator.d.ts +218 -0
  61. package/dist/types/debug/execution-tracer.d.ts +57 -0
  62. package/dist/types/debug/trace-inspector.d.ts +31 -0
  63. package/dist/types/ecosystem/plugin-certification.d.ts +169 -0
  64. package/dist/types/enterprise/data-governance.d.ts +203 -0
  65. package/dist/types/enterprise/multi-tenancy.d.ts +137 -0
  66. package/dist/types/enterprise/sso-integration.d.ts +420 -0
  67. package/dist/types/evaluate/context-metrics.d.ts +55 -0
  68. package/dist/types/evaluate/faithfulness.d.ts +41 -0
  69. package/dist/types/evaluate/groundedness.d.ts +60 -0
  70. package/dist/types/evaluate/pipeline-evaluator.d.ts +88 -0
  71. package/dist/types/evaluate/relevance.d.ts +21 -0
  72. package/dist/types/evaluate/scoring.d.ts +123 -0
  73. package/dist/types/evaluate/semantic-similarity.d.ts +14 -0
  74. package/dist/types/experimental.d.ts +15 -0
  75. package/dist/types/graph/entity-extractor.d.ts +84 -0
  76. package/dist/types/graph/graph-index.d.ts +49 -0
  77. package/dist/types/graph/graph-retriever.d.ts +81 -0
  78. package/dist/types/graph/knowledge-graph.d.ts +129 -0
  79. package/dist/types/grounding/check-answer.d.ts +101 -0
  80. package/dist/types/guardrails/guardrails-pipeline.d.ts +63 -0
  81. package/dist/types/guardrails/injection-detector.d.ts +47 -0
  82. package/dist/types/guardrails/post-generation-guard.d.ts +61 -0
  83. package/dist/types/guardrails/pre-retrieval-guard.d.ts +64 -0
  84. package/dist/types/guardrails/retrieval-guard.d.ts +57 -0
  85. package/dist/types/mcp/mcp-server.d.ts +85 -0
  86. package/dist/types/mcp/mcp-tool-builder.d.ts +55 -0
  87. package/dist/types/reranker/cascade-reranker.d.ts +40 -0
  88. package/dist/types/reranker/embedding-reranker.d.ts +77 -0
  89. package/dist/types/reranker/scoring-reranker.d.ts +41 -0
  90. package/dist/types/retrieval/bm25-search.d.ts +43 -0
  91. package/dist/types/retrieval/file-vector-store.d.ts +99 -0
  92. package/dist/types/retrieval/hybrid-retriever.d.ts +35 -0
  93. package/dist/types/retrieval/rank-fusion.d.ts +10 -0
  94. package/dist/types/security/jwt-config.d.ts +80 -0
  95. package/dist/types/security/jwt-validator.d.ts +195 -0
  96. package/dist/types/security/plugin-sandbox.d.ts +158 -0
  97. package/dist/types/security/plugin-signature-verifier.d.ts +139 -0
  98. package/dist/types/security/validator.d.ts +5 -0
  99. package/dist/types/streaming/embedding-stream.d.ts +65 -0
  100. package/dist/types/streaming/sse-adapter.d.ts +59 -0
  101. package/dist/types/streaming/stream-router.d.ts +88 -0
  102. package/dist/types/streaming/streaming-embedder.d.ts +99 -0
  103. package/dist/types/streaming/websocket-adapter.d.ts +71 -0
  104. package/dist/types/templates/scaffold.d.ts +55 -0
  105. package/dist/types/templates/template-registry.d.ts +63 -0
  106. package/dist/types/testing.d.ts +168 -0
  107. package/dist/types/utils/embed-query.d.ts +20 -0
  108. package/dist/types/utils/logger.d.ts +50 -0
  109. package/dist/types/utils/rate-limiter.d.ts +66 -0
  110. package/dist/types/utils/retry.d.ts +27 -0
  111. package/dist/types/utils/run-abort.d.ts +34 -0
  112. package/dist/types/utils/secure-logging.d.ts +51 -0
  113. package/dist/types/utils/structured-logger.d.ts +126 -0
  114. package/package.json +72 -33
  115. package/src/adapters/ai-sdk.js +215 -0
  116. package/src/agentic/agentic-pipeline.js +75 -7
  117. package/src/agentic/iterative-retriever.js +47 -10
  118. package/src/agentic/query-planner.js +329 -78
  119. package/src/cache/component-keys.js +38 -0
  120. package/src/cache/memory-cache.js +87 -0
  121. package/src/cache/pipeline-cache.js +260 -0
  122. package/src/cache/redis-cache.js +83 -0
  123. package/src/citation/citation-tracker.js +6 -4
  124. package/src/citation/hallucination-detector.js +2 -2
  125. package/src/citation/source-mapper.js +15 -28
  126. package/src/cli/commands/ai.js +106 -0
  127. package/src/cli/commands/plugin-hub/event-handlers.js +6 -0
  128. package/src/cli/commands/plugin-hub/hub-commands.js +0 -74
  129. package/src/cli/commands/plugin-hub/local-commands.js +143 -0
  130. package/src/cli/commands/plugin-hub.js +114 -49
  131. package/src/cli/diagnostics/config-checker.js +76 -63
  132. package/src/cli/diagnostics/environment-checker.js +62 -31
  133. package/src/cli/diagnostics/plugin-checker.js +36 -89
  134. package/src/cli/doctor-command.js +39 -5
  135. package/src/cli/enhanced-cli-commands.js +104 -233
  136. package/src/cli/handlers/ai-handler.js +364 -0
  137. package/src/cli/handlers/diagnostics-handler.js +78 -31
  138. package/src/cli/handlers/ingest-handler.js +28 -22
  139. package/src/cli/handlers/init-handler.js +148 -25
  140. package/src/cli/handlers/query-handler.js +203 -25
  141. package/src/cli/handlers/run-handler.js +16 -167
  142. package/src/cli/handlers/serve-handler.js +60 -0
  143. package/src/cli/services/bench-stats.js +54 -0
  144. package/src/cli/services/benchmark.js +161 -0
  145. package/src/cli/services/feedback.js +155 -0
  146. package/src/cli/services/instrument.js +83 -0
  147. package/src/cli/services/rag-service.js +361 -0
  148. package/src/cli/shared/cli-utils.js +24 -7
  149. package/src/cli/shared/config-context.js +21 -0
  150. package/src/cli/wizard/config-builder.js +81 -0
  151. package/src/cli/wizard/init-wizard.js +602 -0
  152. package/src/config/component-factory.js +125 -0
  153. package/src/config/enhanced-ragrc-schema.js +0 -2
  154. package/src/config/load-config.js +29 -10
  155. package/src/config/load-plugin-config.js +46 -2
  156. package/src/config/validate-schema.js +4 -1
  157. package/src/connectors/anthropic-connector.js +115 -57
  158. package/src/connectors/base-connector.js +74 -19
  159. package/src/connectors/cohere-connector.js +108 -34
  160. package/src/connectors/connector-utils.js +302 -0
  161. package/src/connectors/local-embedder.js +63 -5
  162. package/src/connectors/memory-retriever.js +125 -14
  163. package/src/connectors/ollama-connector.js +112 -51
  164. package/src/connectors/openai-connector.js +153 -44
  165. package/src/connectors/rag-prompt.js +88 -0
  166. package/src/core/create-pipeline.js +307 -61
  167. package/src/core/performance/parallel-processor.js +62 -1
  168. package/src/core/plugin-registry.js +125 -26
  169. package/src/core/stage-contracts.js +36 -0
  170. package/src/core/validate-plugin.js +85 -0
  171. package/src/cost/cost-calculator.js +205 -32
  172. package/src/debug/execution-tracer.js +14 -4
  173. package/src/dev/dev-server.js +173 -11
  174. package/src/dev/hot-reload.js +44 -4
  175. package/src/ecosystem/plugin-checks.js +181 -0
  176. package/src/ecosystem/plugin-hub.js +50 -125
  177. package/src/ecosystem/plugin-installer.js +298 -0
  178. package/src/ecosystem/plugin-probe.js +127 -0
  179. package/src/ecosystem/plugin-scanner.js +185 -0
  180. package/src/ecosystem/tar-extract.js +114 -0
  181. package/src/enterprise/audit-logging.js +158 -29
  182. package/src/enterprise/sso-integration.js +716 -228
  183. package/src/evaluate/context-metrics.js +28 -16
  184. package/src/evaluate/evaluator.js +3 -3
  185. package/src/evaluate/faithfulness.js +18 -14
  186. package/src/evaluate/groundedness.js +43 -12
  187. package/src/evaluate/pipeline-evaluator.js +35 -8
  188. package/src/evaluate/scoring.js +251 -3
  189. package/src/evaluate/semantic-similarity.js +79 -0
  190. package/src/experimental.js +71 -0
  191. package/src/grounding/check-answer.js +173 -0
  192. package/src/guardrails/guardrails-pipeline.js +69 -7
  193. package/src/guardrails/injection-detector.js +283 -0
  194. package/src/guardrails/post-generation-guard.js +19 -0
  195. package/src/guardrails/pre-retrieval-guard.js +36 -36
  196. package/src/guardrails/retrieval-guard.js +58 -8
  197. package/src/index.js +58 -1
  198. package/src/loader/csv-loader.js +3 -2
  199. package/src/loader/document-reader.js +91 -0
  200. package/src/loader/html-loader.js +3 -1
  201. package/src/loader/markdown-loader.js +3 -2
  202. package/src/reranker/cascade-reranker.js +3 -0
  203. package/src/reranker/embedding-reranker.js +136 -21
  204. package/src/reranker/llm-reranker.js +79 -12
  205. package/src/reranker/scoring-reranker.js +3 -0
  206. package/src/retrieval/bm25-search.js +12 -6
  207. package/src/retrieval/file-vector-store.js +241 -0
  208. package/src/retrieval/hybrid-retriever.js +22 -19
  209. package/src/security/jwt-config.js +13 -2
  210. package/src/security/jwt-validator.js +139 -34
  211. package/src/security/plugin-sandbox.js +18 -1
  212. package/src/security/plugin-signature-verifier.js +245 -70
  213. package/src/testing.js +254 -0
  214. package/src/utils/deprecate.js +69 -0
  215. package/src/utils/embed-query.js +33 -0
  216. package/src/utils/input-sanitizer.js +19 -4
  217. package/src/utils/logger.js +34 -4
  218. package/src/utils/run-abort.js +102 -0
  219. package/src/ai/federated-learning.js +0 -211
  220. package/src/ai/federation.js +0 -71
  221. package/src/ai/index.js +0 -22
  222. package/src/ai/model-trainer.js +0 -217
  223. package/src/ai/model-training.js +0 -202
  224. package/src/ai/multimodal/multi-modal-processor.js +0 -345
  225. package/src/ai/orchestrator.js +0 -65
  226. package/src/ai/retrieval/adaptive-retrieval-engine.js +0 -398
  227. package/src/cli/commands/ai-ml/adaptive-commands.js +0 -178
  228. package/src/cli/commands/ai-ml/federated-commands.js +0 -207
  229. package/src/cli/commands/ai-ml/index.js +0 -17
  230. package/src/cli/commands/ai-ml/multimodal-commands.js +0 -187
  231. package/src/cli/commands/ai-ml/shared.js +0 -51
  232. package/src/cli/commands/ai-ml/training-commands.js +0 -228
  233. package/src/cli/commands/ai-ml.js +0 -386
  234. package/src/cli/commands/docs.js +0 -228
  235. package/src/cli/commands/dx.js +0 -538
  236. package/src/cli/commands/wizard.js +0 -627
  237. package/src/cli/input-sanitization-middleware.js +0 -356
  238. package/src/cli/interactive-wizard.js +0 -373
  239. package/src/cli/templates/development.template.json +0 -64
  240. package/src/cli/templates/minimal.template.json +0 -33
  241. package/src/cli/templates/production.template.json +0 -104
  242. package/src/cli/templates/testing.template.json +0 -45
  243. package/src/cli/wizard/configuration.js +0 -148
  244. package/src/cli/wizard/observability.js +0 -79
  245. package/src/cli/wizard/performance.js +0 -76
  246. package/src/cli/wizard/plugin-selection.js +0 -297
  247. package/src/cli/wizard/preview-save.js +0 -172
  248. package/src/cli/wizard/project-setup.js +0 -66
  249. package/src/core/pipeline-factory.js +0 -59
  250. package/src/dag/enhanced-dag-engine.js +0 -894
  251. package/src/dx/index.js +0 -40
  252. package/src/dx/integration-templates.js +0 -662
  253. package/src/dx/performance-profiler.js +0 -968
  254. package/src/dx/realtime-debugger.js +0 -755
  255. package/src/dx/visual-pipeline-builder.js +0 -578
  256. package/src/ingest.js +0 -59
  257. package/src/pipeline/pipeline.js +0 -18
  258. package/src/query.js +0 -117
@@ -0,0 +1,99 @@
1
+ /**
2
+ * In-memory vector store with cosine similarity retrieval.
3
+ * Stores document vectors and retrieves the most similar ones to a query vector.
4
+ * All vectors in one store must have the same dimension.
5
+ * @extends BaseConnector
6
+ */
7
+ export class MemoryRetriever extends BaseConnector {
8
+ /**
9
+ * @param {Object} options
10
+ * @param {number} [options.maxDocuments=100000] - Maximum number of documents to store
11
+ * @param {'error'|'fifo'} [options.eviction='error'] - What to do when a store()
12
+ * would exceed maxDocuments: throw (default) or evict the oldest documents
13
+ */
14
+ constructor(options?: {
15
+ maxDocuments?: number;
16
+ eviction?: "error" | "fifo";
17
+ });
18
+ config: any;
19
+ /** @type {Map<string, { vector: number[], metadata?: Object, content?: string }>} */
20
+ documents: Map<string, {
21
+ vector: number[];
22
+ metadata?: any;
23
+ content?: string;
24
+ }>;
25
+ /** @type {number|null} Vector dimension, fixed by the first stored vector */
26
+ dimensions: number | null;
27
+ _cacheId: string;
28
+ _revision: number;
29
+ /**
30
+ * Cache identity for createRagPipeline({ cache }).
31
+ * @param {'retriever'} role
32
+ * @returns {string|null}
33
+ */
34
+ getCacheKey(role: "retriever"): string | null;
35
+ /**
36
+ * Store one or more vector documents. The batch is validated before
37
+ * anything is inserted, so a rejected call leaves the store unchanged.
38
+ *
39
+ * @param {Array<{ id: string, vector: number[], metadata?: Object, content?: string }>} vectors
40
+ * @returns {Promise<void>}
41
+ * @throws {Error} When a vector's dimension differs from the store's, or
42
+ * (eviction 'error') when the store would exceed maxDocuments
43
+ */
44
+ store(vectors: Array<{
45
+ id: string;
46
+ vector: number[];
47
+ metadata?: any;
48
+ content?: string;
49
+ }>): Promise<void>;
50
+ /**
51
+ * Retrieve the top-k most similar documents to a query vector.
52
+ * @param {number[]|{ query?: string, queryVector: number[], topK?: number, signal?: AbortSignal }} queryOrObj
53
+ * Either a raw vector array or an object with queryVector, optional topK
54
+ * and optional AbortSignal.
55
+ * @param {number} [k=10] - Number of results to return (used when queryOrObj is an array)
56
+ * @returns {Promise<Array<{ id: string, score: number, metadata: Object, content: string }>>}
57
+ * @throws {Error} When the query vector's dimension differs from the stored vectors
58
+ */
59
+ retrieve(queryOrObj: number[] | {
60
+ query?: string;
61
+ queryVector: number[];
62
+ topK?: number;
63
+ signal?: AbortSignal;
64
+ }, k?: number): Promise<Array<{
65
+ id: string;
66
+ score: number;
67
+ metadata: any;
68
+ content: string;
69
+ }>>;
70
+ /**
71
+ * Compute cosine similarity between two vectors of equal length.
72
+ * @param {number[]} a - First vector
73
+ * @param {number[]} b - Second vector
74
+ * @returns {number} Cosine similarity in the range [-1, 1], or 0 for zero vectors
75
+ * @throws {Error} When the vectors have different lengths
76
+ * @private
77
+ */
78
+ private _cosineSimilarity;
79
+ /**
80
+ * Remove all stored documents and reset the vector dimension.
81
+ * @returns {Promise<void>}
82
+ */
83
+ clear(): Promise<void>;
84
+ /**
85
+ * Get statistics about the store.
86
+ * @returns {{ documentCount: number, maxDocuments: number, dimensions: number|null }}
87
+ */
88
+ getStats(): {
89
+ documentCount: number;
90
+ maxDocuments: number;
91
+ dimensions: number | null;
92
+ };
93
+ }
94
+ /**
95
+ * Default configuration for the in-memory retriever.
96
+ * @type {Object}
97
+ */
98
+ export const DEFAULT_CONFIG: any;
99
+ import { BaseConnector } from "./base-connector";
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Connector for Ollama local LLM server.
3
+ * Supports text generation (sync and streaming) and embeddings.
4
+ * Ollama needs no API key.
5
+ * @extends BaseConnector
6
+ */
7
+ export class OllamaConnector extends BaseConnector {
8
+ /**
9
+ * @param {Object} options
10
+ * @param {string} [options.baseURL='http://localhost:11434'] - Ollama server URL
11
+ * @param {string} [options.model='llama3'] - Default generation model
12
+ * @param {string} [options.embeddingModel='nomic-embed-text'] - Default embedding model
13
+ * @param {number} [options.timeout=60000] - Request timeout in ms
14
+ * @param {number} [options.temperature=0.7] - Generation temperature
15
+ * @param {number} [options.maxRetries=3] - Retries for transient failures
16
+ * @param {number} [options.retryDelay=1000] - Base backoff delay in ms
17
+ * @param {string} [options.systemPrompt] - System prompt used when RAG context is supplied
18
+ */
19
+ constructor(options?: {
20
+ baseURL?: string;
21
+ model?: string;
22
+ embeddingModel?: string;
23
+ timeout?: number;
24
+ temperature?: number;
25
+ maxRetries?: number;
26
+ retryDelay?: number;
27
+ systemPrompt?: string;
28
+ });
29
+ /**
30
+ * Cache identity for createRagPipeline({ cache }).
31
+ * @param {'embedder'|'llm'} role
32
+ * @returns {string|null}
33
+ */
34
+ getCacheKey(role: "embedder" | "llm"): string | null;
35
+ config: any;
36
+ client: import("axios").AxiosInstance;
37
+ /**
38
+ * POST with the connector's retry policy and cancellation.
39
+ * @private
40
+ */
41
+ private _post;
42
+ /**
43
+ * Build the /api/generate body. Retrieved context goes into the prompt as
44
+ * delimited, untrusted reference data; instructions go in `system`.
45
+ * @private
46
+ */
47
+ private _buildBody;
48
+ /**
49
+ * Generate a response for the given query with optional context documents.
50
+ * @param {string} query - The user query
51
+ * @param {Array<Object|string>} [context=[]] - Context documents for RAG
52
+ * @param {Object} [options={}] - Override options
53
+ * @param {string} [options.model] - Override the generation model
54
+ * @param {number} [options.temperature] - Override temperature
55
+ * @param {AbortSignal} [options.signal] - Cancels the request
56
+ * @returns {Promise<string>} Generated response text
57
+ */
58
+ generate(query: string, context?: Array<any | string>, options?: {
59
+ model?: string;
60
+ temperature?: number;
61
+ signal?: AbortSignal;
62
+ }): Promise<string>;
63
+ /**
64
+ * Stream a response token-by-token for the given query.
65
+ * @param {string} query - The user query
66
+ * @param {Array<Object|string>} [context=[]] - Context documents for RAG
67
+ * @param {Object} [options={}] - Override options
68
+ * @param {string} [options.model] - Override the generation model
69
+ * @param {number} [options.temperature] - Override temperature
70
+ * @param {AbortSignal} [options.signal] - Cancels the stream
71
+ * @yields {{ token: string, done: boolean }}
72
+ */
73
+ generateStream(query: string, context?: Array<any | string>, options?: {
74
+ model?: string;
75
+ temperature?: number;
76
+ signal?: AbortSignal;
77
+ }): AsyncGenerator<{
78
+ token: any;
79
+ done: boolean;
80
+ }, void, unknown>;
81
+ /**
82
+ * Generate an embedding vector for the given text.
83
+ * @param {string} text - Text to embed
84
+ * @param {Object} [options={}]
85
+ * @param {AbortSignal} [options.signal] - Cancels the request
86
+ * @returns {Promise<number[]>} Embedding vector
87
+ */
88
+ embed(text: string, options?: {
89
+ signal?: AbortSignal;
90
+ }): Promise<number[]>;
91
+ /**
92
+ * Generate an embedding vector for a query string.
93
+ * Alias for {@link embed}.
94
+ * @param {string} query - Query text to embed
95
+ * @param {Object} [options={}] - Same as embed()
96
+ * @returns {Promise<number[]>} Embedding vector
97
+ */
98
+ embedQuery(query: string, options?: any): Promise<number[]>;
99
+ /**
100
+ * Build a prompt string incorporating context documents.
101
+ * Kept for backward compatibility; context is delimited and labelled as
102
+ * untrusted reference data.
103
+ * @param {string} query - The user query
104
+ * @param {Array<Object|string>} context - Context documents
105
+ * @returns {string} Formatted prompt
106
+ * @private
107
+ */
108
+ private _buildPrompt;
109
+ }
110
+ /**
111
+ * Default configuration for the Ollama connector.
112
+ * @type {Object}
113
+ */
114
+ export const DEFAULT_CONFIG: any;
115
+ import { BaseConnector } from "./base-connector";
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Full LLM + embedder connector for the OpenAI API.
3
+ * Supports chat completions (with streaming) and text embeddings.
4
+ *
5
+ * @extends BaseConnector
6
+ */
7
+ export class OpenAIConnector extends BaseConnector {
8
+ /**
9
+ * @param {Object} [options]
10
+ * @param {string} [options.model='gpt-4o-mini'] - Chat model to use
11
+ * @param {string} [options.embeddingModel='text-embedding-3-small'] - Embedding model
12
+ * @param {number} [options.temperature=0.7] - Sampling temperature
13
+ * @param {number} [options.maxTokens=4096] - Max tokens in completion
14
+ * @param {string} [options.apiKey] - API key. Defaults to OPENAI_API_KEY at
15
+ * construction, except when `baseURL` is set (see below)
16
+ * @param {string} [options.baseURL] - Base URL of an OpenAI-compatible API,
17
+ * e.g. Groq, Together, the Hugging Face router, vLLM, LM Studio or
18
+ * Ollama's `/v1` endpoint. With a custom base URL the key is never read
19
+ * from OPENAI_API_KEY (that would send your OpenAI key to another
20
+ * provider): pass `apiKey` explicitly, or omit it for servers that need
21
+ * none
22
+ * @param {number} [options.maxRetries=3] - Retries for transient failures (the SDK's own retries are disabled)
23
+ * @param {number} [options.retryDelay=1000] - Base backoff delay in ms
24
+ * @param {string} [options.systemPrompt] - System prompt used when RAG context is supplied
25
+ */
26
+ constructor(options?: {
27
+ model?: string;
28
+ embeddingModel?: string;
29
+ temperature?: number;
30
+ maxTokens?: number;
31
+ apiKey?: string;
32
+ baseURL?: string;
33
+ maxRetries?: number;
34
+ retryDelay?: number;
35
+ systemPrompt?: string;
36
+ });
37
+ /**
38
+ * Cache identity for createRagPipeline({ cache }): the settings that
39
+ * change this connector's output in the given role.
40
+ * @param {'embedder'|'llm'} role
41
+ * @returns {string|null}
42
+ */
43
+ getCacheKey(role: "embedder" | "llm"): string | null;
44
+ config: any;
45
+ _client: any;
46
+ /**
47
+ * Lazily initialise and return the OpenAI client.
48
+ * SDK retries are disabled (maxRetries: 0); withRetry() owns the policy.
49
+ * @returns {Object} OpenAI client instance
50
+ * @private
51
+ */
52
+ private _getClient;
53
+ /**
54
+ * @throws {Error} code MISSING_API_KEY when no key is configured
55
+ * @private
56
+ */
57
+ private _requireApiKey;
58
+ /**
59
+ * Run a request with the connector's retry policy and cancellation.
60
+ * @private
61
+ */
62
+ private _request;
63
+ /**
64
+ * Generate a chat completion using the provided query and optional RAG context.
65
+ *
66
+ * @param {string} query - The user query / prompt
67
+ * @param {Array<Object|string>} [context=[]] - Retrieved documents for RAG
68
+ * @param {Object} [options={}] - Override model, temperature, maxTokens per-call
69
+ * @param {AbortSignal} [options.signal] - Cancels the request
70
+ * @returns {Promise<string>} The generated text
71
+ */
72
+ generate(query: string, context?: Array<any | string>, options?: {
73
+ signal?: AbortSignal;
74
+ }): Promise<string>;
75
+ /**
76
+ * Stream a chat completion token-by-token.
77
+ *
78
+ * @param {string} query - The user query / prompt
79
+ * @param {Array<Object|string>} [context=[]] - Retrieved documents for RAG
80
+ * @param {Object} [options={}] - Override model, temperature, maxTokens per-call
81
+ * @param {AbortSignal} [options.signal] - Cancels the stream
82
+ * @yields {{ token: string, done: boolean }}
83
+ */
84
+ generateStream(query: string, context?: Array<any | string>, options?: {
85
+ signal?: AbortSignal;
86
+ }): AsyncGenerator<{
87
+ token: any;
88
+ done: boolean;
89
+ }, void, unknown>;
90
+ /**
91
+ * Generate an embedding vector for the given text.
92
+ *
93
+ * @param {string} text - Input text to embed
94
+ * @param {Object} [options={}]
95
+ * @param {AbortSignal} [options.signal] - Cancels the request
96
+ * @returns {Promise<number[]>} Embedding vector
97
+ */
98
+ embed(text: string, options?: {
99
+ signal?: AbortSignal;
100
+ }): Promise<number[]>;
101
+ /**
102
+ * Generate an embedding vector for a search query.
103
+ * Alias for {@link OpenAIConnector#embed}.
104
+ *
105
+ * @param {string} query - Query text to embed
106
+ * @param {Object} [options={}] - Same as embed()
107
+ * @returns {Promise<number[]>} Embedding vector
108
+ */
109
+ embedQuery(query: string, options?: any): Promise<number[]>;
110
+ /**
111
+ * Build the messages array for a chat completion request. Retrieved
112
+ * context goes into the user message as delimited, untrusted reference
113
+ * data; the system message only carries instructions.
114
+ *
115
+ * @param {string} query - User query
116
+ * @param {Array<Object|string>} context - RAG context documents
117
+ * @returns {Array<{ role: string, content: string }>}
118
+ * @private
119
+ */
120
+ private _buildMessages;
121
+ }
122
+ /**
123
+ * Default configuration for the OpenAI connector.
124
+ * `apiKey` is a getter so the environment is read when a connector is
125
+ * constructed, not when this module is first required.
126
+ * @type {Object}
127
+ */
128
+ export const DEFAULT_CONFIG: any;
129
+ import { BaseConnector } from "./base-connector";
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Prompt construction shared by the LLM connectors.
3
+ *
4
+ * Retrieved documents are untrusted: they may contain text written to look
5
+ * like instructions (indirect prompt injection). They are therefore placed in
6
+ * the USER message inside clearly labelled delimiters, never in the system
7
+ * role, and the system prompt tells the model to treat them as data only.
8
+ */
9
+ /** System prompt used when retrieved context is supplied. */
10
+ export const RAG_SYSTEM_PROMPT: string;
11
+ /**
12
+ * Build the system prompt and user message for a RAG request.
13
+ * Without context, the user message is the query unchanged and there is no
14
+ * system prompt (same as before).
15
+ *
16
+ * @param {string} query
17
+ * @param {Array<object|string>} [context=[]]
18
+ * @param {object} [opts]
19
+ * @param {string} [opts.systemPrompt] - Override the default RAG system prompt
20
+ * @returns {{ system: string|null, user: string }}
21
+ */
22
+ export function buildRagPrompt(query: string, context?: Array<object | string>, opts?: {
23
+ systemPrompt?: string;
24
+ }): {
25
+ system: string | null;
26
+ user: string;
27
+ };
28
+ /**
29
+ * Format retrieved documents as a delimited, labelled block.
30
+ * @param {Array<object|string>} context
31
+ * @returns {string}
32
+ */
33
+ export function formatContext(context: Array<object | string>): string;
34
+ /**
35
+ * Neutralise anything in document text that could close or open our
36
+ * delimiters, so a document cannot break out of its block.
37
+ * @param {string} text
38
+ * @returns {string}
39
+ */
40
+ export function escapeDelimiters(text: string): string;
@@ -0,0 +1,8 @@
1
+ export function createRagPipeline({ registry, loader, embedder, retriever, llm, reranker, cache, }?: {}): {
2
+ run: ({ query, queryVector, options }?: {
3
+ options?: {};
4
+ }) => Promise<any>;
5
+ cleanup(): void;
6
+ /** Cache hits, misses and skips per layer; null when caching is off. */
7
+ cacheStats(): {};
8
+ };
@@ -0,0 +1,136 @@
1
+ export = registry;
2
+ declare const registry: PluginRegistry;
3
+ declare class PluginRegistry {
4
+ constructor(options?: {});
5
+ _plugins: Map<any, any>;
6
+ _validTypes: Set<string>;
7
+ _contracts: Map<any, any>;
8
+ _contractWarningsShown: Set<any>;
9
+ _disableContractWarnings: any;
10
+ _validateContractSchema: any;
11
+ _signatureVerifier: import("../security/plugin-signature-verifier.js").PluginSignatureVerifier;
12
+ _requireSignedPlugins: boolean;
13
+ _contractsLoaded: boolean;
14
+ /**
15
+ * Load the contract schema and the stage contracts once.
16
+ * @private
17
+ */
18
+ private _ensureContracts;
19
+ _ajv: any;
20
+ _contractSchema: any;
21
+ _contractSchemaValidator: any;
22
+ /**
23
+ * Load contract schema for validation
24
+ *
25
+ * @private
26
+ * @returns {Object|null} Contract schema or null if not found
27
+ *
28
+ * @since 2.2.4
29
+ */
30
+ private _loadContractSchema;
31
+ /**
32
+ * Validate contract against schema
33
+ *
34
+ * @private
35
+ * @param {Object} contract - Contract to validate
36
+ * @param {string} type - Contract type
37
+ * @returns {Object} Validation result { valid: boolean, errors: Array }
38
+ *
39
+ * @since 2.2.4
40
+ */
41
+ private _validateContractAgainstSchema;
42
+ /**
43
+ * Format schema validation errors for display
44
+ *
45
+ * @private
46
+ * @param {Array} errors - Ajv validation errors
47
+ * @returns {string} Formatted error message
48
+ *
49
+ * @since 2.2.4
50
+ */
51
+ private _formatSchemaErrors;
52
+ /**
53
+ * Check if a contract exists for the given plugin type
54
+ *
55
+ * @param {string} type - Plugin type (loader, embedder, etc.)
56
+ * @returns {boolean} True if contract exists, false otherwise
57
+ *
58
+ * @example
59
+ * const hasContract = registry.checkContractExists('loader');
60
+ * if (!hasContract) {
61
+ * console.warn('No contract for loader plugins');
62
+ * }
63
+ *
64
+ * @since 2.2.4
65
+ */
66
+ checkContractExists(type: string): boolean;
67
+ /**
68
+ * Log one-time warning for missing contract
69
+ *
70
+ * Logs a helpful warning message about the benefits of contracts
71
+ * and how to add them. Only logs once per contract type and only
72
+ * in non-production environments.
73
+ *
74
+ * @private
75
+ * @param {string} type - Plugin type
76
+ * @param {string} context - Context where warning is generated (e.g., 'load', 'register')
77
+ *
78
+ * @since 2.2.4
79
+ */
80
+ private _warnMissingContract;
81
+ _loadContracts(): void;
82
+ _validatePluginContract(category: any, impl: any): void;
83
+ _getRequiredMethodsFromContract(contract: any): any[];
84
+ /**
85
+ * Register a plugin.
86
+ *
87
+ * @param {string} category - Plugin type
88
+ * @param {string} name - Plugin name
89
+ * @param {object} impl - Plugin implementation
90
+ * @param {object|null} [manifest] - Signed manifest; when given, its
91
+ * signature is verified before registration
92
+ * @param {object} [options]
93
+ * @param {object} [options.content] - Plugin content checked against the
94
+ * manifest's contentDigest: `{ files, baseDir, contents }`
95
+ * @returns {Promise<PluginRegistry>}
96
+ */
97
+ register(category: string, name: string, impl: object, manifest?: object | null, options?: {
98
+ content?: object;
99
+ }): Promise<PluginRegistry>;
100
+ /**
101
+ * Verify plugin signature
102
+ * @param {object} manifest - Plugin manifest
103
+ * @param {string} pluginName - Plugin name
104
+ */
105
+ _verifyPluginSignature(manifest: object, pluginName: string, content?: any): Promise<void>;
106
+ /**
107
+ * Whether plugin signature verification is enabled for this registry.
108
+ * @returns {boolean}
109
+ */
110
+ isSignatureVerificationEnabled(): boolean;
111
+ /**
112
+ * Whether plugins without a signed manifest are rejected.
113
+ * @returns {boolean}
114
+ */
115
+ requiresSignedPlugins(): boolean;
116
+ /**
117
+ * Verify a plugin's signed manifest and code before it is loaded (use this
118
+ * before importing plugin files, since importing executes them).
119
+ *
120
+ * @param {string} pluginName - Plugin name (for audit entries)
121
+ * @param {object} manifest - Signed manifest
122
+ * @param {object} content - `{ files, baseDir, contents }`
123
+ * @returns {Promise<void>} Rejects if verification fails
124
+ */
125
+ verifyPluginContent(pluginName: string, manifest: object, content: object): Promise<void>;
126
+ /**
127
+ * Emit audit entry
128
+ * @param {string} action - Audit action
129
+ * @param {object} details - Audit details
130
+ */
131
+ _emitAuditEntry(action: string, details: object): void;
132
+ get(category: any, name: any): any;
133
+ resolve(category: any, name: any): any;
134
+ list(category: any): any[];
135
+ clear(): void;
136
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * What each pipeline stage must provide, as createRagPipeline and the CLI
3
+ * use it. A plugin needs at least one of `anyOf`; a missing `recommended`
4
+ * method only matters for the command named in its note.
5
+ *
6
+ * Shared by validatePlugin() and the `rag-pipeline init` wizard. The
7
+ * stricter rules pluginRegistry.register() applies (metadata, and the
8
+ * methods in contracts/*.json) are checked by validatePlugin(..., {
9
+ * registry: true }).
10
+ */
11
+ export const STAGE_CONTRACTS: Readonly<{
12
+ loader: {
13
+ anyOf: string[];
14
+ recommended: {};
15
+ };
16
+ embedder: {
17
+ anyOf: string[];
18
+ recommended: {
19
+ embed: string;
20
+ };
21
+ };
22
+ retriever: {
23
+ anyOf: string[];
24
+ recommended: {
25
+ store: string;
26
+ };
27
+ };
28
+ reranker: {
29
+ anyOf: string[];
30
+ recommended: {};
31
+ };
32
+ llm: {
33
+ anyOf: string[];
34
+ recommended: {};
35
+ };
36
+ }>;
@@ -0,0 +1,45 @@
1
+ export type PluginValidationResult = {
2
+ /**
3
+ * - True when there are no errors
4
+ */
5
+ valid: boolean;
6
+ /**
7
+ * - Problems that stop the plugin from working
8
+ */
9
+ errors: string[];
10
+ /**
11
+ * - Methods some commands need, e.g. `store`
12
+ * for `rag-pipeline ingest`
13
+ */
14
+ warnings: string[];
15
+ };
16
+ /**
17
+ * @typedef {Object} PluginValidationResult
18
+ * @property {boolean} valid - True when there are no errors
19
+ * @property {string[]} errors - Problems that stop the plugin from working
20
+ * @property {string[]} warnings - Methods some commands need, e.g. `store`
21
+ * for `rag-pipeline ingest`
22
+ */
23
+ /**
24
+ * Checks that an object can be used as a pipeline stage, without throwing,
25
+ * so plugin authors can assert on it in their own tests.
26
+ *
27
+ * By default it checks what createRagPipeline() calls. With
28
+ * `{ registry: true }` it also applies the rules pluginRegistry.register()
29
+ * enforces: `metadata` with a string `name` and `version` and a `type`
30
+ * equal to the stage, plus the methods in the stage's contract.
31
+ *
32
+ * @example
33
+ * const { validatePlugin } = require('@devilsdev/rag-pipeline-utils');
34
+ * const result = validatePlugin('llm', myLlm, { registry: true });
35
+ * expect(result.errors).toEqual([]);
36
+ *
37
+ * @param {'loader'|'embedder'|'retriever'|'reranker'|'llm'} stage
38
+ * @param {object} plugin - Plugin instance or object
39
+ * @param {Object} [options]
40
+ * @param {boolean} [options.registry=false] - Also check registry rules
41
+ * @returns {PluginValidationResult}
42
+ */
43
+ export function validatePlugin(stage: "loader" | "embedder" | "retriever" | "reranker" | "llm", plugin: object, options?: {
44
+ registry?: boolean;
45
+ }): PluginValidationResult;