@zukhruf/retrieval 0.0.0-stage → 0.8.78

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 (83) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +468 -2
  3. package/dist/batch-retriever.d.ts +9 -0
  4. package/dist/batch-retriever.d.ts.map +1 -0
  5. package/dist/batch-retriever.js +2 -0
  6. package/dist/batch-retriever.js.map +1 -0
  7. package/dist/filter.d.ts +13 -0
  8. package/dist/filter.d.ts.map +1 -0
  9. package/dist/filter.js +2 -0
  10. package/dist/filter.js.map +1 -0
  11. package/dist/fusion.d.ts +7 -0
  12. package/dist/fusion.d.ts.map +1 -0
  13. package/dist/fusion.js +2 -0
  14. package/dist/fusion.js.map +1 -0
  15. package/dist/index.d.ts +12 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +3 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/model-identity.d.ts +26 -0
  20. package/dist/model-identity.d.ts.map +1 -0
  21. package/dist/model-identity.js +31 -0
  22. package/dist/model-identity.js.map +1 -0
  23. package/dist/model-mismatch-error.d.ts +15 -0
  24. package/dist/model-mismatch-error.d.ts.map +1 -0
  25. package/dist/model-mismatch-error.js +18 -0
  26. package/dist/model-mismatch-error.js.map +1 -0
  27. package/dist/passage-store.d.ts +12 -0
  28. package/dist/passage-store.d.ts.map +1 -0
  29. package/dist/passage-store.js +2 -0
  30. package/dist/passage-store.js.map +1 -0
  31. package/dist/passage.d.ts +13 -0
  32. package/dist/passage.d.ts.map +1 -0
  33. package/dist/passage.js +2 -0
  34. package/dist/passage.js.map +1 -0
  35. package/dist/postprocessor.d.ts +11 -0
  36. package/dist/postprocessor.d.ts.map +1 -0
  37. package/dist/postprocessor.js +2 -0
  38. package/dist/postprocessor.js.map +1 -0
  39. package/dist/retrieve-options.d.ts +10 -0
  40. package/dist/retrieve-options.d.ts.map +1 -0
  41. package/dist/retrieve-options.js +2 -0
  42. package/dist/retrieve-options.js.map +1 -0
  43. package/dist/retriever.d.ts +10 -0
  44. package/dist/retriever.d.ts.map +1 -0
  45. package/dist/retriever.js +2 -0
  46. package/dist/retriever.js.map +1 -0
  47. package/dist/scored-passage.d.ts +9 -0
  48. package/dist/scored-passage.d.ts.map +1 -0
  49. package/dist/scored-passage.js +2 -0
  50. package/dist/scored-passage.js.map +1 -0
  51. package/dist/sqlite/identifier.d.ts +3 -0
  52. package/dist/sqlite/identifier.d.ts.map +1 -0
  53. package/dist/sqlite/identifier.js +3 -0
  54. package/dist/sqlite/identifier.js.map +1 -0
  55. package/dist/sqlite/passage-rows.d.ts +13 -0
  56. package/dist/sqlite/passage-rows.d.ts.map +1 -0
  57. package/dist/sqlite/passage-rows.js +44 -0
  58. package/dist/sqlite/passage-rows.js.map +1 -0
  59. package/dist/sqlite/sqlite-bm25-retriever.d.ts +21 -0
  60. package/dist/sqlite/sqlite-bm25-retriever.d.ts.map +1 -0
  61. package/dist/sqlite/sqlite-bm25-retriever.js +48 -0
  62. package/dist/sqlite/sqlite-bm25-retriever.js.map +1 -0
  63. package/dist/sqlite/sqlite-embedding-retriever.d.ts +23 -0
  64. package/dist/sqlite/sqlite-embedding-retriever.d.ts.map +1 -0
  65. package/dist/sqlite/sqlite-embedding-retriever.js +125 -0
  66. package/dist/sqlite/sqlite-embedding-retriever.js.map +1 -0
  67. package/dist/sqlite/sqlite-passage-store.d.ts +23 -0
  68. package/dist/sqlite/sqlite-passage-store.d.ts.map +1 -0
  69. package/dist/sqlite/sqlite-passage-store.js +32 -0
  70. package/dist/sqlite/sqlite-passage-store.js.map +1 -0
  71. package/dist/sqlite/where.d.ts +13 -0
  72. package/dist/sqlite/where.d.ts.map +1 -0
  73. package/dist/sqlite/where.js +62 -0
  74. package/dist/sqlite/where.js.map +1 -0
  75. package/dist/sqlite.d.ts +4 -0
  76. package/dist/sqlite.d.ts.map +1 -0
  77. package/dist/sqlite.js +4 -0
  78. package/dist/sqlite.js.map +1 -0
  79. package/dist/vector-missing-error.d.ts +10 -0
  80. package/dist/vector-missing-error.d.ts.map +1 -0
  81. package/dist/vector-missing-error.js +13 -0
  82. package/dist/vector-missing-error.js.map +1 -0
  83. package/package.json +58 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ezzabuzaid
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,469 @@
1
- # Temporary Holding Version
1
+ # @zukhruf/retrieval
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Design on paper, for review: no code exists yet. Ezz approved the API on 2026-11-23 ("Approve, write the paper"). He ruled on each ADR the same day; all are accepted (backlog #5399). Each example below shows the planned API.
4
+
5
+ This package is the query side of retrieval-augmented generation (RAG). A query goes in. The best passages come out, best first, each with a score that is higher for a better passage. The package never cuts or embeds documents: elt writes the passages, their vectors with the model identity, and a keyword index ([ADR 0001](./docs/adr/0001-the-package-is-the-query-side-of-rag-and-reads-a-passage-contract-that-elt-writes.md)).
6
+
7
+ The port of the package is `Retriever`. The engine retrievers read that passage contract with the SQL of SQLite, Postgres or SQL Server. A host can implement `Retriever` over any other source, such as a web search. Composite retrievers fuse retrievers or rewrite the query, and postprocessors rerank, cut, diversify, group, reorder and widen the result.
8
+
9
+ The words in these documents have one meaning each. See the glossary in [CONTEXT.md](./CONTEXT.md).
10
+
11
+ ## Use it
12
+
13
+ ```sh
14
+ npm install @zukhruf/retrieval @zukhruf/vectors ai @ai-sdk/openai
15
+ ```
16
+
17
+ ```ts
18
+ // Planned API.
19
+ import { DatabaseSync } from 'node:sqlite';
20
+
21
+ import { openai } from '@ai-sdk/openai';
22
+
23
+ import { SqliteEmbeddingRetriever } from '@zukhruf/retrieval/sqlite';
24
+ import { install } from '@zukhruf/vectors/sqlite';
25
+
26
+ const database = new DatabaseSync('knowledge.db'); // elt wrote the passage contract here
27
+ install(database); // or load sqlite-vec: the SQL is the same
28
+
29
+ const retriever = new SqliteEmbeddingRetriever({
30
+ database,
31
+ passages: 'docs_passages',
32
+ vectors: 'docs_passage_vectors',
33
+ model: openai.embedding('text-embedding-3-small'),
34
+ });
35
+
36
+ const results = await retriever.retrieve('how do I rotate a key?');
37
+ // 10 scored passages, best first: { passage: { id, text, source, seq, start, end, metadata }, score }
38
+ ```
39
+
40
+ ## Search passages by meaning
41
+
42
+ An embedding retriever embeds the query with its AI SDK model and sends one SQL query to the engine. The engine ranks the passages by cosine similarity: `vec_distance_cosine` on SQLite, pgvector's `<=>` on Postgres, `VECTOR_DISTANCE` or elt's `marts.<name>_nearest` on SQL Server ([ADR 0003](./docs/adr/0003-an-embedding-retriever-runs-the-vector-search-in-the-sql-of-its-engine-one-query-or-a-batch.md)). The score is `1 - cosine distance`.
43
+
44
+ ```ts
45
+ // Planned API.
46
+ import { PgvectorEmbeddingRetriever } from '@zukhruf/retrieval/postgres';
47
+
48
+ const retriever = new PgvectorEmbeddingRetriever({
49
+ session: {
50
+ query: (sql, parameters) => pool.query(sql, parameters).then((r) => r.rows),
51
+ },
52
+ passages: 'docs_passages',
53
+ vectors: 'docs_passage_vectors',
54
+ model,
55
+ });
56
+
57
+ const results = await retriever.retrieve('rotate a key', {
58
+ topK: 5,
59
+ abortSignal,
60
+ });
61
+ ```
62
+
63
+ The retriever reads the model identity of the stored vectors first. When its query model has another provider or model id, the call fails with `ModelMismatchError` and sends no model call and no search. When the query vector has other dimensions than the stored vectors, the call fails with `DimensionMismatchError` of `@zukhruf/vectors` after the model call and sends no search ([ADR 0010](./docs/adr/0010-an-embedding-retriever-refuses-a-query-model-whose-identity-differs-from-the-stored-vectors.md)).
64
+
65
+ ## Search by keywords
66
+
67
+ A keyword retriever queries the keyword index that elt writes: FTS5 on SQLite, `tsvector` on Postgres, full-text on SQL Server. It quotes each word of the query, so a word of the user is never an operator of the engine. Its score is higher for a better match on every engine; `SqliteBM25Retriever` negates `bm25()` ([ADR 0004](./docs/adr/0004-a-keyword-retriever-queries-the-keyword-index-that-elt-writes.md)).
68
+
69
+ ```ts
70
+ // Planned API.
71
+ import { SqliteBM25Retriever } from '@zukhruf/retrieval/sqlite';
72
+
73
+ const keywords = new SqliteBM25Retriever({
74
+ database,
75
+ passages: 'docs_passages',
76
+ index: 'docs_passages_fts',
77
+ operator: 'OR', // the default is 'AND', the implicit operator of FTS5
78
+ });
79
+
80
+ const results = await keywords.retrieve('rotate signing key');
81
+ ```
82
+
83
+ ## Combine searches
84
+
85
+ `FusionRetriever` asks each retriever for `rankWindowSize` passages, fuses the lists on `Passage.id` and gives the best `topK`. The default fusion is reciprocal rank fusion with k 60 and ranks from 1; each retriever has a weight of 1 ([ADR 0007](./docs/adr/0007-reciprocal-rank-fusion-is-the-default-fusion-with-k-60-and-ranks-from-1.md)).
86
+
87
+ ```ts
88
+ // Planned API.
89
+ import {
90
+ FusionRetriever,
91
+ MultiQueryRetriever,
92
+ relativeScoreFusion,
93
+ } from '@zukhruf/retrieval';
94
+
95
+ const hybrid = new FusionRetriever({
96
+ retrievers: [meaning, keywords],
97
+ rankWindowSize: 50,
98
+ });
99
+
100
+ const minMax = new FusionRetriever({
101
+ retrievers: [meaning, keywords],
102
+ fusion: relativeScoreFusion(),
103
+ weights: [0.75, 0.25],
104
+ });
105
+
106
+ // The language model writes 4 versions of the query; reciprocalRankFusion() fuses their lists, as in FusionRetriever.
107
+ const expanded = new MultiQueryRetriever({
108
+ retriever: hybrid,
109
+ model: languageModel,
110
+ });
111
+ ```
112
+
113
+ `HydeRetriever { retriever, model }` asks the language model for an answer and searches with that answer as the query.
114
+
115
+ ## Rerank and post-process the results
116
+
117
+ `PostprocessingRetriever` runs a list of postprocessors, in order, on the result of its retriever ([ADR 0008](./docs/adr/0008-a-search-is-composed-of-retrievers-that-wrap-retrievers-and-a-list-of-postprocessors.md)).
118
+
119
+ ```ts
120
+ // Planned API.
121
+ import {
122
+ Collapse,
123
+ ContextWindow,
124
+ LongContextReorder,
125
+ MaximalMarginalRelevance,
126
+ PostprocessingRetriever,
127
+ Rerank,
128
+ SimilarityCutoff,
129
+ } from '@zukhruf/retrieval';
130
+ import { SqlitePassageStore } from '@zukhruf/retrieval/sqlite';
131
+
132
+ const search = new PostprocessingRetriever({
133
+ retriever: hybrid,
134
+ postprocessors: [
135
+ new Rerank({ model: rerankingModel, topN: 20 }), // AI SDK rerank
136
+ new SimilarityCutoff({ threshold: 0.3 }),
137
+ new MaximalMarginalRelevance({ lambda: 0.5, topK: 8 }), // lambda 1 = relevance only
138
+ new Collapse({ field: 'source', size: 1 }), // one passage per source
139
+ new ContextWindow({
140
+ store: new SqlitePassageStore({ database, passages: 'docs_passages' }),
141
+ windowSize: 3,
142
+ }),
143
+ new LongContextReorder(),
144
+ ],
145
+ });
146
+
147
+ const results = await search.retrieve('rotate a key', {
148
+ topK: 50,
149
+ includeVectors: true,
150
+ });
151
+ ```
152
+
153
+ `MaximalMarginalRelevance` compares the vectors of the passages, so its retriever runs with `includeVectors: true`.
154
+
155
+ ## Search many queries at once
156
+
157
+ Batch search is part of vector search. Each embedding retriever has `retrieveMany` beside `retrieve`. It embeds the queries in one model call and runs one SQL query: `CROSS JOIN LATERAL` on Postgres. The SQL Server form, `CROSS APPLY` over `VECTOR_SEARCH`, is to be probed, and the SQLite form waits on a cost probe (#5422) ([ADR 0003](./docs/adr/0003-an-embedding-retriever-runs-the-vector-search-in-the-sql-of-its-engine-one-query-or-a-batch.md)).
158
+
159
+ ```ts
160
+ // Planned API.
161
+ const lists = await retriever.retrieveMany(['rotate a key', 'revoke a token'], {
162
+ topK: 5,
163
+ });
164
+ // lists[0] is the result of 'rotate a key', lists[1] of 'revoke a token'
165
+ ```
166
+
167
+ ## Filter by metadata
168
+
169
+ A filter has Haystack's shape: AND, OR and NOT over `== != > >= < <= in "not in"` ([ADR 0009](./docs/adr/0009-a-filter-has-the-shape-of-haystacks-filters.md)). A field is a passage field (`source`, `seq`, `start`, `end`) or a metadata column, `metadata.<column>`. An engine retriever runs the filter as SQL `WHERE` in the same query.
170
+
171
+ ```ts
172
+ // Planned API.
173
+ const results = await retriever.retrieve('rotate a key', {
174
+ filter: {
175
+ operator: 'AND',
176
+ conditions: [
177
+ { field: 'metadata.product', operator: '==', value: 'vault' },
178
+ { field: 'metadata.year', operator: '>=', value: 2025 },
179
+ ],
180
+ },
181
+ });
182
+ ```
183
+
184
+ On Postgres, pgvector filters after the approximate index scan, so a filtered call can give fewer than `topK` passages ([pgvector README](https://github.com/pgvector/pgvector/blob/master/README.md)).
185
+
186
+ ## Errors
187
+
188
+ | Error | When |
189
+ | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
190
+ | `ModelMismatchError` | The query model of an embedding retriever has another provider or model id than the stored vectors, before the model call |
191
+ | `DimensionMismatchError` (`@zukhruf/vectors`) | The query vector has other dimensions than the stored vectors, after the model call. `expected` and `actual` |
192
+ | `VectorMissingError` | `MaximalMarginalRelevance` gets a passage without a vector: the call did not ask for vectors |
193
+
194
+ An error of the model, of the engine or of the reranking model reaches the caller as it is. An aborted call rejects with the reason of its `abortSignal`.
195
+
196
+ ## What the package does not do
197
+
198
+ - **It does not cut or embed documents.** elt loads, cuts and embeds them, and writes the passage contract (elt #5401). Cutting text moves to its own zukhruf package (#5414) ([ADR 0001](./docs/adr/0001-the-package-is-the-query-side-of-rag-and-reads-a-passage-contract-that-elt-writes.md)).
199
+ - **It does not ship adapters for live sources.** A web search or the API of a product is an adapter of the host that implements `Retriever` ([ADR 0002](./docs/adr/0002-a-retriever-is-a-port-for-any-source.md)).
200
+ - **It does not make agent tools.** An AI SDK tool over a retriever is the consumer's code.
201
+ - **It does not write the keyword index or the vector index.** elt writes both; this package only queries them ([ADR 0004](./docs/adr/0004-a-keyword-retriever-queries-the-keyword-index-that-elt-writes.md)).
202
+
203
+ ## Who uses it
204
+
205
+ No consumer uses it yet. These moves are forced onto it after it ships.
206
+
207
+ | Consumer | How | Record |
208
+ | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ |
209
+ | deepagents | `@deepagents/retrieval` goes; toolbox `search_content_tool` and the orchestrator move to this package and elt | #5406 |
210
+ | deepagents | `ContextStore.searchMessages` (FTS5, `ts_rank`, `CONTAINSTABLE`) moves to the keyword retrievers, with one score direction | #5417, #4884 |
211
+ | April | the TB2 explorer moves to an elt push source, the Vectorizer and `SqliteEmbeddingRetriever`; its hand collapse of passages to documents becomes `Collapse` | #5407 |
212
+ | text2sql | the two `toFtsQuery` copies move to the keyword retrievers | #5410 |
213
+ | datahub | the planned third FTS5 BM25 place uses the keyword retrievers; its staff search fusion uses the fusions | #3451, #3426 |
214
+ | Meddit | its evidence layer moves onto the package after it ships | #5378 |
215
+ | `@zukhruf/mteb` | keeps its MTEB port of `HybridSearch`; it does not move | #5400 |
216
+
217
+ ## The same concepts in other systems
218
+
219
+ | Concept | Other systems |
220
+ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
221
+ | `Passage` | LlamaIndex `TextNode` ([schema.py](https://raw.githubusercontent.com/run-llama/llama_index/main/llama-index-core/llama_index/core/schema.py)); LangChain `Document` ([document.ts](https://raw.githubusercontent.com/langchain-ai/langchainjs/main/libs/langchain-core/src/documents/document.ts)); Haystack `Document` ([document.py](https://raw.githubusercontent.com/deepset-ai/haystack/main/haystack/dataclasses/document.py)) |
222
+ | `ScoredPassage` | LlamaIndex `NodeWithScore`; .NET `VectorSearchResult<TRecord>{Record, Score}` ([vector search](https://learn.microsoft.com/en-us/dotnet/ai/vector-stores/vector-search)) |
223
+ | `Retriever.retrieve` | LlamaIndex `BaseRetriever.retrieve` ([base_retriever.py](https://raw.githubusercontent.com/run-llama/llama_index/main/llama-index-core/llama_index/core/base/base_retriever.py)); LangChain `BaseRetriever` ([retrievers/index.ts](https://raw.githubusercontent.com/langchain-ai/langchainjs/main/libs/langchain-core/src/retrievers/index.ts)); Semantic Kernel `ITextSearch` ([text search](https://learn.microsoft.com/en-us/semantic-kernel/concepts/text-search/text-search-abstractions)) |
224
+ | engine retrievers | Haystack's retrievers for each document store ([retrievers](https://docs.haystack.deepset.ai/docs/retrievers)) |
225
+ | `topK`, `includeVectors` | Haystack `top_k` = 10 ([document_store.py](https://raw.githubusercontent.com/deepset-ai/haystack/main/haystack/document_stores/in_memory/document_store.py)), `return_embedding`; Mastra `topK` = 10 ([pg](https://mastra.ai/reference/vectors/pg)); .NET `IncludeVectors` ([VectorSearchOptions](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.vectordata.vectorsearchoptions-1)) |
226
+ | `Filter` | Haystack filters ([metadata filtering](https://docs.haystack.deepset.ai/docs/metadata-filtering)); LlamaIndex `MetadataFilters` ([types.py](https://raw.githubusercontent.com/run-llama/llama_index/main/llama-index-core/llama_index/core/vector_stores/types.py)); Qdrant `filter` ([search](https://qdrant.tech/documentation/search/search/)) |
227
+ | `FusionRetriever` | LlamaIndex `QueryFusionRetriever` ([fusion_retriever.py](https://raw.githubusercontent.com/run-llama/llama_index/main/llama-index-core/llama_index/core/retrievers/fusion_retriever.py)); LangChain `EnsembleRetriever` ([ensemble.ts](https://raw.githubusercontent.com/langchain-ai/langchainjs/main/libs/langchain-classic/src/retrievers/ensemble.ts)); Elasticsearch `rrf` ([rrf retriever](https://www.elastic.co/docs/reference/elasticsearch/rest-apis/retrievers/rrf-retriever)); Qdrant `prefetch` ([hybrid queries](https://qdrant.tech/documentation/concepts/hybrid-queries/)) |
228
+ | score fusions | Weaviate `relativeScoreFusion` ([hybrid](https://docs.weaviate.io/weaviate/search/hybrid)); OpenSearch `min_max` ([normalization processor](https://docs.opensearch.org/latest/search-plugins/search-pipelines/normalization-processor/)); Haystack `distribution_based_rank_fusion` ([document_joiner.py](https://raw.githubusercontent.com/deepset-ai/haystack/main/haystack/components/joiners/document_joiner.py)); Qdrant `dbsf` |
229
+ | `MultiQueryRetriever`, HyDE | LangChain `MultiQueryRetriever` ([multi_query.ts](https://raw.githubusercontent.com/langchain-ai/langchainjs/main/libs/langchain-classic/src/retrievers/multi_query.ts)), `HydeRetriever` ([HyDE](https://docs.langchain.com/oss/javascript/integrations/retrievers/hyde)) |
230
+ | `PostprocessingRetriever` | LangChain `ContextualCompressionRetriever` ([contextual_compression.ts](https://raw.githubusercontent.com/langchain-ai/langchainjs/main/libs/langchain-classic/src/retrievers/contextual_compression.ts)); LlamaIndex `node_postprocessors` ([types.py](https://raw.githubusercontent.com/run-llama/llama_index/main/llama-index-core/llama_index/core/postprocessor/types.py)) |
231
+ | `MaximalMarginalRelevance` | Elasticsearch `diversify` `lambda` ([diversify retriever](https://www.elastic.co/docs/reference/elasticsearch/rest-apis/retrievers/diversify-retriever)); Weaviate `balance` ([1.39](https://weaviate.io/blog/weaviate-1-39-release)); Qdrant `mmr` `diversity`, 1 = diverse ([search relevance](https://qdrant.tech/documentation/search/search-relevance/)) |
232
+ | `Collapse` | Elasticsearch `collapse` ([standard retriever](https://www.elastic.co/docs/reference/elasticsearch/rest-apis/retrievers/standard-retriever)); Vespa `collapsesize` ([query API](https://docs.vespa.ai/en/reference/api/query.html)); Qdrant `query_points_groups` ([search](https://qdrant.tech/documentation/search/search/)) |
233
+ | `ContextWindow` | Haystack `SentenceWindowRetriever` ([sentence_window_retriever.py](https://raw.githubusercontent.com/deepset-ai/haystack/main/haystack/components/retrievers/sentence_window_retriever.py)); LlamaIndex `PrevNextNodePostprocessor` |
234
+ | `LongContextReorder` | LangChain `LongContextReorder` ([reference](https://reference.langchain.com/python/langchain-community/document_transformers/long_context_reorder/LongContextReorder)); Haystack `LostInTheMiddleRanker` ([rankers](https://docs.haystack.deepset.ai/docs/rankers)) |
235
+ | hybrid search in SQL | Alex Garcia's sqlite-vec recipe, RRF k 60 in SQL ([hybrid search](https://alexgarcia.xyz/blog/2024/sqlite-vec-hybrid-search/index.html)) |
236
+ | passage contract | pgai `create_vectorizer` ([API reference](https://raw.githubusercontent.com/timescale/pgai/main/docs/vectorizer/api-reference.md)); Airbyte pgvector ([destination](https://docs.airbyte.com/integrations/destinations/pgvector)) |
237
+
238
+ ## Why not an npm package
239
+
240
+ Checked on 2026-11-23 with `npm pack` of each candidate and no install. The requirements: **R1** takes AI SDK 7 models; **R2** reads tables that exist, on SQLite, Postgres and SQL Server; **R3** has the features (fusion, rerank, MMR, grouping); **R4** takes an `AbortSignal`. No candidate passes all four. R2 decides: every store creates its own tables, and none searches vectors in SQL Server. Node 26.13.0 has no built-in module for retrieval, reranking, BM25 or fusion.
241
+
242
+ | Package | R1 | R2 | R3 | R4 |
243
+ | -------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | --------------------------------- |
244
+ | `llamaindex` 0.12.1 | fails: only `@llamaindex/vercel`, peer `ai` ^5 | fails: `@llamaindex/postgres` creates fixed columns; no `node:sqlite` or SQL Server store | in part: HYBRID and MMR modes, a cutoff, a reranker; no RRF | fails: `retrieve` takes no signal |
245
+ | `@langchain/core`, `/classic` | fails: no `ai` import | in part: `PGVectorStore` maps a table, with metadata in one JSONB column; no SQL Server store | in part: RRF `c` 60, multi-query, HyDE, compression, MMR; no score fusion or collapse | passes: `RunnableConfig.signal` |
246
+ | `@mastra/rag` 2.8.1 | in part: own model types; `rerank` is not AI SDK `RerankingModel` | fails: `@mastra/pg` and `@mastra/libsql` create their tables; `@mastra/mssql` has no vector API | fails: no RRF or MMR | fails: no `AbortSignal` |
247
+ | `@orama/orama` 3.1.18 | fails: own embedding plugins | fails: an in-memory index of its own, no SQL | in part: a hybrid mode | fails: no `AbortSignal` |
248
+ | `@convex-dev/rag` 0.7.9 | passes: peer `ai` ^7 | fails: it chunks and embeds into Convex storage | in part: RRF, filters, neighbour chunks; no rerank or MMR | fails: no `AbortSignal` |
249
+ | `@reaatech/hybrid-rag-retrieval` 0.1.1 | fails: depends on `openai`, no `ai` import | fails: depends on Qdrant | in part: RRF, own BM25, a reranker | fails: no signal |
250
+
251
+ ## API
252
+
253
+ ```ts
254
+ // @zukhruf/retrieval (planned)
255
+ import type { EmbeddingModel, LanguageModel, RerankingModel } from 'ai';
256
+
257
+ type Passage = {
258
+ readonly id: string;
259
+ readonly text: string;
260
+ readonly source: string;
261
+ readonly seq: number;
262
+ readonly start: number;
263
+ readonly end: number;
264
+ readonly metadata: Readonly<Record<string, unknown>>;
265
+ };
266
+ type ScoredPassage = {
267
+ readonly passage: Passage;
268
+ readonly score: number;
269
+ readonly vector?: readonly number[];
270
+ }; // higher is better
271
+
272
+ type Filter =
273
+ | {
274
+ readonly operator: 'AND' | 'OR' | 'NOT';
275
+ readonly conditions: readonly Filter[];
276
+ }
277
+ | {
278
+ readonly field: string; // 'source' | 'seq' | 'start' | 'end' | `metadata.${string}`
279
+ readonly operator:
280
+ '==' | '!=' | '>' | '>=' | '<' | '<=' | 'in' | 'not in';
281
+ readonly value: unknown;
282
+ };
283
+
284
+ type RetrieveOptions = {
285
+ readonly topK?: number; // 10
286
+ readonly filter?: Filter;
287
+ readonly includeVectors?: boolean; // false
288
+ readonly abortSignal?: AbortSignal;
289
+ };
290
+
291
+ interface Retriever {
292
+ retrieve(query: string, options?: RetrieveOptions): Promise<ScoredPassage[]>;
293
+ }
294
+ interface BatchRetriever extends Retriever {
295
+ retrieveMany(
296
+ queries: readonly string[],
297
+ options?: RetrieveOptions,
298
+ ): Promise<ScoredPassage[][]>; // in the order of the queries
299
+ }
300
+
301
+ interface Fusion {
302
+ fuse(
303
+ lists: readonly (readonly ScoredPassage[])[],
304
+ weights: readonly number[],
305
+ ): ScoredPassage[];
306
+ }
307
+ function reciprocalRankFusion(options?: { k?: number }): Fusion; // k 60, ranks from 1
308
+ function relativeScoreFusion(): Fusion; // min-max
309
+ function distributionBasedScoreFusion(): Fusion; // mean ± 3σ
310
+
311
+ class FusionRetriever implements Retriever {
312
+ constructor(options: {
313
+ retrievers: readonly Retriever[];
314
+ fusion?: Fusion; // reciprocalRankFusion({ k: 60 })
315
+ weights?: readonly number[]; // 1 each
316
+ rankWindowSize?: number; // the topK of the call
317
+ });
318
+ }
319
+ class MultiQueryRetriever implements Retriever {
320
+ constructor(options: {
321
+ retriever: Retriever;
322
+ model: LanguageModel;
323
+ queryCount?: number; // 4
324
+ fusion?: Fusion; // reciprocalRankFusion({ k: 60 })
325
+ });
326
+ }
327
+ class HydeRetriever implements Retriever {
328
+ constructor(options: { retriever: Retriever; model: LanguageModel });
329
+ }
330
+
331
+ interface Postprocessor {
332
+ postprocess(
333
+ passages: readonly ScoredPassage[],
334
+ query: string,
335
+ options?: { abortSignal?: AbortSignal },
336
+ ): Promise<ScoredPassage[]>;
337
+ }
338
+ class PostprocessingRetriever implements Retriever {
339
+ constructor(options: {
340
+ retriever: Retriever;
341
+ postprocessors: readonly Postprocessor[];
342
+ });
343
+ }
344
+ class Rerank implements Postprocessor {
345
+ constructor(options: { model: RerankingModel; topN?: number }); // every passage when topN is absent
346
+ }
347
+ class SimilarityCutoff implements Postprocessor {
348
+ constructor(options: { threshold: number }); // keeps score >= threshold
349
+ }
350
+ class MaximalMarginalRelevance implements Postprocessor {
351
+ constructor(options: { lambda?: number; topK: number }); // 0.5; 1 = relevance only
352
+ }
353
+ class Collapse implements Postprocessor {
354
+ constructor(options?: { field?: string; size?: number }); // 'source', 1
355
+ }
356
+ class LongContextReorder implements Postprocessor {}
357
+ class ContextWindow implements Postprocessor {
358
+ constructor(options: { store: PassageStore; windowSize?: number }); // 3
359
+ }
360
+
361
+ interface PassageStore {
362
+ get(ids: readonly string[]): Promise<ReadonlyMap<string, Passage>>;
363
+ neighbours(options: {
364
+ source: string;
365
+ seq: number;
366
+ windowSize: number;
367
+ }): Promise<Passage[]>;
368
+ }
369
+
370
+ class ModelMismatchError extends Error {
371
+ readonly stored: { provider: string; modelId: string };
372
+ readonly query: { provider: string; modelId: string }; // before the model call; other dimensions are DimensionMismatchError of @zukhruf/vectors (ADR 0010)
373
+ }
374
+ class VectorMissingError extends Error {
375
+ readonly passageId: string;
376
+ }
377
+
378
+ // @zukhruf/retrieval/sqlite
379
+ class SqliteEmbeddingRetriever implements BatchRetriever {
380
+ constructor(options: {
381
+ database: DatabaseSync;
382
+ passages: string;
383
+ vectors: string;
384
+ model: EmbeddingModel;
385
+ });
386
+ }
387
+ class SqliteBM25Retriever implements Retriever {
388
+ constructor(options: {
389
+ database: DatabaseSync;
390
+ passages: string;
391
+ index: string;
392
+ operator?: 'AND' | 'OR';
393
+ }); // 'AND'
394
+ }
395
+ class SqlitePassageStore implements PassageStore {
396
+ constructor(options: { database: DatabaseSync; passages: string });
397
+ }
398
+
399
+ // @zukhruf/retrieval/postgres
400
+ type PostgresSession = {
401
+ query(
402
+ sql: string,
403
+ parameters: readonly unknown[],
404
+ ): Promise<readonly Record<string, unknown>[]>;
405
+ };
406
+ class PgvectorEmbeddingRetriever implements BatchRetriever {
407
+ constructor(options: {
408
+ session: PostgresSession;
409
+ passages: string;
410
+ vectors: string;
411
+ model: EmbeddingModel;
412
+ });
413
+ }
414
+ class PgvectorKeywordRetriever implements Retriever {
415
+ constructor(options: {
416
+ session: PostgresSession;
417
+ passages: string;
418
+ index: string;
419
+ operator?: 'AND' | 'OR';
420
+ });
421
+ }
422
+ class PostgresPassageStore implements PassageStore {
423
+ constructor(options: { session: PostgresSession; passages: string });
424
+ }
425
+
426
+ // @zukhruf/retrieval/sqlserver
427
+ type SqlServerSession = {
428
+ query(
429
+ sql: string,
430
+ parameters: Readonly<Record<string, unknown>>,
431
+ ): Promise<readonly Record<string, unknown>[]>;
432
+ };
433
+ class SqlServerEmbeddingRetriever implements BatchRetriever {
434
+ constructor(options: {
435
+ session: SqlServerSession;
436
+ passages: string;
437
+ vectors: string;
438
+ model: EmbeddingModel;
439
+ });
440
+ }
441
+ class SqlServerKeywordRetriever implements Retriever {
442
+ constructor(options: {
443
+ session: SqlServerSession;
444
+ passages: string;
445
+ index: string;
446
+ operator?: 'AND' | 'OR';
447
+ });
448
+ }
449
+ class SqlServerPassageStore implements PassageStore {
450
+ constructor(options: { session: SqlServerSession; passages: string });
451
+ }
452
+ ```
453
+
454
+ ## Documentation
455
+
456
+ **Decisions**
457
+
458
+ - [ADR 0001](./docs/adr/0001-the-package-is-the-query-side-of-rag-and-reads-a-passage-contract-that-elt-writes.md): the package is the query side of RAG and reads a passage contract that elt writes.
459
+ - [ADR 0002](./docs/adr/0002-a-retriever-is-a-port-for-any-source.md): a retriever is a port for any source.
460
+ - [ADR 0003](./docs/adr/0003-an-embedding-retriever-runs-the-vector-search-in-the-sql-of-its-engine-one-query-or-a-batch.md): an embedding retriever runs the vector search in the SQL of its engine, one query or a batch.
461
+ - [ADR 0004](./docs/adr/0004-a-keyword-retriever-queries-the-keyword-index-that-elt-writes.md): a keyword retriever queries the keyword index that elt writes.
462
+ - [ADR 0005](./docs/adr/0005-a-score-is-higher-for-a-better-passage.md): a score is higher for a better passage.
463
+ - [ADR 0006](./docs/adr/0006-a-retriever-gives-10-passages-when-the-caller-gives-no-topk.md): a retriever gives 10 passages when the caller gives no topK.
464
+ - [ADR 0007](./docs/adr/0007-reciprocal-rank-fusion-is-the-default-fusion-with-k-60-and-ranks-from-1.md): reciprocal rank fusion is the default fusion, with k 60 and ranks from 1.
465
+ - [ADR 0008](./docs/adr/0008-a-search-is-composed-of-retrievers-that-wrap-retrievers-and-a-list-of-postprocessors.md): a search is composed of retrievers that wrap retrievers and a list of postprocessors.
466
+ - [ADR 0009](./docs/adr/0009-a-filter-has-the-shape-of-haystacks-filters.md): a filter has the shape of Haystack's filters.
467
+ - [ADR 0010](./docs/adr/0010-an-embedding-retriever-refuses-a-query-model-whose-identity-differs-from-the-stored-vectors.md): an embedding retriever refuses a query model whose identity differs from the stored vectors.
468
+ - [ADR 0011](./docs/adr/0011-the-package-is-in-the-base-layer.md): the package is in the base layer.
469
+ - [ADR 0012](./docs/adr/0012-the-package-is-zukhruf-retrieval-and-its-port-is-retriever-with-retrieve-after-go.md): the package is @zukhruf/retrieval, and its port is Retriever with retrieve, after Go.
@@ -0,0 +1,9 @@
1
+ import type { RetrieveOptions } from './retrieve-options.ts';
2
+ import type { Retriever } from './retriever.ts';
3
+ import type { ScoredPassage } from './scored-passage.ts';
4
+ /** A retriever that also searches many queries in one call (ADR 0003). */
5
+ export interface BatchRetriever extends Retriever {
6
+ /** Gives one result list for each query, in the order of the queries. */
7
+ retrieveMany(queries: readonly string[], options?: RetrieveOptions): Promise<ScoredPassage[][]>;
8
+ }
9
+ //# sourceMappingURL=batch-retriever.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batch-retriever.d.ts","sourceRoot":"","sources":["../src/batch-retriever.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD,0EAA0E;AAC1E,MAAM,WAAW,cAAe,SAAQ,SAAS;IAC/C,yEAAyE;IACzE,YAAY,CACV,OAAO,EAAE,SAAS,MAAM,EAAE,EAC1B,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC;CAC/B"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=batch-retriever.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batch-retriever.js","sourceRoot":"","sources":["../src/batch-retriever.ts"],"names":[],"mappings":""}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * A condition on passage fields and metadata columns, in the shape of
3
+ * Haystack's filters (ADR 0009). An engine retriever runs it as SQL `WHERE`.
4
+ */
5
+ export type Filter = {
6
+ readonly operator: 'AND' | 'OR' | 'NOT';
7
+ readonly conditions: readonly Filter[];
8
+ } | {
9
+ readonly field: 'source' | 'seq' | 'start' | 'end' | `metadata.${string}`;
10
+ readonly operator: '==' | '!=' | '>' | '>=' | '<' | '<=' | 'in' | 'not in';
11
+ readonly value: unknown;
12
+ };
13
+ //# sourceMappingURL=filter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"filter.d.ts","sourceRoot":"","sources":["../src/filter.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,MAAM,MAAM,GACd;IACE,QAAQ,CAAC,QAAQ,EAAE,KAAK,GAAG,IAAI,GAAG,KAAK,CAAC;IACxC,QAAQ,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;CACxC,GACD;IACE,QAAQ,CAAC,KAAK,EAAE,QAAQ,GAAG,KAAK,GAAG,OAAO,GAAG,KAAK,GAAG,YAAY,MAAM,EAAE,CAAC;IAC1E,QAAQ,CAAC,QAAQ,EACf,IAAI,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,GAAG,QAAQ,CAAC;IAC1D,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;CACzB,CAAC"}
package/dist/filter.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=filter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"filter.js","sourceRoot":"","sources":["../src/filter.ts"],"names":[],"mappings":""}
@@ -0,0 +1,7 @@
1
+ import type { ScoredPassage } from './scored-passage.ts';
2
+ /** Combines the result lists of several retrievers into one list, on `Passage.id` (ADR 0007). */
3
+ export interface Fusion {
4
+ /** `weights` has one weight for each list, in the order of the lists. */
5
+ fuse(lists: readonly (readonly ScoredPassage[])[], weights: readonly number[]): ScoredPassage[];
6
+ }
7
+ //# sourceMappingURL=fusion.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fusion.d.ts","sourceRoot":"","sources":["../src/fusion.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD,iGAAiG;AACjG,MAAM,WAAW,MAAM;IACrB,yEAAyE;IACzE,IAAI,CACF,KAAK,EAAE,SAAS,CAAC,SAAS,aAAa,EAAE,CAAC,EAAE,EAC5C,OAAO,EAAE,SAAS,MAAM,EAAE,GACzB,aAAa,EAAE,CAAC;CACpB"}
package/dist/fusion.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=fusion.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fusion.js","sourceRoot":"","sources":["../src/fusion.ts"],"names":[],"mappings":""}
@@ -0,0 +1,12 @@
1
+ export type { BatchRetriever } from './batch-retriever.ts';
2
+ export type { Filter } from './filter.ts';
3
+ export type { Fusion } from './fusion.ts';
4
+ export { ModelMismatchError } from './model-mismatch-error.ts';
5
+ export type { PassageStore } from './passage-store.ts';
6
+ export type { Passage } from './passage.ts';
7
+ export type { Postprocessor } from './postprocessor.ts';
8
+ export type { RetrieveOptions } from './retrieve-options.ts';
9
+ export type { Retriever } from './retriever.ts';
10
+ export type { ScoredPassage } from './scored-passage.ts';
11
+ export { VectorMissingError } from './vector-missing-error.ts';
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,YAAY,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAC1C,YAAY,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,YAAY,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,YAAY,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAC5C,YAAY,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,YAAY,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,YAAY,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,YAAY,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { ModelMismatchError } from './model-mismatch-error.js';
2
+ export { VectorMissingError } from './vector-missing-error.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAO/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC"}
@@ -0,0 +1,26 @@
1
+ import type { EmbeddingModel } from 'ai';
2
+ /** The provider, the model id and the dimensions of the model that made a vector (ADR 0010). */
3
+ export type ModelIdentity = {
4
+ readonly provider: string;
5
+ readonly modelId: string;
6
+ readonly dimensions: number;
7
+ };
8
+ /**
9
+ * The provider and the model id of a model, which a retriever compares
10
+ * before the model call. An AI SDK embedding model does not state its
11
+ * dimensions, so only its vector shows them.
12
+ */
13
+ export type ModelName = Pick<ModelIdentity, 'provider' | 'modelId'>;
14
+ /**
15
+ * The form of elt's Embedding rule, `openai/text-embedding-3-small (1536
16
+ * dimensions)`, which the `model` column of the passage vectors holds.
17
+ */
18
+ export declare const describe: ({ provider, modelId, dimensions, }: ModelIdentity) => string;
19
+ /** Reads the identity that the `model` column of the passage vectors holds. */
20
+ export declare function parseModelIdentity(text: string): ModelIdentity;
21
+ /**
22
+ * The provider and the model id of a query model, as elt names them: a
23
+ * string model id is `provider/model`, as the AI SDK gateway reads it.
24
+ */
25
+ export declare function modelName(model: EmbeddingModel): ModelName;
26
+ //# sourceMappingURL=model-identity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model-identity.d.ts","sourceRoot":"","sources":["../src/model-identity.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,IAAI,CAAC;AAEzC,gGAAgG;AAChG,MAAM,MAAM,aAAa,GAAG;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC7B,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,SAAS,GAAG,IAAI,CAAC,aAAa,EAAE,UAAU,GAAG,SAAS,CAAC,CAAC;AAEpE;;;GAGG;AACH,eAAO,MAAM,QAAQ,uCAIlB,aAAa,KAAG,MACkC,CAAC;AAItD,+EAA+E;AAC/E,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,aAAa,CAY9D;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,cAAc,GAAG,SAAS,CAW1D"}