@devilsdev/rag-pipeline-utils 2.5.0 → 2.6.1

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 (66) hide show
  1. package/CHANGELOG.md +102 -0
  2. package/README.md +99 -24
  3. package/dist/index.cjs +1484 -147
  4. package/dist/index.d.ts +49 -0
  5. package/dist/index.mjs +1 -1
  6. package/dist/testing.cjs +2 -0
  7. package/dist/testing.d.ts +1 -0
  8. package/dist/testing.mjs +5 -0
  9. package/dist/types/adapters/ai-sdk.d.ts +53 -0
  10. package/dist/types/cache/component-keys.d.ts +7 -0
  11. package/dist/types/cache/memory-cache.d.ts +54 -0
  12. package/dist/types/cache/pipeline-cache.d.ts +66 -0
  13. package/dist/types/cache/redis-cache.d.ts +46 -0
  14. package/dist/types/connectors/anthropic-connector.d.ts +7 -2
  15. package/dist/types/connectors/cohere-connector.d.ts +7 -2
  16. package/dist/types/connectors/local-embedder.d.ts +9 -0
  17. package/dist/types/connectors/memory-retriever.d.ts +8 -0
  18. package/dist/types/connectors/ollama-connector.d.ts +7 -2
  19. package/dist/types/connectors/openai-connector.d.ts +16 -1
  20. package/dist/types/core/create-pipeline.d.ts +8 -0
  21. package/dist/types/core/plugin-registry.d.ts +136 -0
  22. package/dist/types/core/stage-contracts.d.ts +36 -0
  23. package/dist/types/core/validate-plugin.d.ts +45 -0
  24. package/dist/types/evaluate/semantic-similarity.d.ts +14 -0
  25. package/dist/types/grounding/check-answer.d.ts +101 -0
  26. package/dist/types/retrieval/file-vector-store.d.ts +12 -0
  27. package/dist/types/testing.d.ts +168 -0
  28. package/package.json +22 -7
  29. package/src/adapters/ai-sdk.js +215 -0
  30. package/src/cache/component-keys.js +38 -0
  31. package/src/cache/memory-cache.js +87 -0
  32. package/src/cache/pipeline-cache.js +260 -0
  33. package/src/cache/redis-cache.js +83 -0
  34. package/src/cli/commands/ai.js +17 -12
  35. package/src/cli/commands/plugin-hub.js +18 -13
  36. package/src/cli/enhanced-cli-commands.js +45 -29
  37. package/src/cli/handlers/query-handler.js +174 -11
  38. package/src/cli/services/instrument.js +83 -0
  39. package/src/cli/services/rag-service.js +51 -12
  40. package/src/cli/wizard/init-wizard.js +2 -17
  41. package/src/config/enhanced-ragrc-schema.js +0 -2
  42. package/src/config/validate-schema.js +4 -1
  43. package/src/connectors/anthropic-connector.js +22 -2
  44. package/src/connectors/cohere-connector.js +20 -2
  45. package/src/connectors/local-embedder.js +20 -0
  46. package/src/connectors/memory-retriever.js +18 -0
  47. package/src/connectors/ollama-connector.js +29 -2
  48. package/src/connectors/openai-connector.js +49 -4
  49. package/src/core/create-pipeline.js +112 -15
  50. package/src/core/performance/parallel-processor.js +62 -1
  51. package/src/core/plugin-registry.js +42 -19
  52. package/src/core/stage-contracts.js +36 -0
  53. package/src/core/validate-plugin.js +85 -0
  54. package/src/debug/execution-tracer.js +14 -4
  55. package/src/dev/dev-server.js +8 -1
  56. package/src/dev/hot-reload.js +4 -3
  57. package/src/enterprise/sso-integration.js +4 -3
  58. package/src/evaluate/semantic-similarity.js +79 -0
  59. package/src/grounding/check-answer.js +173 -0
  60. package/src/index.js +22 -0
  61. package/src/loader/csv-loader.js +3 -2
  62. package/src/loader/html-loader.js +3 -1
  63. package/src/loader/markdown-loader.js +3 -2
  64. package/src/retrieval/file-vector-store.js +30 -1
  65. package/src/security/jwt-validator.js +5 -4
  66. package/src/testing.js +254 -0
