@eltjs/vectorizer 0.0.0-stage → 0.13.7

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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 ezzabuzaid
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,463 @@
1
- # Temporary Holding Version
1
+ # Vectorizer
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
+ `Vectorizer` is one declaration that keeps the passage contract of [`@zukhruf/retrieval`](https://github.com/JanuaryLabs/zukhruf/tree/main/packages/retrieval) in step with what an elt pipeline loads: the passages of each source row with their metadata, the vector of each passage with the identity of its model, and a keyword index. The retrievers of `@zukhruf/retrieval` then search the rows by meaning and by words. pgai's `create_vectorizer` does the same job in Postgres. The words of this package are in its [glossary](./CONTEXT.md).
4
+
5
+ ```sh
6
+ npm install @eltjs/vectorizer @eltjs/elt @eltjs/elt-sqlite @zukhruf/retrieval
7
+ ```
8
+
9
+ `@eltjs/vectorizer/sqlite` writes the contract into a SQLite file. Postgres and SQL Server come later, each in its own subpath.
10
+
11
+ ## Search the rows of a table
12
+
13
+ The program loads three tasks that it holds, through an `IterableSource`, and declares a `Vectorizer` over their table. Then it searches the passages with the retrievers of `@zukhruf/retrieval`, widens the best passage with `ContextWindow`, and reads the status view.
14
+
15
+ ```ts
16
+ import { join } from 'node:path';
17
+
18
+ import type {
19
+ EmbeddingModelV4,
20
+ EmbeddingModelV4CallOptions,
21
+ EmbeddingModelV4Result,
22
+ } from '@ai-sdk/provider';
23
+ import { TemporaryFiles } from '@zukhruf/fs';
24
+ import { ContextWindow, FusionRetriever } from '@zukhruf/retrieval';
25
+ import {
26
+ SqliteBM25Retriever,
27
+ SqliteEmbeddingRetriever,
28
+ SqlitePassageStore,
29
+ } from '@zukhruf/retrieval/sqlite';
30
+ import { open } from '@zukhruf/sqlite-open';
31
+ import { install } from '@zukhruf/vectors/sqlite';
32
+ import { countTokens } from 'gpt-tokenizer/encoding/cl100k_base';
33
+
34
+ import { Connection, Copy, IterableSource, Pipeline } from '@eltjs/elt';
35
+ import { SQLiteDestination, SQLiteSyncHistory } from '@eltjs/elt-sqlite';
36
+ import { Vectorizer } from '@eltjs/vectorizer/sqlite';
37
+
38
+ // A local embedding model with no network: the vector of a text counts each
39
+ // letter a to z. Give your own AI SDK embedding model in its place.
40
+ class LetterModel implements EmbeddingModelV4 {
41
+ readonly specificationVersion = 'v4';
42
+ readonly provider = 'readme';
43
+ readonly modelId = 'letters';
44
+ readonly maxEmbeddingsPerCall = undefined;
45
+ readonly supportsParallelCalls = true;
46
+
47
+ async doEmbed({
48
+ values,
49
+ }: EmbeddingModelV4CallOptions): Promise<EmbeddingModelV4Result> {
50
+ return {
51
+ embeddings: values.map((text) =>
52
+ Array.from(
53
+ { length: 26 },
54
+ (_, letter) =>
55
+ [...text.toLowerCase()].filter(
56
+ (character) => character.charCodeAt(0) - 97 === letter,
57
+ ).length,
58
+ ),
59
+ ),
60
+ warnings: [],
61
+ };
62
+ }
63
+ }
64
+
65
+ const tasks = [
66
+ {
67
+ name: 'fix-git',
68
+ title: 'Fix a broken git history',
69
+ body: 'A rebase went wrong and two commits are lost. Find them in the reflog and put them back on main.',
70
+ category: 'software-engineering',
71
+ },
72
+ {
73
+ name: 'train-fasttext',
74
+ title: 'Train a fastText model',
75
+ body: 'Train a text classifier on the reviews in the data folder, and save a model of less than 150 MB.',
76
+ category: 'model-training',
77
+ },
78
+ {
79
+ name: 'git-multibranch',
80
+ title: 'Deploy two git branches',
81
+ body: 'Set up a git server where a push to main or dev deploys that branch to its own web folder.',
82
+ category: 'system-administration',
83
+ },
84
+ ];
85
+
86
+ await using directory = await new TemporaryFiles().directory('vectorizer-');
87
+ const model = new LetterModel();
88
+ const source = new IterableSource({
89
+ identity: 'terminal-bench',
90
+ streams: {
91
+ tasks: {
92
+ description: 'The tasks of Terminal-Bench 2.',
93
+ jsonSchema: {
94
+ type: 'object',
95
+ description: 'A task.',
96
+ properties: {
97
+ name: { type: 'string', description: 'The name of the task.' },
98
+ title: { type: 'string', description: 'Its title.' },
99
+ body: { type: 'string', description: 'What it asks.' },
100
+ category: { type: 'string', description: 'Its category.' },
101
+ },
102
+ required: ['name', 'title', 'body', 'category'],
103
+ },
104
+ primaryKey: ['name'],
105
+ snapshot: () => tasks,
106
+ },
107
+ },
108
+ });
109
+ const destination = new SQLiteDestination({
110
+ path: join(directory.path, 'tasks.sqlite'),
111
+ });
112
+ const table = destination.table('tasks');
113
+ const vectorizer = new Vectorizer({
114
+ into: destination,
115
+ from: table,
116
+ name: 'docs',
117
+ description: 'The tasks of Terminal-Bench 2.',
118
+ key: 'name',
119
+ loading: { columns: ['title', 'body'] },
120
+ chunking: {
121
+ tokenizer: { name: 'cl100k_base', count: countTokens },
122
+ maxTokens: 16,
123
+ overlapTokens: 0,
124
+ },
125
+ embedding: { model, dimensions: 26, clock: globalThis },
126
+ metadata: ['category'],
127
+ });
128
+
129
+ await new Pipeline({
130
+ clock: globalThis,
131
+ history: new SQLiteSyncHistory(),
132
+ connections: [
133
+ new Connection({
134
+ name: 'terminal-bench',
135
+ source,
136
+ destination,
137
+ steps: [
138
+ new Copy(source.streams.tasks, table, {
139
+ syncMode: 'full_refresh',
140
+ destinationSyncMode: 'overwrite_dedup',
141
+ }),
142
+ ],
143
+ }),
144
+ ],
145
+ derived: [vectorizer],
146
+ }).run();
147
+
148
+ using database = open(destination.path, { readOnly: true });
149
+ install(database);
150
+ const store = new SqlitePassageStore({
151
+ database,
152
+ passages: vectorizer.contract.passages,
153
+ });
154
+ const meaning = new SqliteEmbeddingRetriever({
155
+ store,
156
+ vectors: vectorizer.contract.vectors,
157
+ model,
158
+ });
159
+ const words = new SqliteBM25Retriever({
160
+ store,
161
+ index: vectorizer.contract.index,
162
+ });
163
+ const search = new FusionRetriever({ retrievers: [meaning, words] });
164
+
165
+ const found = await search.retrieve('deploy git branches', { topK: 3 });
166
+ for (const { passage, score } of found)
167
+ console.log(passage.id, passage.metadata.category, score.toFixed(4));
168
+
169
+ const [widened] = await new ContextWindow({ store, windowSize: 5 }).postprocess(
170
+ found,
171
+ 'deploy git branches',
172
+ );
173
+ console.log(JSON.stringify(widened?.passage.text));
174
+
175
+ console.log({ ...database.prepare('SELECT * FROM "docs_status"').get() });
176
+ ```
177
+
178
+ The output:
179
+
180
+ ```text
181
+ git-multibranch:0 system-administration 0.0328
182
+ git-multibranch:1 system-administration 0.0161
183
+ fix-git:2 software-engineering 0.0159
184
+ "Deploy two git branches\nSet up a git server where a push to main or dev deploys that branch to its own web folder."
185
+ {
186
+ state: 'current',
187
+ as_of: '2026-11-24T17:30:59.962Z',
188
+ pending_sources: 0,
189
+ pending_vectors: 0
190
+ }
191
+ ```
192
+
193
+ - `from` is the table of a copy, and `into` is its file. A `View` can be `from` too: it names its own file, so the vectorizer then takes no `into`.
194
+ - `key` is the column, or the columns, that identify a source row.
195
+ - `loading: { columns }` gives the text of these columns, with a line break between them.
196
+ - `chunking` gives the sizes of [`@eltjs/chunking`](../chunking/README.md): the tokenizer of the embedding model, `maxTokens` and `overlapTokens`.
197
+ - `embedding` gives the options of [`@eltjs/embedding`](../embedding/README.md) without `key` and `fields`: the AI SDK embedding model, its `dimensions` and the `clock` of its calls.
198
+ - `metadata` lists the columns of the source row that each passage gives beside its text. With no `metadata`, a passage has none.
199
+ - `vectorizer.contract` gives the names that the store and the retrievers take: `{ passages, vectors, index }`.
200
+
201
+ ## Search the text of stored files
202
+
203
+ With `loading: { file }`, the passages cut the text of the file that a column names. The vectorizer reads each file once with a `DocumentParser`, as `DocumentText` of elt does, and keys the passages by the source key, so two rows that share one file each have their passages.
204
+
205
+ ```ts
206
+ import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
207
+ import { join } from 'node:path';
208
+
209
+ import type {
210
+ EmbeddingModelV4,
211
+ EmbeddingModelV4CallOptions,
212
+ EmbeddingModelV4Result,
213
+ } from '@ai-sdk/provider';
214
+ import { TemporaryFiles } from '@zukhruf/fs';
215
+ import {
216
+ SqliteBM25Retriever,
217
+ SqlitePassageStore,
218
+ } from '@zukhruf/retrieval/sqlite';
219
+ import { open } from '@zukhruf/sqlite-open';
220
+
221
+ import {
222
+ Catalog,
223
+ Connection,
224
+ Copy,
225
+ type CopyConfiguration,
226
+ DocumentParser,
227
+ Gauge,
228
+ LocalFiles,
229
+ Pipeline,
230
+ Source,
231
+ Stream,
232
+ } from '@eltjs/elt';
233
+ import { SQLiteDestination, SQLiteSyncHistory } from '@eltjs/elt-sqlite';
234
+ import { Vectorizer } from '@eltjs/vectorizer/sqlite';
235
+
236
+ // A local embedding model with no network, as in the first example.
237
+ class LetterModel implements EmbeddingModelV4 {
238
+ readonly specificationVersion = 'v4';
239
+ readonly provider = 'readme';
240
+ readonly modelId = 'letters';
241
+ readonly maxEmbeddingsPerCall = undefined;
242
+ readonly supportsParallelCalls = true;
243
+
244
+ async doEmbed({
245
+ values,
246
+ }: EmbeddingModelV4CallOptions): Promise<EmbeddingModelV4Result> {
247
+ return {
248
+ embeddings: values.map((text) =>
249
+ Array.from(
250
+ { length: 26 },
251
+ (_, letter) =>
252
+ [...text.toLowerCase()].filter(
253
+ (character) => character.charCodeAt(0) - 97 === letter,
254
+ ).length,
255
+ ),
256
+ ),
257
+ warnings: [],
258
+ };
259
+ }
260
+ }
261
+
262
+ // The notes a user keeps in one folder. Each file is one record.
263
+ class NotesFolder extends Source {
264
+ readonly identity = 'notes-folder';
265
+ readonly notes = new Stream({
266
+ name: 'notes',
267
+ jsonSchema: {
268
+ type: 'object',
269
+ description: 'A file in the folder.',
270
+ properties: { name: { type: 'string', description: 'File name.' } },
271
+ required: ['name'],
272
+ },
273
+ primaryKey: ['name'],
274
+ supportedSyncModes: ['full_refresh'],
275
+ supportsFileTransfer: true,
276
+ });
277
+ protected readonly catalog = new Catalog([this.notes]);
278
+ readonly #folder: string;
279
+
280
+ constructor(folder: string) {
281
+ super();
282
+ this.#folder = folder;
283
+ }
284
+
285
+ override coverage() {
286
+ return { description: 'Every file in the folder.', selection: {} };
287
+ }
288
+
289
+ override async currentAsOf() {
290
+ return null;
291
+ }
292
+
293
+ protected override async open() {
294
+ return new AsyncDisposableStack();
295
+ }
296
+
297
+ // This program only runs and never watches, so no watch reads this gauge.
298
+ override changeSignals(streams: readonly Stream[]) {
299
+ const gauge = new (class extends Gauge<number> {
300
+ protected async read() {
301
+ return 0;
302
+ }
303
+ })();
304
+ return [{ gauge, streams, interval: 1000, timeout: 1000 }];
305
+ }
306
+
307
+ protected override async *extract(configuration: CopyConfiguration) {
308
+ for (const name of await readdir(this.#folder))
309
+ yield {
310
+ stream: configuration.stream.name,
311
+ data: { name },
312
+ file: join(this.#folder, name),
313
+ };
314
+ }
315
+ }
316
+
317
+ // The text of a plain text file.
318
+ class TextParser extends DocumentParser {
319
+ constructor() {
320
+ super('text/plain');
321
+ }
322
+
323
+ override async parse(path: string) {
324
+ return readFile(path, 'utf8');
325
+ }
326
+ }
327
+
328
+ await using directory = await new TemporaryFiles().directory('vectorizer-');
329
+ const folder = join(directory.path, 'Notes');
330
+ await mkdir(folder);
331
+ await writeFile(
332
+ join(folder, 'monday.txt'),
333
+ 'Call the cooperative about the cold store.',
334
+ );
335
+ await writeFile(join(folder, 'tuesday.txt'), 'Order panels for the barn roof.');
336
+
337
+ const source = new NotesFolder(folder);
338
+ const files = new LocalFiles({ directory: join(directory.path, 'files') });
339
+ const destination = new SQLiteDestination({
340
+ path: join(directory.path, 'notes.sqlite'),
341
+ });
342
+ const notes = destination.table('notes', (c) => [
343
+ c.text('name').primaryKey(),
344
+ c.text('noteRef').from(source.notes.file.store(files)),
345
+ ]);
346
+ const vectorizer = new Vectorizer({
347
+ into: destination,
348
+ from: notes,
349
+ name: 'notes_search',
350
+ description: 'The notes in the folder.',
351
+ key: 'name',
352
+ loading: { file: 'noteRef', files, parser: () => new TextParser() },
353
+ chunking: 'none',
354
+ embedding: { model: new LetterModel(), dimensions: 26, clock: globalThis },
355
+ });
356
+
357
+ await new Pipeline({
358
+ clock: globalThis,
359
+ history: new SQLiteSyncHistory(),
360
+ connections: [
361
+ new Connection({
362
+ name: 'notes',
363
+ source,
364
+ destination,
365
+ steps: [new Copy(source.notes, notes)],
366
+ }),
367
+ ],
368
+ derived: [vectorizer],
369
+ }).run();
370
+
371
+ using database = open(destination.path, { readOnly: true });
372
+ const store = new SqlitePassageStore({
373
+ database,
374
+ passages: vectorizer.contract.passages,
375
+ });
376
+ const words = new SqliteBM25Retriever({
377
+ store,
378
+ index: vectorizer.contract.index,
379
+ });
380
+ for (const { passage } of await words.retrieve('cold store'))
381
+ console.log(
382
+ passage.id,
383
+ JSON.stringify(passage.text),
384
+ passage.start,
385
+ passage.end,
386
+ );
387
+ ```
388
+
389
+ The output:
390
+
391
+ ```text
392
+ monday.txt:0 "Call the cooperative about the cold store." 0 42
393
+ ```
394
+
395
+ ## The relations
396
+
397
+ A vectorizer named `docs` refreshes these members, in this order, in the file of its source. Each is a derived dataset of elt-sqlite with its own row of `derived_status`.
398
+
399
+ | Relation | What it holds |
400
+ | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
401
+ | `docs_text` | Only with `loading: { file }`: the text of each stored file, a computed dataset of `DocumentText` |
402
+ | `docs_documents` | Only with `loading: { file }`: the text of the file of each source row, by the source key |
403
+ | `docs_chunks` | The parts of the text of each source row, a computed dataset; its parts are in `docs_chunks_parts` |
404
+ | `docs_keywords` | The id, source, seq and text of each passage. The FTS5 table `docs_passages_fts` indexes the text |
405
+ | `docs_passages` | The passages: `rowid`, `id`, `source`, `seq`, `start`, `end`, `text` and the metadata columns |
406
+ | `docs_chunk_texts` | The text of each part, by its part hash |
407
+ | `docs_chunk_vectors` | The vector of each part text, a computed dataset of `Embedding` |
408
+ | `docs_passage_vectors` | The vectors: `id`, `vector` and `model`, the identity of the model, for example `openai/text-embedding-3-small (1536 dimensions)` |
409
+ | `docs_status` | One row: `state`, `as_of`, `pending_sources` and `pending_vectors` |
410
+
411
+ - The id of a passage is `<source>:<seq>`.
412
+ - The passages of a source row tile its text: `start` and `end` count code points, and `ContextWindow` merges passages by them with no gap.
413
+ - A part text that many passages share is embedded once.
414
+ - A vector that the model failed is not in `docs_passage_vectors`, so a vector search never gives its passage. A keyword search still gives it.
415
+ - The keywords table, the FTS5 table and its three triggers are one declaration. When one of them differs from the declaration, the next refresh makes all of them again. See [ADR 0002](./docs/adr/0002-the-keyword-index-is-a-member-that-keeps-a-keywords-table-and-its-full-text-index-in-step.md).
416
+
417
+ ## One passage for each row
418
+
419
+ `chunking: 'none'` gives one passage for each source row: its whole text, with `seq` 0, `start` 0 and `end` the count of code points of the text. Use it for short rows, for example a title and a summary.
420
+
421
+ ## A key of several columns
422
+
423
+ When `key` is a list of two or more columns, the source of a passage is the JSON array of their values, for example `["s1",7]`, and its id is `["s1",7]:0`. A key of one column gives its plain value, for example `7`.
424
+
425
+ ## A new model
426
+
427
+ When the model or its `dimensions` change, the next refresh makes each vector again, in place. While it runs, `docs_status` has the state `refreshing` and counts the texts that wait in `pending_vectors`. A retriever with the new model finds only the passages that it already embedded, and a retriever with the old model finds only the others. When the refresh ends, each vector has the new model.
428
+
429
+ ## Rules and failures
430
+
431
+ - The constructor refuses, with a `TypeError` that names it, a metadata column that has the name of a column of the passages (`rowid`, `id`, `source`, `seq`, `start`, `end` or `text`, in any ASCII case), and a metadata column or a key column that is listed twice.
432
+ - Before it reads, the pipeline refuses a vectorizer whose table no copy loads into its file, and a key, metadata or loading column that the stream or the target does not declare. The run rejects with a `TypeError`.
433
+ - The name of the vectorizer and the name of each relation count in the check of distinct names of the pipeline.
434
+ - A vectorizer fails as one dataset of the pipeline ([elt ADR 0034](../elt/docs/adr/0034-a-composite-dataset-refreshes-its-members-in-order-as-one-dataset.md)): the first member that fails stops the members after it, the copies and the other datasets go on, and the refresh after the next pass tries it again. A run rejects with the `DerivedDatasetError` of the vectorizer, whose `cause` is the `DerivedDatasetError` of the member. `docs_status` then has the state `failed`.
435
+
436
+ ## The same in other systems
437
+
438
+ | System | What it is |
439
+ | ------------------------------ | -------------------------------------------------------------------------------- |
440
+ | pgai `create_vectorizer` | One call that keeps the embeddings of a Postgres table in step with its rows |
441
+ | Airbyte vector destinations | `text_fields` and `metadata_fields` of each record, chunked and embedded on load |
442
+ | LlamaIndex `IngestionPipeline` | The steps that make nodes and their embeddings from documents |
443
+
444
+ ## Decisions
445
+
446
+ - [ADR 0001](./docs/adr/0001-the-vectorizer-writes-the-passage-contract-of-zukhruf-retrieval-one-subpath-per-engine.md): the vectorizer writes the passage contract of `@zukhruf/retrieval`, one subpath per engine.
447
+ - [ADR 0002](./docs/adr/0002-the-keyword-index-is-a-member-that-keeps-a-keywords-table-and-its-full-text-index-in-step.md): the keyword index is a member that keeps a keywords table and its full-text index in step.
448
+
449
+ ## Development
450
+
451
+ ```sh
452
+ npx nx run vectorizer:test # builds, then runs src/sqlite.test.ts
453
+ npx nx run vectorizer:typecheck # formats, lints, then type checks
454
+ ```
455
+
456
+ ```
457
+ src/
458
+ sqlite.ts the subpath /sqlite
459
+ options.ts SourceKey, Loading, ChunkingOptions, EmbeddingOptions and the checks of the columns
460
+ passage-rules.ts the rules of the passages: the chunks of Chunking by source, or one part for each row
461
+ sqlite/vectorizer.ts Vectorizer: the members and the views of SQLite
462
+ sqlite/keyword-index.ts KeywordIndex: the keywords table, its FTS5 table and its triggers
463
+ ```