@devilsdev/rag-pipeline-utils 2.4.5 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. package/.ragrc.schema.json +83 -192
  2. package/CHANGELOG.md +345 -0
  3. package/README.md +418 -117
  4. package/SECURITY.md +5 -5
  5. package/dist/experimental.cjs +2 -0
  6. package/dist/experimental.d.ts +1 -0
  7. package/dist/experimental.mjs +5 -0
  8. package/dist/index.cjs +4992 -1242
  9. package/dist/index.d.ts +80 -2
  10. package/dist/index.mjs +1 -1
  11. package/dist/types/agentic/agentic-pipeline.d.ts +103 -0
  12. package/dist/types/agentic/iterative-retriever.d.ts +85 -0
  13. package/dist/types/agentic/query-planner.d.ts +145 -0
  14. package/dist/types/agentic/self-critique.d.ts +45 -0
  15. package/dist/types/ai/adaptive-retrieval.d.ts +44 -0
  16. package/dist/types/ai/federation/federated-learning-coordinator.d.ts +62 -0
  17. package/dist/types/ai/multimodal-processing.d.ts +32 -0
  18. package/dist/types/ai/multimodal.d.ts +39 -0
  19. package/dist/types/ai/retrieval-engine.d.ts +37 -0
  20. package/dist/types/ai/training/model-training-orchestrator.d.ts +31 -0
  21. package/dist/types/chunking/chunking-engine.d.ts +70 -0
  22. package/dist/types/chunking/strategies/fixed-size.d.ts +17 -0
  23. package/dist/types/chunking/strategies/recursive.d.ts +20 -0
  24. package/dist/types/chunking/strategies/semantic.d.ts +19 -0
  25. package/dist/types/chunking/strategies/sentence.d.ts +13 -0
  26. package/dist/types/chunking/strategies/structure-aware.d.ts +19 -0
  27. package/dist/types/citation/citation-tracker.d.ts +64 -0
  28. package/dist/types/citation/hallucination-detector.d.ts +40 -0
  29. package/dist/types/citation/source-mapper.d.ts +37 -0
  30. package/dist/types/connectors/anthropic-connector.d.ts +92 -0
  31. package/dist/types/connectors/base-connector.d.ts +87 -0
  32. package/dist/types/connectors/cohere-connector.d.ts +89 -0
  33. package/dist/types/connectors/connector-utils.d.ts +110 -0
  34. package/dist/types/connectors/local-embedder.d.ts +86 -0
  35. package/dist/types/connectors/memory-retriever.d.ts +91 -0
  36. package/dist/types/connectors/ollama-connector.d.ts +110 -0
  37. package/dist/types/connectors/openai-connector.d.ts +114 -0
  38. package/dist/types/connectors/rag-prompt.d.ts +40 -0
  39. package/dist/types/cost/cost-calculator.d.ts +152 -0
  40. package/dist/types/cost/cost-tracker.d.ts +126 -0
  41. package/dist/types/cost/token-budget.d.ts +110 -0
  42. package/dist/types/dag/core/error-context.d.ts +239 -0
  43. package/dist/types/dag/core/execution-scheduler.d.ts +191 -0
  44. package/dist/types/dag/core/topology-validation.d.ts +226 -0
  45. package/dist/types/dag/dag-engine.d.ts +156 -0
  46. package/dist/types/dag/dag-node.d.ts +37 -0
  47. package/dist/types/dashboard/dashboard-generator.d.ts +127 -0
  48. package/dist/types/dashboard/metrics-aggregator.d.ts +218 -0
  49. package/dist/types/debug/execution-tracer.d.ts +57 -0
  50. package/dist/types/debug/trace-inspector.d.ts +31 -0
  51. package/dist/types/ecosystem/plugin-certification.d.ts +169 -0
  52. package/dist/types/enterprise/data-governance.d.ts +203 -0
  53. package/dist/types/enterprise/multi-tenancy.d.ts +137 -0
  54. package/dist/types/enterprise/sso-integration.d.ts +420 -0
  55. package/dist/types/evaluate/context-metrics.d.ts +55 -0
  56. package/dist/types/evaluate/faithfulness.d.ts +41 -0
  57. package/dist/types/evaluate/groundedness.d.ts +60 -0
  58. package/dist/types/evaluate/pipeline-evaluator.d.ts +88 -0
  59. package/dist/types/evaluate/relevance.d.ts +21 -0
  60. package/dist/types/evaluate/scoring.d.ts +123 -0
  61. package/dist/types/experimental.d.ts +15 -0
  62. package/dist/types/graph/entity-extractor.d.ts +84 -0
  63. package/dist/types/graph/graph-index.d.ts +49 -0
  64. package/dist/types/graph/graph-retriever.d.ts +81 -0
  65. package/dist/types/graph/knowledge-graph.d.ts +129 -0
  66. package/dist/types/guardrails/guardrails-pipeline.d.ts +63 -0
  67. package/dist/types/guardrails/injection-detector.d.ts +47 -0
  68. package/dist/types/guardrails/post-generation-guard.d.ts +61 -0
  69. package/dist/types/guardrails/pre-retrieval-guard.d.ts +64 -0
  70. package/dist/types/guardrails/retrieval-guard.d.ts +57 -0
  71. package/dist/types/mcp/mcp-server.d.ts +85 -0
  72. package/dist/types/mcp/mcp-tool-builder.d.ts +55 -0
  73. package/dist/types/reranker/cascade-reranker.d.ts +40 -0
  74. package/dist/types/reranker/embedding-reranker.d.ts +77 -0
  75. package/dist/types/reranker/scoring-reranker.d.ts +41 -0
  76. package/dist/types/retrieval/bm25-search.d.ts +43 -0
  77. package/dist/types/retrieval/file-vector-store.d.ts +87 -0
  78. package/dist/types/retrieval/hybrid-retriever.d.ts +35 -0
  79. package/dist/types/retrieval/rank-fusion.d.ts +10 -0
  80. package/dist/types/security/jwt-config.d.ts +80 -0
  81. package/dist/types/security/jwt-validator.d.ts +195 -0
  82. package/dist/types/security/plugin-sandbox.d.ts +158 -0
  83. package/dist/types/security/plugin-signature-verifier.d.ts +139 -0
  84. package/dist/types/security/validator.d.ts +5 -0
  85. package/dist/types/streaming/embedding-stream.d.ts +65 -0
  86. package/dist/types/streaming/sse-adapter.d.ts +59 -0
  87. package/dist/types/streaming/stream-router.d.ts +88 -0
  88. package/dist/types/streaming/streaming-embedder.d.ts +99 -0
  89. package/dist/types/streaming/websocket-adapter.d.ts +71 -0
  90. package/dist/types/templates/scaffold.d.ts +55 -0
  91. package/dist/types/templates/template-registry.d.ts +63 -0
  92. package/dist/types/utils/embed-query.d.ts +20 -0
  93. package/dist/types/utils/logger.d.ts +50 -0
  94. package/dist/types/utils/rate-limiter.d.ts +66 -0
  95. package/dist/types/utils/retry.d.ts +27 -0
  96. package/dist/types/utils/run-abort.d.ts +34 -0
  97. package/dist/types/utils/secure-logging.d.ts +51 -0
  98. package/dist/types/utils/structured-logger.d.ts +126 -0
  99. package/package.json +53 -29
  100. package/src/agentic/agentic-pipeline.js +75 -7
  101. package/src/agentic/iterative-retriever.js +47 -10
  102. package/src/agentic/query-planner.js +329 -78
  103. package/src/citation/citation-tracker.js +6 -4
  104. package/src/citation/hallucination-detector.js +2 -2
  105. package/src/citation/source-mapper.js +15 -28
  106. package/src/cli/commands/ai.js +101 -0
  107. package/src/cli/commands/plugin-hub/event-handlers.js +6 -0
  108. package/src/cli/commands/plugin-hub/hub-commands.js +0 -74
  109. package/src/cli/commands/plugin-hub/local-commands.js +143 -0
  110. package/src/cli/commands/plugin-hub.js +96 -36
  111. package/src/cli/diagnostics/config-checker.js +76 -63
  112. package/src/cli/diagnostics/environment-checker.js +62 -31
  113. package/src/cli/diagnostics/plugin-checker.js +36 -89
  114. package/src/cli/doctor-command.js +39 -5
  115. package/src/cli/enhanced-cli-commands.js +72 -217
  116. package/src/cli/handlers/ai-handler.js +364 -0
  117. package/src/cli/handlers/diagnostics-handler.js +78 -31
  118. package/src/cli/handlers/ingest-handler.js +28 -22
  119. package/src/cli/handlers/init-handler.js +148 -25
  120. package/src/cli/handlers/query-handler.js +41 -26
  121. package/src/cli/handlers/run-handler.js +16 -167
  122. package/src/cli/handlers/serve-handler.js +60 -0
  123. package/src/cli/services/bench-stats.js +54 -0
  124. package/src/cli/services/benchmark.js +161 -0
  125. package/src/cli/services/feedback.js +155 -0
  126. package/src/cli/services/rag-service.js +322 -0
  127. package/src/cli/shared/cli-utils.js +24 -7
  128. package/src/cli/shared/config-context.js +21 -0
  129. package/src/cli/wizard/config-builder.js +81 -0
  130. package/src/cli/wizard/init-wizard.js +617 -0
  131. package/src/config/component-factory.js +125 -0
  132. package/src/config/load-config.js +29 -10
  133. package/src/config/load-plugin-config.js +46 -2
  134. package/src/connectors/anthropic-connector.js +93 -55
  135. package/src/connectors/base-connector.js +74 -19
  136. package/src/connectors/cohere-connector.js +88 -32
  137. package/src/connectors/connector-utils.js +302 -0
  138. package/src/connectors/local-embedder.js +43 -5
  139. package/src/connectors/memory-retriever.js +108 -15
  140. package/src/connectors/ollama-connector.js +83 -49
  141. package/src/connectors/openai-connector.js +108 -44
  142. package/src/connectors/rag-prompt.js +88 -0
  143. package/src/core/create-pipeline.js +209 -60
  144. package/src/core/plugin-registry.js +87 -11
  145. package/src/cost/cost-calculator.js +205 -32
  146. package/src/dev/dev-server.js +166 -11
  147. package/src/dev/hot-reload.js +40 -1
  148. package/src/ecosystem/plugin-checks.js +181 -0
  149. package/src/ecosystem/plugin-hub.js +50 -125
  150. package/src/ecosystem/plugin-installer.js +298 -0
  151. package/src/ecosystem/plugin-probe.js +127 -0
  152. package/src/ecosystem/plugin-scanner.js +185 -0
  153. package/src/ecosystem/tar-extract.js +114 -0
  154. package/src/enterprise/audit-logging.js +158 -29
  155. package/src/enterprise/sso-integration.js +715 -228
  156. package/src/evaluate/context-metrics.js +28 -16
  157. package/src/evaluate/evaluator.js +3 -3
  158. package/src/evaluate/faithfulness.js +18 -14
  159. package/src/evaluate/groundedness.js +43 -12
  160. package/src/evaluate/pipeline-evaluator.js +35 -8
  161. package/src/evaluate/scoring.js +251 -3
  162. package/src/experimental.js +71 -0
  163. package/src/guardrails/guardrails-pipeline.js +69 -7
  164. package/src/guardrails/injection-detector.js +283 -0
  165. package/src/guardrails/post-generation-guard.js +19 -0
  166. package/src/guardrails/pre-retrieval-guard.js +36 -36
  167. package/src/guardrails/retrieval-guard.js +58 -8
  168. package/src/index.js +36 -1
  169. package/src/loader/document-reader.js +91 -0
  170. package/src/reranker/cascade-reranker.js +3 -0
  171. package/src/reranker/embedding-reranker.js +136 -21
  172. package/src/reranker/llm-reranker.js +79 -12
  173. package/src/reranker/scoring-reranker.js +3 -0
  174. package/src/retrieval/bm25-search.js +12 -6
  175. package/src/retrieval/file-vector-store.js +212 -0
  176. package/src/retrieval/hybrid-retriever.js +22 -19
  177. package/src/security/jwt-config.js +13 -2
  178. package/src/security/jwt-validator.js +134 -30
  179. package/src/security/plugin-sandbox.js +18 -1
  180. package/src/security/plugin-signature-verifier.js +245 -70
  181. package/src/utils/deprecate.js +69 -0
  182. package/src/utils/embed-query.js +33 -0
  183. package/src/utils/input-sanitizer.js +19 -4
  184. package/src/utils/logger.js +34 -4
  185. package/src/utils/run-abort.js +102 -0
  186. package/src/ai/federated-learning.js +0 -211
  187. package/src/ai/federation.js +0 -71
  188. package/src/ai/index.js +0 -22
  189. package/src/ai/model-trainer.js +0 -217
  190. package/src/ai/model-training.js +0 -202
  191. package/src/ai/multimodal/multi-modal-processor.js +0 -345
  192. package/src/ai/orchestrator.js +0 -65
  193. package/src/ai/retrieval/adaptive-retrieval-engine.js +0 -398
  194. package/src/cli/commands/ai-ml/adaptive-commands.js +0 -178
  195. package/src/cli/commands/ai-ml/federated-commands.js +0 -207
  196. package/src/cli/commands/ai-ml/index.js +0 -17
  197. package/src/cli/commands/ai-ml/multimodal-commands.js +0 -187
  198. package/src/cli/commands/ai-ml/shared.js +0 -51
  199. package/src/cli/commands/ai-ml/training-commands.js +0 -228
  200. package/src/cli/commands/ai-ml.js +0 -386
  201. package/src/cli/commands/docs.js +0 -228
  202. package/src/cli/commands/dx.js +0 -538
  203. package/src/cli/commands/wizard.js +0 -627
  204. package/src/cli/input-sanitization-middleware.js +0 -356
  205. package/src/cli/interactive-wizard.js +0 -373
  206. package/src/cli/templates/development.template.json +0 -64
  207. package/src/cli/templates/minimal.template.json +0 -33
  208. package/src/cli/templates/production.template.json +0 -104
  209. package/src/cli/templates/testing.template.json +0 -45
  210. package/src/cli/wizard/configuration.js +0 -148
  211. package/src/cli/wizard/observability.js +0 -79
  212. package/src/cli/wizard/performance.js +0 -76
  213. package/src/cli/wizard/plugin-selection.js +0 -297
  214. package/src/cli/wizard/preview-save.js +0 -172
  215. package/src/cli/wizard/project-setup.js +0 -66
  216. package/src/core/pipeline-factory.js +0 -59
  217. package/src/dag/enhanced-dag-engine.js +0 -894
  218. package/src/dx/index.js +0 -40
  219. package/src/dx/integration-templates.js +0 -662
  220. package/src/dx/performance-profiler.js +0 -968
  221. package/src/dx/realtime-debugger.js +0 -755
  222. package/src/dx/visual-pipeline-builder.js +0 -578
  223. package/src/ingest.js +0 -59
  224. package/src/pipeline/pipeline.js +0 -18
  225. package/src/query.js +0 -117
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Embedder + reranker connector for the Cohere API.
3
+ * Provides text embeddings (with separate document/query input types) and
4
+ * document reranking capabilities.
5
+ *
6
+ * @extends BaseConnector
7
+ */
8
+ export class CohereConnector extends BaseConnector {
9
+ /**
10
+ * @param {Object} [options]
11
+ * @param {string} [options.apiKey] - Cohere API key
12
+ * @param {string} [options.baseURL='https://api.cohere.ai/v1'] - API base URL
13
+ * @param {string} [options.embeddingModel='embed-english-v3.0'] - Embedding model
14
+ * @param {string} [options.rerankModel='rerank-english-v3.0'] - Reranking model
15
+ * @param {string} [options.inputType='search_document'] - Input type for document embeddings
16
+ * @param {string} [options.queryInputType='search_query'] - Input type for query embeddings
17
+ */
18
+ constructor(options?: {
19
+ apiKey?: string;
20
+ baseURL?: string;
21
+ embeddingModel?: string;
22
+ rerankModel?: string;
23
+ inputType?: string;
24
+ queryInputType?: string;
25
+ });
26
+ config: any;
27
+ client: axios.AxiosInstance;
28
+ /**
29
+ * @throws {Error} code MISSING_API_KEY when no key is configured
30
+ * @private
31
+ */
32
+ private _requireApiKey;
33
+ /**
34
+ * POST with the connector's retry policy and cancellation.
35
+ * @param {string} path
36
+ * @param {object} body
37
+ * @param {AbortSignal} [signal]
38
+ * @returns {Promise<object>} Response data
39
+ * @private
40
+ */
41
+ private _post;
42
+ /**
43
+ * Generate an embedding vector for document text.
44
+ * Uses the document input type by default.
45
+ *
46
+ * @param {string} text - Input text to embed
47
+ * @param {Object} [options={}]
48
+ * @param {AbortSignal} [options.signal] - Cancels the request
49
+ * @returns {Promise<number[]>} Embedding vector
50
+ */
51
+ embed(text: string, options?: {
52
+ signal?: AbortSignal;
53
+ }): Promise<number[]>;
54
+ /**
55
+ * Generate an embedding vector for a search query.
56
+ * Uses the query input type for better retrieval accuracy.
57
+ *
58
+ * @param {string} query - Query text to embed
59
+ * @param {Object} [options={}]
60
+ * @param {AbortSignal} [options.signal] - Cancels the request
61
+ * @returns {Promise<number[]>} Embedding vector
62
+ */
63
+ embedQuery(query: string, options?: {
64
+ signal?: AbortSignal;
65
+ }): Promise<number[]>;
66
+ /**
67
+ * Rerank documents by relevance to a query using Cohere's reranker.
68
+ *
69
+ * @param {string} query - The search query
70
+ * @param {Array<Object|string>} documents - Documents to rerank
71
+ * @param {Object} [options={}]
72
+ * @param {number} [options.topK] - Number of top results to return (defaults to all)
73
+ * @param {AbortSignal} [options.signal] - Cancels the request
74
+ * @returns {Promise<Array<Object>>} Reranked documents with relevance scores
75
+ */
76
+ rerank(query: string, documents: Array<any | string>, options?: {
77
+ topK?: number;
78
+ signal?: AbortSignal;
79
+ }): Promise<Array<any>>;
80
+ }
81
+ /**
82
+ * Default configuration for the Cohere connector.
83
+ * `apiKey` is a getter so the environment is read when a connector is
84
+ * constructed, not when this module is first required.
85
+ * @type {Object}
86
+ */
87
+ export const DEFAULT_CONFIG: any;
88
+ import { BaseConnector } from "./base-connector";
89
+ import axios = require("axios");
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Create an AbortError for the given signal.
3
+ * Reuses signal.reason when it already is an AbortError.
4
+ *
5
+ * @param {AbortSignal} [signal]
6
+ * @returns {Error} Error with name 'AbortError' and code 'ABORT_ERR'
7
+ */
8
+ export function createAbortError(signal?: AbortSignal): Error;
9
+ /**
10
+ * @param {*} err
11
+ * @returns {boolean} True when err represents a cancellation.
12
+ */
13
+ export function isAbortError(err: any): boolean;
14
+ /**
15
+ * Throw an AbortError when the signal is already aborted.
16
+ * @param {AbortSignal} [signal]
17
+ */
18
+ export function throwIfAborted(signal?: AbortSignal): void;
19
+ /**
20
+ * Race a promise against an AbortSignal so callers reject promptly even when
21
+ * the underlying SDK or HTTP client ignores the signal. The abort listener is
22
+ * removed once the promise settles.
23
+ *
24
+ * @template T
25
+ * @param {Promise<T>|(() => Promise<T>)} work - Promise or function returning one
26
+ * @param {AbortSignal} [signal]
27
+ * @returns {Promise<T>}
28
+ */
29
+ export function raceAbort<T>(work: Promise<T> | (() => Promise<T>), signal?: AbortSignal): Promise<T>;
30
+ /**
31
+ * Sleep that rejects with AbortError as soon as the signal aborts.
32
+ * @param {number} ms
33
+ * @param {AbortSignal} [signal]
34
+ * @returns {Promise<void>}
35
+ */
36
+ export function abortableSleep(ms: number, signal?: AbortSignal): Promise<void>;
37
+ /**
38
+ * Extract the HTTP status from an openai SDK error or an axios error.
39
+ * @param {*} err
40
+ * @returns {number|undefined}
41
+ */
42
+ export function getErrorStatus(err: any): number | undefined;
43
+ /**
44
+ * Parse Retry-After / retry-after-ms from an error's response headers.
45
+ *
46
+ * @param {*} err
47
+ * @param {number} [now=Date.now()]
48
+ * @returns {number|undefined} Delay in milliseconds, or undefined when absent
49
+ */
50
+ export function getRetryAfterMs(err: any, now?: number): number | undefined;
51
+ /**
52
+ * Default retry classification: network failures and HTTP
53
+ * 408/409/425/429/5xx are retried; aborts, other 4xx (400, 401, 403, 404,
54
+ * 422, ...) and errors without a status or network code are not.
55
+ *
56
+ * @param {*} err
57
+ * @returns {boolean}
58
+ */
59
+ export function isRetryableError(err: any): boolean;
60
+ /**
61
+ * Compute the delay before the next retry attempt.
62
+ * Honours Retry-After (capped at maxDelay); otherwise uses exponential backoff
63
+ * with full jitter: random() * min(maxDelay, baseDelay * 2^attempt).
64
+ *
65
+ * @param {*} err - The error that triggered the retry
66
+ * @param {number} attempt - Zero-based retry attempt
67
+ * @param {object} [opts]
68
+ * @param {number} [opts.baseDelay=1000]
69
+ * @param {number} [opts.maxDelay=30000]
70
+ * @param {() => number} [opts.random=Math.random]
71
+ * @returns {number} Delay in milliseconds
72
+ */
73
+ export function computeRetryDelay(err: any, attempt: number, opts?: {
74
+ baseDelay?: number;
75
+ maxDelay?: number;
76
+ random?: () => number;
77
+ }): number;
78
+ /**
79
+ * Resolve an API key at construction time. An explicit option (even '')
80
+ * wins over the environment variable.
81
+ *
82
+ * @param {object} options - Connector options
83
+ * @param {string} envVar - Environment variable name
84
+ * @returns {string}
85
+ */
86
+ export function resolveApiKey(options: object, envVar: string): string;
87
+ /**
88
+ * Error thrown when a provider call is attempted without an API key.
89
+ * @param {string} provider - Display name, e.g. 'OpenAI'
90
+ * @param {string} envVar - Environment variable name
91
+ * @returns {Error}
92
+ */
93
+ export function missingApiKeyError(provider: string, envVar: string): Error;
94
+ /**
95
+ * Build request options carrying the signal only when one was supplied, so
96
+ * calls without a signal look exactly as before.
97
+ * @param {AbortSignal} [signal]
98
+ * @returns {object}
99
+ */
100
+ export function signalOptions(signal?: AbortSignal): object;
101
+ /**
102
+ * Shared helpers for the built-in connectors: AbortSignal handling, retry
103
+ * classification and backoff, and API key resolution.
104
+ *
105
+ * Everything here must run on Node 18 (no AbortSignal.any, no crypto.hash).
106
+ */
107
+ /** HTTP status codes that are worth retrying. */
108
+ export const RETRYABLE_STATUS: Set<number>;
109
+ /** Error codes produced by Node, axios and undici for transient network failures. */
110
+ export const RETRYABLE_CODES: Set<string>;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * TF-IDF based embedder for fully offline use.
3
+ * No external API required -- builds a vocabulary from training documents
4
+ * and produces sparse TF-IDF vectors.
5
+ * @extends BaseConnector
6
+ */
7
+ export class LocalEmbedder extends BaseConnector {
8
+ /**
9
+ * @param {Object} options
10
+ * @param {number} [options.maxVocabularySize=10000] - Maximum vocabulary size
11
+ * @param {number} [options.minDocFrequency=1] - Minimum document frequency for a token to be included
12
+ */
13
+ constructor(options?: {
14
+ maxVocabularySize?: number;
15
+ minDocFrequency?: number;
16
+ });
17
+ config: any;
18
+ /** @type {Map<string, number>} token -> vocabulary index */
19
+ vocabulary: Map<string, number>;
20
+ /** @type {Map<string, number>} token -> IDF weight */
21
+ idf: Map<string, number>;
22
+ /** @type {number} */
23
+ docCount: number;
24
+ /**
25
+ * Build vocabulary and IDF weights from a corpus of documents.
26
+ * @param {Array<string|{ content?: string, text?: string }>} documents - Training documents
27
+ */
28
+ train(documents: Array<string | {
29
+ content?: string;
30
+ text?: string;
31
+ }>): void;
32
+ /**
33
+ * Compute a TF-IDF vector for the given text.
34
+ * The vector length equals the vocabulary size. Synchronous; when
35
+ * options.signal is already aborted it throws an AbortError (which an
36
+ * awaiting caller sees as a rejection).
37
+ * @param {string} text - Text to embed
38
+ * @param {Object} [options={}]
39
+ * @param {AbortSignal} [options.signal] - Cancellation signal
40
+ * @returns {number[]} L2-normalized TF-IDF vector
41
+ */
42
+ embed(text: string, options?: {
43
+ signal?: AbortSignal;
44
+ }): number[];
45
+ /**
46
+ * Compute a TF-IDF vector for a query string.
47
+ * Alias for {@link embed}.
48
+ * @param {string} query - Query text to embed
49
+ * @param {Object} [options={}] - Same as embed()
50
+ * @returns {number[]} L2-normalized TF-IDF vector
51
+ */
52
+ embedQuery(query: string, options?: any): number[];
53
+ /**
54
+ * Serializable vocabulary and IDF weights, so a trained embedder can be
55
+ * restored in another process (e.g. by FileVectorStore-backed CLI queries).
56
+ *
57
+ * @returns {{docCount: number, vocabulary: Array<[string, number]>, idf: Array<[string, number]>}}
58
+ */
59
+ getState(): {
60
+ docCount: number;
61
+ vocabulary: Array<[string, number]>;
62
+ idf: Array<[string, number]>;
63
+ };
64
+ /**
65
+ * Restore state produced by getState().
66
+ * @param {{docCount: number, vocabulary: Array<[string, number]>, idf: Array<[string, number]>}} state
67
+ */
68
+ setState(state: {
69
+ docCount: number;
70
+ vocabulary: Array<[string, number]>;
71
+ idf: Array<[string, number]>;
72
+ }): void;
73
+ /** @returns {number} Vector length produced by embed() once trained */
74
+ get dimensions(): number;
75
+ /**
76
+ * Get the current vocabulary size.
77
+ * @returns {number}
78
+ */
79
+ getVocabularySize(): number;
80
+ }
81
+ /**
82
+ * Default configuration for the local TF-IDF embedder.
83
+ * @type {Object}
84
+ */
85
+ export const DEFAULT_CONFIG: any;
86
+ import { BaseConnector } from "./base-connector";
@@ -0,0 +1,91 @@
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
+ /**
28
+ * Store one or more vector documents. The batch is validated before
29
+ * anything is inserted, so a rejected call leaves the store unchanged.
30
+ *
31
+ * @param {Array<{ id: string, vector: number[], metadata?: Object, content?: string }>} vectors
32
+ * @returns {Promise<void>}
33
+ * @throws {Error} When a vector's dimension differs from the store's, or
34
+ * (eviction 'error') when the store would exceed maxDocuments
35
+ */
36
+ store(vectors: Array<{
37
+ id: string;
38
+ vector: number[];
39
+ metadata?: any;
40
+ content?: string;
41
+ }>): Promise<void>;
42
+ /**
43
+ * Retrieve the top-k most similar documents to a query vector.
44
+ * @param {number[]|{ query?: string, queryVector: number[], topK?: number, signal?: AbortSignal }} queryOrObj
45
+ * Either a raw vector array or an object with queryVector, optional topK
46
+ * and optional AbortSignal.
47
+ * @param {number} [k=10] - Number of results to return (used when queryOrObj is an array)
48
+ * @returns {Promise<Array<{ id: string, score: number, metadata: Object, content: string }>>}
49
+ * @throws {Error} When the query vector's dimension differs from the stored vectors
50
+ */
51
+ retrieve(queryOrObj: number[] | {
52
+ query?: string;
53
+ queryVector: number[];
54
+ topK?: number;
55
+ signal?: AbortSignal;
56
+ }, k?: number): Promise<Array<{
57
+ id: string;
58
+ score: number;
59
+ metadata: any;
60
+ content: string;
61
+ }>>;
62
+ /**
63
+ * Compute cosine similarity between two vectors of equal length.
64
+ * @param {number[]} a - First vector
65
+ * @param {number[]} b - Second vector
66
+ * @returns {number} Cosine similarity in the range [-1, 1], or 0 for zero vectors
67
+ * @throws {Error} When the vectors have different lengths
68
+ * @private
69
+ */
70
+ private _cosineSimilarity;
71
+ /**
72
+ * Remove all stored documents and reset the vector dimension.
73
+ * @returns {Promise<void>}
74
+ */
75
+ clear(): Promise<void>;
76
+ /**
77
+ * Get statistics about the store.
78
+ * @returns {{ documentCount: number, maxDocuments: number, dimensions: number|null }}
79
+ */
80
+ getStats(): {
81
+ documentCount: number;
82
+ maxDocuments: number;
83
+ dimensions: number | null;
84
+ };
85
+ }
86
+ /**
87
+ * Default configuration for the in-memory retriever.
88
+ * @type {Object}
89
+ */
90
+ export const DEFAULT_CONFIG: any;
91
+ import { BaseConnector } from "./base-connector";
@@ -0,0 +1,110 @@
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
+ config: any;
30
+ client: axios.AxiosInstance;
31
+ /**
32
+ * POST with the connector's retry policy and cancellation.
33
+ * @private
34
+ */
35
+ private _post;
36
+ /**
37
+ * Build the /api/generate body. Retrieved context goes into the prompt as
38
+ * delimited, untrusted reference data; instructions go in `system`.
39
+ * @private
40
+ */
41
+ private _buildBody;
42
+ /**
43
+ * Generate a response for the given query with optional context documents.
44
+ * @param {string} query - The user query
45
+ * @param {Array<Object|string>} [context=[]] - Context documents for RAG
46
+ * @param {Object} [options={}] - Override options
47
+ * @param {string} [options.model] - Override the generation model
48
+ * @param {number} [options.temperature] - Override temperature
49
+ * @param {AbortSignal} [options.signal] - Cancels the request
50
+ * @returns {Promise<string>} Generated response text
51
+ */
52
+ generate(query: string, context?: Array<any | string>, options?: {
53
+ model?: string;
54
+ temperature?: number;
55
+ signal?: AbortSignal;
56
+ }): Promise<string>;
57
+ /**
58
+ * Stream a response token-by-token for the given query.
59
+ * @param {string} query - The user query
60
+ * @param {Array<Object|string>} [context=[]] - Context documents for RAG
61
+ * @param {Object} [options={}] - Override options
62
+ * @param {string} [options.model] - Override the generation model
63
+ * @param {number} [options.temperature] - Override temperature
64
+ * @param {AbortSignal} [options.signal] - Cancels the stream
65
+ * @yields {{ token: string, done: boolean }}
66
+ */
67
+ generateStream(query: string, context?: Array<any | string>, options?: {
68
+ model?: string;
69
+ temperature?: number;
70
+ signal?: AbortSignal;
71
+ }): AsyncGenerator<{
72
+ token: any;
73
+ done: boolean;
74
+ }, void, unknown>;
75
+ /**
76
+ * Generate an embedding vector for the given text.
77
+ * @param {string} text - Text to embed
78
+ * @param {Object} [options={}]
79
+ * @param {AbortSignal} [options.signal] - Cancels the request
80
+ * @returns {Promise<number[]>} Embedding vector
81
+ */
82
+ embed(text: string, options?: {
83
+ signal?: AbortSignal;
84
+ }): Promise<number[]>;
85
+ /**
86
+ * Generate an embedding vector for a query string.
87
+ * Alias for {@link embed}.
88
+ * @param {string} query - Query text to embed
89
+ * @param {Object} [options={}] - Same as embed()
90
+ * @returns {Promise<number[]>} Embedding vector
91
+ */
92
+ embedQuery(query: string, options?: any): Promise<number[]>;
93
+ /**
94
+ * Build a prompt string incorporating context documents.
95
+ * Kept for backward compatibility; context is delimited and labelled as
96
+ * untrusted reference data.
97
+ * @param {string} query - The user query
98
+ * @param {Array<Object|string>} context - Context documents
99
+ * @returns {string} Formatted prompt
100
+ * @private
101
+ */
102
+ private _buildPrompt;
103
+ }
104
+ /**
105
+ * Default configuration for the Ollama connector.
106
+ * @type {Object}
107
+ */
108
+ export const DEFAULT_CONFIG: any;
109
+ import { BaseConnector } from "./base-connector";
110
+ import axios = require("axios");
@@ -0,0 +1,114 @@
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] - OpenAI API key (defaults to OPENAI_API_KEY at construction)
15
+ * @param {number} [options.maxRetries=3] - Retries for transient failures (the SDK's own retries are disabled)
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
+ model?: string;
21
+ embeddingModel?: string;
22
+ temperature?: number;
23
+ maxTokens?: number;
24
+ apiKey?: string;
25
+ maxRetries?: number;
26
+ retryDelay?: number;
27
+ systemPrompt?: string;
28
+ });
29
+ config: any;
30
+ _client: any;
31
+ /**
32
+ * Lazily initialise and return the OpenAI client.
33
+ * SDK retries are disabled (maxRetries: 0); withRetry() owns the policy.
34
+ * @returns {Object} OpenAI client instance
35
+ * @private
36
+ */
37
+ private _getClient;
38
+ /**
39
+ * @throws {Error} code MISSING_API_KEY when no key is configured
40
+ * @private
41
+ */
42
+ private _requireApiKey;
43
+ /**
44
+ * Run a request with the connector's retry policy and cancellation.
45
+ * @private
46
+ */
47
+ private _request;
48
+ /**
49
+ * Generate a chat completion using the provided query and optional RAG context.
50
+ *
51
+ * @param {string} query - The user query / prompt
52
+ * @param {Array<Object|string>} [context=[]] - Retrieved documents for RAG
53
+ * @param {Object} [options={}] - Override model, temperature, maxTokens per-call
54
+ * @param {AbortSignal} [options.signal] - Cancels the request
55
+ * @returns {Promise<string>} The generated text
56
+ */
57
+ generate(query: string, context?: Array<any | string>, options?: {
58
+ signal?: AbortSignal;
59
+ }): Promise<string>;
60
+ /**
61
+ * Stream a chat completion token-by-token.
62
+ *
63
+ * @param {string} query - The user query / prompt
64
+ * @param {Array<Object|string>} [context=[]] - Retrieved documents for RAG
65
+ * @param {Object} [options={}] - Override model, temperature, maxTokens per-call
66
+ * @param {AbortSignal} [options.signal] - Cancels the stream
67
+ * @yields {{ token: string, done: boolean }}
68
+ */
69
+ generateStream(query: string, context?: Array<any | string>, options?: {
70
+ signal?: AbortSignal;
71
+ }): AsyncGenerator<{
72
+ token: any;
73
+ done: boolean;
74
+ }, void, unknown>;
75
+ /**
76
+ * Generate an embedding vector for the given text.
77
+ *
78
+ * @param {string} text - Input text to embed
79
+ * @param {Object} [options={}]
80
+ * @param {AbortSignal} [options.signal] - Cancels the request
81
+ * @returns {Promise<number[]>} Embedding vector
82
+ */
83
+ embed(text: string, options?: {
84
+ signal?: AbortSignal;
85
+ }): Promise<number[]>;
86
+ /**
87
+ * Generate an embedding vector for a search query.
88
+ * Alias for {@link OpenAIConnector#embed}.
89
+ *
90
+ * @param {string} query - Query text to embed
91
+ * @param {Object} [options={}] - Same as embed()
92
+ * @returns {Promise<number[]>} Embedding vector
93
+ */
94
+ embedQuery(query: string, options?: any): Promise<number[]>;
95
+ /**
96
+ * Build the messages array for a chat completion request. Retrieved
97
+ * context goes into the user message as delimited, untrusted reference
98
+ * data; the system message only carries instructions.
99
+ *
100
+ * @param {string} query - User query
101
+ * @param {Array<Object|string>} context - RAG context documents
102
+ * @returns {Array<{ role: string, content: string }>}
103
+ * @private
104
+ */
105
+ private _buildMessages;
106
+ }
107
+ /**
108
+ * Default configuration for the OpenAI connector.
109
+ * `apiKey` is a getter so the environment is read when a connector is
110
+ * constructed, not when this module is first required.
111
+ * @type {Object}
112
+ */
113
+ export const DEFAULT_CONFIG: any;
114
+ 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;