package/CHANGELOG.md CHANGED
@@ -9,6 +9,105 @@ Older history (pre-2.4.0) is preserved in the
9
9
  [GitHub releases](https://github.com/DevilsDev/rag-pipeline-utils/releases)
10
10
  page.
11
11
 
12
+ ## [Unreleased]
13
+
14
+ ## [2.6.1] - 2026-10-29
15
+
16
+ Documentation only; no code changes.
17
+
18
+ ### Changed
19
+
20
+ - **README covers the 2.6.0 features**, so the npm package page shows
21
+ them: `checkAnswer` for answers from other frameworks, the `/testing`
22
+ entry, caching, the `query` `--explain`, `--trace`, `--stats` and
23
+ `--streaming` options, `OpenAIConnector` `baseURL` and the AI SDK
24
+ adapter.
25
+ - **StackBlitz examples checked**: the basic pipeline, OpenAI with
26
+ Pinecone (offline mock) and the Fastify service each install and run.
27
+ The docs now say to reload if StackBlitz stalls while cloning.
28
+
29
+ ## [2.6.0] - 2026-10-29
30
+
31
+ ### Added
32
+
33
+ - **`OpenAIConnector` `baseURL`** for OpenAI-compatible APIs (Groq,
34
+ Together, the Hugging Face router, vLLM, LM Studio, Ollama's `/v1`
35
+ endpoint). With a custom `baseURL` the key is never read from
36
+ `OPENAI_API_KEY`, so an OpenAI key is not sent to another provider; pass
37
+ `apiKey`, or omit it for local servers that need none.
38
+ - **`validatePlugin(stage, plugin, { registry })`** returns
39
+ `{ valid, errors, warnings }` for a plugin without throwing, for use in
40
+ plugin tests. `registry: true` also applies the rules
41
+ `pluginRegistry.register()` enforces.
42
+ - **`ParallelEmbedder` `mode`** (`'auto'`, `'batch'`, `'single'`).
43
+ - **`checkAnswer({ question, answer, sources })`** checks an answer from any
44
+ framework (LangChain, LlamaIndex, Mastra, the AI SDK, your own code)
45
+ against its sources: `grounded`, `groundedness`, the `unsupported`
46
+ sentences, per-sentence `citations` and `evaluation` scores. Sources may be
47
+ strings, `{ id, content }`, LangChain Documents or LlamaIndex nodes;
48
+ `normalizeSources` is exported for the conversion alone.
49
+ - **Caching**: `createRagPipeline({ cache })` caches query embeddings,
50
+ retrieval results and answers (`true`, a store, or per layer with time to
51
+ live). `MemoryCache` (LRU and TTL) and `RedisCache` (node-redis or
52
+ ioredis) are included; any `get`/`set` store works. A layer caches only
53
+ when its component identifies itself (`getCacheKey(role)` or `cacheKey`;
54
+ all built-ins do), retrieval is keyed by the store's state and the query
55
+ vector, answers by the exact documents and generation options, and
56
+ answers are not cached when the temperature is above 0. Retrieval is
57
+ cached before `filterResults` and the reranker, so guardrail ACLs run on
58
+ every request. Nothing from a failed, aborted or timed-out run, or from an
59
+ unfinished stream, is stored. Results carry `cache` per layer and the
60
+ pipeline has `cacheStats()`.
61
+ - **`@devilsdev/rag-pipeline-utils/testing`**: deterministic, offline test
62
+ helpers. `HashEmbedder`, `EchoLLM` (answers with the top document or a set
63
+ answer, records every call, streams), `fixtures.documents` and
64
+ `createTestPipeline()`. Shares classes with the main entry and is not
65
+ loaded by it.
66
+ - **`computeSemanticSimilarity(answer, reference, { embedder })`**: cosine
67
+ similarity of the two embeddings, 0 to 1. `checkAnswer` adds it as
68
+ `evaluation.scores.semanticSimilarity` when given a `referenceAnswer` and
69
+ an `embedder`.
70
+ - **`rag-pipeline query`** options: `--trace` (time per stage), `--explain`
71
+ (passage scores, and the passages supporting each answer sentence, with
72
+ unsupported sentences flagged), `--stats` (latency, estimated tokens and
73
+ cost), `--streaming` and `--timeout <ms>`; global `--quiet`. `--json`
74
+ includes trace, stats and explanation when asked.
75
+ - **`createAiSdkAdapter({ ai, embeddingModel, languageModel })`** wraps
76
+ Vercel AI SDK models as an `embedder` and an `llm` for
77
+ `createRagPipeline()`, with streaming, `embedMany` batching and the run's
78
+ `AbortSignal`. You pass the AI SDK functions, so it is not a dependency and
79
+ works with AI SDK 5, 6 and 7 from ESM or CommonJS. The RAG system prompt
80
+ is sent as both `instructions` (AI SDK 7) and `system` (5 and 6). Tested
81
+ against AI SDK 6 and 7 with their mock models.
82
+
83
+ ### Changed
84
+
85
+ - **Faster CLI.** Commands load only their own dependencies: `--help`
86
+ takes about 0.5 s and `query` about 0.5 s instead of about 3.6 s. Loading
87
+ the CLI drops from 1281 modules and 93 packages to 55 and 13. The HTML,
88
+ Markdown and CSV loaders load `jsdom`, `marked` and `csv-parse` when they
89
+ read a file.
90
+ - **Faster import.** `require('@devilsdev/rag-pipeline-utils')` takes about
91
+ 125 ms instead of about 515 ms and loads 31 modules from 9 packages
92
+ instead of 245 from 54 (published bundle, Node 22). `axios`,
93
+ `jsonwebtoken`, `ajv` and `chokidar` now load when the feature that needs
94
+ them is first used (the Anthropic, Cohere and Ollama connectors,
95
+ `JWTValidator`, plugin registration and config validation, hot reload).
96
+ The shared `pluginRegistry` loads its contracts on first use; registries
97
+ created with `new PluginRegistry()` still load them in the constructor.
98
+
99
+ ### Fixed
100
+
101
+ - **`ExecutionTracer.exportTraces('json')`** threw "circular structure"
102
+ with the default `captureOutputs: true`: traces stored the live result,
103
+ which carries the trace. Traces now store JSON snapshots, which also keeps
104
+ later changes to a result out of its recorded trace.
105
+ - **`ParallelEmbedder`** failed with the built-in connectors, which embed
106
+ one string at a time, because it always called `embed(batch)` with an
107
+ array. In the default `'auto'` mode it now embeds texts one by one for
108
+ those connectors and uses `embedBatch(texts)` when an embedder has it;
109
+ other embedders are still called with the array.
110
+
12
111
  ## [2.5.0] - 2026-10-28
13
112
 
14
113
  ### Added
@@ -468,6 +567,9 @@ First public release on the 2.4 line, introducing the v2.4 feature set.
468
567
  For release notes prior to v2.4.0, see
469
568
  [github.com/DevilsDev/rag-pipeline-utils/releases](https://github.com/DevilsDev/rag-pipeline-utils/releases).
470
569
 
570
+ [2.6.1]: https://github.com/DevilsDev/rag-pipeline-utils/releases/tag/v2.6.1
571
+ [2.6.0]: https://github.com/DevilsDev/rag-pipeline-utils/releases/tag/v2.6.0
572
+ [2.5.0]: https://github.com/DevilsDev/rag-pipeline-utils/releases/tag/v2.5.0
471
573
  [2.4.5]: https://github.com/DevilsDev/rag-pipeline-utils/releases/tag/v2.4.5
472
574
  [2.4.4]: https://github.com/DevilsDev/rag-pipeline-utils/releases/tag/v2.4.4
473
575
  [2.4.3]: https://github.com/DevilsDev/rag-pipeline-utils/releases/tag/v2.4.3
package/README.md CHANGED
@@ -143,7 +143,15 @@ npx rag-pipeline serve --port 3000 # local HTTP API: GET /health, POST /
143
143
  npx rag-pipeline doctor # checks config, API keys, plugins and the index
144
144
  ```
145
145
 
146
- The default `local` template needs no API keys. Use `init --template openai`, `anthropic` or `ollama` to generate answers with a model. Other commands include `validate`, `hub install` for plugins and `ai benchmark` for measured latency. See the [CLI reference](https://devilsdev.github.io/rag-pipeline-utils/docs/CLI).
146
+ The default `local` template needs no API keys. Use `init --template openai`, `anthropic` or `ollama` to generate answers with a model. Other commands include `validate`, `hub install` for plugins and `ai benchmark` for measured latency.
147
+
148
+ `query` can also show its work: `--explain` lists each passage's score and which passages support each sentence, `--trace` times each stage, `--stats` estimates tokens and cost, and `--streaming` prints the answer as it is generated:
149
+
150
+ ```bash
151
+ npx rag-pipeline query "How many vacation days do I get?" --explain --trace
152
+ ```
153
+
154
+ See the [CLI reference](https://devilsdev.github.io/rag-pipeline-utils/docs/CLI).
147
155
 
148
156
  ## Use cases
149
157
 
@@ -198,6 +206,45 @@ console.log(report.scores); // includes contextRecall because a reference was gi
198
206
  if (report.scores.faithfulness < 0.8) process.exitCode = 1;
199
207
  ```
200
208
 
209
+ ### Check answers from another framework
210
+
211
+ Already on LangChain, LlamaIndex, Mastra or the AI SDK? `checkAnswer` checks the answer your chain produced against the sources it was given, in the shape your framework returns them:
212
+
213
+ ```js
214
+ import { checkAnswer } from "@devilsdev/rag-pipeline-utils";
215
+
216
+ const check = await checkAnswer({
217
+ question: "How many vacation days do I get?",
218
+ answer: "Full-time employees receive thirty days of paid vacation per year.",
219
+ sources: [
220
+ {
221
+ pageContent:
222
+ "Full-time employees receive twenty days of paid vacation per year.",
223
+ metadata: { source: "handbook.md" },
224
+ },
225
+ ],
226
+ });
227
+
228
+ console.log(check.grounded); // false
229
+ console.log(check.unsupported.length); // 1
230
+ ```
231
+
232
+ ### Test your RAG code offline
233
+
234
+ `@devilsdev/rag-pipeline-utils/testing` has a deterministic embedder, an LLM that echoes the top passage and records its calls, and fixture documents, so tests need no network or API keys:
235
+
236
+ ```js
237
+ import { createTestPipeline } from "@devilsdev/rag-pipeline-utils/testing";
238
+
239
+ const { pipeline, llm } = await createTestPipeline();
240
+ const result = await pipeline.run({
241
+ query: "How many vacation days do I get?",
242
+ });
243
+
244
+ console.log(result.results[0].id); // "vacation"
245
+ console.log(llm.calls.length); // 1
246
+ ```
247
+
201
248
  ### Protect an internal assistant
202
249
 
203
250
  `GuardrailsPipeline` wraps any pipeline. Access control runs before the LLM sees a document, prompt-injection detection runs on the query, and PII is redacted from the answer, its citations and its evaluation details.
@@ -354,6 +401,30 @@ const result = await pipeline.run({
354
401
  if (!result.success) console.error(result.error); // "Execution timeout" or "Execution aborted"
355
402
  ```
356
403
 
404
+ ### Cache repeated questions
405
+
406
+ `cache: true` caches query embeddings, retrieval results and answers in memory, so a repeated question makes no model calls. Use `RedisCache` to share the cache between processes. Cached results are not reused when the index, embedder, model or its settings change, and access-control filtering still runs on every request:
407
+
408
+ ```js
409
+ import { createRagPipeline } from "@devilsdev/rag-pipeline-utils";
410
+ import {
411
+ createTestPipeline,
412
+ EchoLLM,
413
+ } from "@devilsdev/rag-pipeline-utils/testing";
414
+
415
+ const { embedder, retriever } = await createTestPipeline();
416
+ const llm = new EchoLLM();
417
+ const pipeline = createRagPipeline({ embedder, retriever, llm, cache: true });
418
+
419
+ await pipeline.run({ query: "How many vacation days do I get?" });
420
+ const again = await pipeline.run({ query: "How many vacation days do I get?" });
421
+
422
+ console.log(again.cache.generation); // "hit"
423
+ console.log(llm.calls.length); // 1
424
+ ```
425
+
426
+ Answers are cached only at temperature 0. See [Caching](https://devilsdev.github.io/rag-pipeline-utils/docs/Caching).
427
+
357
428
  ### Run fully local
358
429
 
359
430
  Pair the `LocalEmbedder` or Ollama embeddings with an Ollama model and `FileVectorStore` for a private, offline setup. The CLI's `local` and `ollama` templates set this up for you:
@@ -391,19 +462,22 @@ The result of `run()` is:
391
462
 
392
463
  ## Capabilities
393
464
 
394
- | Area | What you get |
395
- | -------------- | ---------------------------------------------------------------------------------------------------------- |
396
- | **Chunking** | `ChunkingEngine` with sentence, fixed-size, recursive, semantic and structure-aware strategies |
397
- | **Retrieval** | `MemoryRetriever`, persistent `FileVectorStore`, `BM25Search`, `HybridRetriever` (Reciprocal Rank Fusion) |
398
- | **Reranking** | `ScoringReranker`, `EmbeddingReranker` (cached), `CascadeReranker` |
399
- | **Citations** | Per-sentence source mapping, hallucination report, numeric-consistency check |
400
- | **Evaluation** | Faithfulness, relevance, context precision, context recall (with a reference), groundedness, BLEU/ROUGE |
401
- | **Guardrails** | Injection detection with input normalisation, ACL and relevance filtering before generation, PII redaction |
402
- | **Agentic** | `QueryPlanner`, `IterativeRetriever`, `SelfCritiqueChecker`, `AgenticPipeline` |
403
- | **GraphRAG** | `KnowledgeGraph`, `EntityExtractor`, `GraphRetriever` |
404
- | **Streaming** | Token streaming with a final chunk carrying citations and evaluation; `SSEAdapter`, `WebSocketAdapter` |
405
- | **Cost** | `CostTracker`, `TokenBudget`, `CostCalculator` with sourced, overridable pricing |
406
- | **Operations** | `DevServer` HTTP API, `ExecutionTracer`, `AuditLogger`, MCP tool server (`MCPServer`) |
465
+ | Area | What you get |
466
+ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
467
+ | **Chunking** | `ChunkingEngine` with sentence, fixed-size, recursive, semantic and structure-aware strategies |
468
+ | **Retrieval** | `MemoryRetriever`, persistent `FileVectorStore`, `BM25Search`, `HybridRetriever` (Reciprocal Rank Fusion) |
469
+ | **Reranking** | `ScoringReranker`, `EmbeddingReranker` (cached), `CascadeReranker` |
470
+ | **Citations** | Per-sentence source mapping, hallucination report, numeric-consistency check |
471
+ | **Evaluation** | Faithfulness, relevance, context precision, context recall (with a reference), groundedness, BLEU/ROUGE, semantic similarity with any embedder |
472
+ | **Integrations** | `checkAnswer` for answers from LangChain, LlamaIndex, Mastra or the AI SDK; `createAiSdkAdapter` |
473
+ | **Caching** | Opt-in caches for query embeddings, retrieval and answers, in memory (`MemoryCache`) or Redis (`RedisCache`) |
474
+ | **Testing** | `/testing` entry: offline `HashEmbedder`, `EchoLLM`, fixtures, `createTestPipeline()`; `validatePlugin` for plugin tests |
475
+ | **Guardrails** | Injection detection with input normalisation, ACL and relevance filtering before generation, PII redaction |
476
+ | **Agentic** | `QueryPlanner`, `IterativeRetriever`, `SelfCritiqueChecker`, `AgenticPipeline` |
477
+ | **GraphRAG** | `KnowledgeGraph`, `EntityExtractor`, `GraphRetriever` |
478
+ | **Streaming** | Token streaming with a final chunk carrying citations and evaluation; `SSEAdapter`, `WebSocketAdapter` |
479
+ | **Cost** | `CostTracker`, `TokenBudget`, `CostCalculator` with sourced, overridable pricing |
480
+ | **Operations** | `DevServer` HTTP API, `ExecutionTracer`, `AuditLogger`, MCP tool server (`MCPServer`) |
407
481
 
408
482
  ## How it compares
409
483
 
@@ -422,17 +496,18 @@ A short summary of the [comparison page](https://devilsdev.github.io/rag-pipelin
422
496
  | Stability | Documented [SEMVER policy](SEMVER.md) with deprecations | Versioned per package | Versioned |
423
497
 
424
498
  Choose LangChain.js for the widest integration catalogue or work that goes well beyond RAG, and LlamaIndex.TS for rich index types and structured data sources. Choose this library when evaluation, citations and guardrails are requirements and you want a small surface to review.
425
- 3
426
499
 
427
500
  ## Connectors and plugins
428
501
 
429
- | Connector | Embeddings | Generation | Notes |
430
- | -------------------- | :--------: | :--------: | ------------------------------------------ |
431
- | `OpenAIConnector` | ✓ | ✓ | `OPENAI_API_KEY` |
432
- | `AnthropicConnector` | | ✓ | `ANTHROPIC_API_KEY` |
433
- | `CohereConnector` | ✓ | | Embeddings and reranking, `COHERE_API_KEY` |
434
- | `OllamaConnector` | ✓ | ✓ | Local models, no key |
435
- | `LocalEmbedder` | ✓ | | Offline TF-IDF, fitted to your corpus |
502
+ | Connector | Embeddings | Generation | Notes |
503
+ | -------------------- | :--------: | :--------: | ---------------------------------------------------------------------------------------- |
504
+ | `OpenAIConnector` | ✓ | ✓ | `OPENAI_API_KEY`; `baseURL` for OpenAI-compatible APIs (Groq, Together, vLLM, LM Studio) |
505
+ | `AnthropicConnector` | | ✓ | `ANTHROPIC_API_KEY` |
506
+ | `CohereConnector` | ✓ | | Embeddings and reranking, `COHERE_API_KEY` |
507
+ | `OllamaConnector` | ✓ | ✓ | Local models, no key |
508
+ | `LocalEmbedder` | ✓ | | Offline TF-IDF, fitted to your corpus |
509
+
510
+ Vercel AI SDK models (any provider it supports) work as the embedder and LLM through `createAiSdkAdapter`; see [Use with other frameworks](https://devilsdev.github.io/rag-pipeline-utils/docs/Integrations).
436
511
 
437
512
  Connectors read API keys when they are created, retry only transient failures (network errors, 429, 5xx) with backoff, and send retrieved documents to the model as clearly delimited, untrusted reference data rather than as instructions.
438
513
 
@@ -451,7 +526,7 @@ Simulated or incomplete modules live under a separate entry point and are not co
451
526
  import { TenantManager } from "@devilsdev/rag-pipeline-utils/experimental";
452
527
  ```
453
528
 
454
- They are still exported from the main entry in 2.5 with a one-time deprecation warning, and will be removed from it in 3.0. Do not use them for authentication, tenant isolation or compliance. The [Experimental modules](https://devilsdev.github.io/rag-pipeline-utils/docs/Experimental) page describes what each one really does.
529
+ They are still exported from the main entry in 2.x with a one-time deprecation warning, and will be removed from it in 3.0. Do not use them for authentication, tenant isolation or compliance. The [Experimental modules](https://devilsdev.github.io/rag-pipeline-utils/docs/Experimental) page describes what each one really does.
455
530
 
456
531
  ## Compatibility
457
532
 
@@ -469,7 +544,7 @@ They are still exported from the main entry in 2.5 with a one-time deprecation w
469
544
  - [CLI reference](https://devilsdev.github.io/rag-pipeline-utils/docs/CLI)
470
545
  - [API reference](https://devilsdev.github.io/rag-pipeline-utils/docs/API-Reference)
471
546
  - [Evaluation guide](https://devilsdev.github.io/rag-pipeline-utils/docs/Evaluation)
472
- - [Examples](examples/): basic pipeline, OpenAI with Pinecone, and a deployable Fastify service
547
+ - [Examples](examples/): basic pipeline, OpenAI with Pinecone, and a deployable Fastify service ([run the basic pipeline in your browser](https://stackblitz.com/github/DevilsDev/rag-pipeline-utils/tree/main/examples/basic-pipeline))
473
548
  - [Changelog](CHANGELOG.md) and [benchmarks methodology](BENCHMARKS.md)
474
549
 
475
550
  ## Security