@eltjs/vectorizer 0.0.0-stage → 0.13.8

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.
@@ -0,0 +1,260 @@
1
+ import { CompositeDataset, DocumentText, } from '@eltjs/elt';
2
+ import { ComputedDataset, PostgresDestination, PostgresTable, View, hnsw, inMarts, inWarehouse, marts, quote, rawTable, } from '@eltjs/elt-postgresql';
3
+ import { Embedding } from '@eltjs/embedding';
4
+ import { copiesInto } from '../copies.js';
5
+ import { refuseUndeclaredColumns } from '../declared-columns.js';
6
+ import { keyColumns, refuseColumns, } from '../options.js';
7
+ import { passageRule } from '../passage-rules.js';
8
+ import { KeywordIndex } from './keyword-index.js';
9
+ // The columns of the passages of @zukhruf/retrieval on Postgres, which no
10
+ // metadata column may take: the passage columns of its ADR 0001 and the
11
+ // keywords column of its ADR 0004.
12
+ const contractColumns = [
13
+ 'id',
14
+ 'source',
15
+ 'seq',
16
+ 'start',
17
+ 'end',
18
+ 'text',
19
+ 'keywords',
20
+ ];
21
+ // One declaration that keeps the passage contract of @zukhruf/retrieval in
22
+ // step with what a pipeline loads into one Postgres database, as pgai's
23
+ // create_vectorizer does: the passages of each source row with its metadata,
24
+ // the vector of each passage with the identity of its model, and a keyword
25
+ // index of the passages (ADR 0001). Each relation is a member that the
26
+ // pipeline refreshes in order, so a member's failure fails only the
27
+ // vectorizer (elt ADR 0034). The views of the contract live in marts and read
28
+ // the raw tables in _warehouse, the rows of now, so a search uses the HNSW
29
+ // index of the vectors and the GIN index of the keywords. Every relation's
30
+ // name starts with name.
31
+ export class Vectorizer extends CompositeDataset {
32
+ name;
33
+ members;
34
+ contract;
35
+ // The database of the relations, whose URL a host opens for the store.
36
+ into;
37
+ #from;
38
+ #key;
39
+ #loading;
40
+ #metadata;
41
+ // name: the start of the name of each relation. key: the column, or
42
+ // columns, that identify a source row. loading: what text of a row the
43
+ // passages cut. metadata: the columns of the source row that each passage
44
+ // gives beside its text; none when absent (Airbyte metadata_fields).
45
+ // keywords: the text search configuration of the keyword index, 'english'
46
+ // when absent, as PgvectorKeywordRetriever reads it. indexing: the index of
47
+ // the vectors, an HNSW index with pgvector's own build when absent (pgai
48
+ // ai.indexing_hnsw), or none, so a search compares every vector (pgai
49
+ // ai.indexing_none).
50
+ constructor(options) {
51
+ super();
52
+ const { name, description, key, loading, chunking, embedding } = options;
53
+ const metadata = options.metadata ?? [];
54
+ const configuration = options.keywords?.configuration ?? 'english';
55
+ const build = options.indexing?.vectors ?? hnsw();
56
+ refuseColumns({
57
+ vectorizer: name,
58
+ key,
59
+ metadata,
60
+ contract: contractColumns,
61
+ });
62
+ this.name = name;
63
+ this.into = 'into' in options ? options.into : options.from.into;
64
+ this.#from = options.from;
65
+ this.#key = key;
66
+ this.#loading = loading;
67
+ this.#metadata = Object.freeze([...metadata]);
68
+ const into = this.into;
69
+ const columns = keyColumns(key);
70
+ const source = options.from instanceof PostgresTable
71
+ ? inWarehouse(options.from.raw)
72
+ : inMarts(options.from.name);
73
+ const keyDescriptions = Object.fromEntries(columns.map((column) => [
74
+ column,
75
+ `The ${column} column of the key of the source row.`,
76
+ ]));
77
+ const names = {
78
+ text: `${name}_text`,
79
+ documents: `${name}_documents`,
80
+ chunks: `${name}_chunks`,
81
+ keywords: `${name}_keywords`,
82
+ passages: `${name}_passages`,
83
+ chunkTexts: `${name}_chunk_texts`,
84
+ chunkVectors: `${name}_chunk_vectors`,
85
+ passageVectors: `${name}_passage_vectors`,
86
+ status: `${name}_status`,
87
+ };
88
+ const rawParts = rawTable(`${names.chunks}_parts`);
89
+ const parts = inWarehouse(rawParts);
90
+ const vectors = inWarehouse(rawTable(names.chunkVectors));
91
+ // The text of a stored file is the input of the chunks through a view
92
+ // keyed by the source key, since rows can share a file (elt ADR 0027).
93
+ let files = [];
94
+ let input = options.from;
95
+ if ('file' in loading) {
96
+ const text = new ComputedDataset({
97
+ into,
98
+ name: names.text,
99
+ description: `The text of each file of the vectorizer ${name}. ${description}`,
100
+ from: [options.from],
101
+ compute: new DocumentText({
102
+ parser: loading.parser,
103
+ files: loading.files,
104
+ column: loading.file,
105
+ }),
106
+ });
107
+ input = new View({
108
+ into,
109
+ name: names.documents,
110
+ description: `The text of the file of each source row of the vectorizer ${name}. ${description}`,
111
+ columns: {
112
+ ...keyDescriptions,
113
+ content: 'The text the parser extracted from the file.',
114
+ },
115
+ sql: `SELECT ${columns.map((column) => `s.${quote(column)}`).join(', ')}, t."content" FROM ${source} AS s JOIN ${inWarehouse(rawTable(names.text))} AS t ON t."ref" = s.${quote(loading.file)} WHERE t."status" = 'computed'`,
116
+ });
117
+ files = [text, input];
118
+ }
119
+ const chunks = new ComputedDataset({
120
+ into,
121
+ name: names.chunks,
122
+ description: `The passages of the vectorizer ${name}, one row for each source row. ${description}`,
123
+ from: [input],
124
+ compute: passageRule({
125
+ key,
126
+ fields: 'columns' in loading ? loading.columns : ['content'],
127
+ chunking,
128
+ }),
129
+ });
130
+ const keywords = new KeywordIndex({
131
+ into,
132
+ name: names.keywords,
133
+ parts: rawParts,
134
+ configuration,
135
+ });
136
+ // The source text of a passage is the key in the type of each key
137
+ // column: jsonb_populate_record reads it into the row type of the source,
138
+ // so the join compares in that type and looks the row up by its key.
139
+ const keyOf = (column, value) => `(jsonb_populate_record(NULL::${source}, jsonb_build_object(${literal(column)}, ${value}))).${quote(column)}`;
140
+ const join = typeof key === 'string'
141
+ ? `s.${quote(key)} = ${keyOf(key, 'p."source"')}`
142
+ : columns
143
+ .map((column, index) => `s.${quote(column)} = ${keyOf(column, `p."source"::jsonb -> ${index}`)}`)
144
+ .join(' AND ');
145
+ const passages = new View({
146
+ into,
147
+ name: names.passages,
148
+ description: `The passages of the vectorizer ${name}, as @zukhruf/retrieval reads them. ${description}`,
149
+ columns: {
150
+ id: 'The id of the passage: its source, a colon and its seq.',
151
+ source: 'The key of the source row that the passage is cut from: the value of its key column, or the JSON array of the values of its key columns.',
152
+ seq: 'The place of the passage in its source row, from 0.',
153
+ start: 'The offset of the first code point of the passage in the text of its row, from 0.',
154
+ end: 'The offset after the last code point of the passage in the text of its row.',
155
+ text: 'The text of the passage.',
156
+ keywords: `The keywords of the text, the tsvector of the text search configuration ${configuration}.`,
157
+ ...Object.fromEntries(metadata.map((column) => [
158
+ column,
159
+ `The ${column} column of the source row.`,
160
+ ])),
161
+ },
162
+ sql: `SELECT k."id", p."source", p."seq", p."start", p."end", p."text", k."keywords"${metadata
163
+ .map((column) => `, s.${quote(column)} AS ${quote(column)}`)
164
+ .join('')} FROM ${inWarehouse(rawTable(names.keywords))} AS k JOIN ${parts} AS p ON p."source" = k."source" AND p."seq" = k."seq" JOIN ${source} AS s ON ${join}`,
165
+ });
166
+ // The text of each part by its part hash. Parts with one text share a
167
+ // part hash, and a computed dataset keeps the first input of a key, so a
168
+ // text is embedded once with no DISTINCT.
169
+ const chunkTexts = new View({
170
+ into,
171
+ name: names.chunkTexts,
172
+ description: `The text of each passage of the vectorizer ${name}, by its part hash. ${description}`,
173
+ columns: {
174
+ id: 'The part hash of the passage.',
175
+ text: 'The text of the passage.',
176
+ },
177
+ sql: `SELECT "part_hash" AS "id", "text" FROM ${parts}`,
178
+ });
179
+ const indexes = build === 'none'
180
+ ? []
181
+ : [{ type: 'vector', column: 'vector', metric: 'cosine', build }];
182
+ const chunkVectors = new ComputedDataset({
183
+ into,
184
+ name: names.chunkVectors,
185
+ description: `The vector of each passage text of the vectorizer ${name}. ${description}`,
186
+ from: [chunkTexts],
187
+ compute: new Embedding({ ...embedding, key: 'id', fields: ['text'] }),
188
+ indexes,
189
+ });
190
+ // A vector whose model failed is no answer to a search, so only computed
191
+ // ones show. The rule names the model as the retriever reads it. The id
192
+ // compares in byte order, as the primary key of the keyword index does,
193
+ // so the retriever's join to the passages looks each one up by it.
194
+ const passageVectors = new View({
195
+ into,
196
+ name: names.passageVectors,
197
+ description: `The vector of each passage of the vectorizer ${name}, as @zukhruf/retrieval reads them. ${description}`,
198
+ columns: {
199
+ id: 'The id of the passage.',
200
+ vector: 'The unit vector of the passage text.',
201
+ model: 'The model that made the vector: <provider>/<model id> (<n> dimensions).',
202
+ },
203
+ sql: `SELECT (p."source" || ':' || p."seq") COLLATE "C" AS "id", v."vector", v."rule" AS "model" FROM ${parts} AS p JOIN ${vectors} AS v ON v."id" = p."part_hash" WHERE v."status" = 'computed'`,
204
+ });
205
+ const leaves = [
206
+ ...files,
207
+ chunks,
208
+ keywords,
209
+ passages,
210
+ chunkTexts,
211
+ chunkVectors,
212
+ passageVectors,
213
+ ];
214
+ const status = new View({
215
+ into,
216
+ name: names.status,
217
+ description: `How far the relations of the vectorizer ${name} are in step with their source. ${description}`,
218
+ columns: {
219
+ state: 'failed when a relation failed, waiting when one waits for its input, refreshing when one refreshes, else current.',
220
+ as_of: 'The earliest as_of of the relations: the data that every relation holds. NULL until each holds some.',
221
+ pending_sources: 'The source rows that wait for their passages.',
222
+ pending_vectors: 'The passage texts that wait for their vectors.',
223
+ },
224
+ sql: `WITH "members" ("dataset") AS (VALUES ${leaves
225
+ .map((member) => `(${literal(member.qualifiedName)})`)
226
+ .join(', ')}), "rows" AS (SELECT m."dataset", coalesce(d."state", 'waiting') AS "state", d."as_of", coalesce(d."pending", 0) AS "pending" FROM "members" AS m LEFT JOIN ${inWarehouse('derived_status')} AS d ON d."dataset" = m."dataset") SELECT CASE max(CASE "state" WHEN 'failed' THEN 3 WHEN 'waiting' THEN 2 WHEN 'refreshing' THEN 1 ELSE 0 END) WHEN 3 THEN 'failed' WHEN 2 THEN 'waiting' WHEN 1 THEN 'refreshing' ELSE 'current' END AS "state", CASE WHEN count("as_of") = count(*) THEN min("as_of") END AS "as_of", (SELECT "pending" FROM "rows" WHERE "dataset" = ${literal(chunks.qualifiedName)}) AS "pending_sources", (SELECT "pending" FROM "rows" WHERE "dataset" = ${literal(chunkVectors.qualifiedName)}) AS "pending_vectors" FROM "rows"`,
227
+ });
228
+ this.members = Object.freeze([...leaves, status]);
229
+ this.contract = Object.freeze({
230
+ schema: marts,
231
+ passages: names.passages,
232
+ vectors: names.passageVectors,
233
+ index: Object.freeze({ column: 'keywords', configuration }),
234
+ });
235
+ Object.freeze(this);
236
+ }
237
+ // A source table must be one that a copy loads into the database of the
238
+ // vectorizer, and the copy's stream must declare each column that the
239
+ // vectorizer reads. A View's columns are its own SQL's, so its first
240
+ // refresh tells, as for any view.
241
+ validate(connections) {
242
+ const from = this.#from;
243
+ if (!(from instanceof PostgresTable))
244
+ return;
245
+ refuseUndeclaredColumns({
246
+ vectorizer: this.name,
247
+ from,
248
+ copies: copiesInto(connections, (destination) => destination instanceof PostgresDestination &&
249
+ destination.url === this.into.url),
250
+ destination: 'its database',
251
+ key: this.#key,
252
+ metadata: this.#metadata,
253
+ loading: this.#loading,
254
+ });
255
+ }
256
+ }
257
+ // A string literal of SQL.
258
+ function literal(text) {
259
+ return `'${text.replaceAll("'", "''")}'`;
260
+ }
@@ -0,0 +1,2 @@
1
+ export { Vectorizer, type PostgresContract } from './postgresql/vectorizer.ts';
2
+ export type { ChunkingOptions, EmbeddingOptions, Loading, SourceKey, } from './options.ts';
@@ -0,0 +1 @@
1
+ export { Vectorizer } from './postgresql/vectorizer.js';
@@ -0,0 +1,18 @@
1
+ import { type Connection, DerivedDataset, type PipelineClock } from '@eltjs/elt';
2
+ import { SQLiteDestination, type SQLiteTable } from '@eltjs/elt-sqlite';
3
+ export declare class KeywordIndex extends DerivedDataset<SQLiteTable> {
4
+ #private;
5
+ readonly name: string;
6
+ readonly index: string;
7
+ constructor({ into, name, index, parts, }: {
8
+ into: SQLiteDestination;
9
+ name: string;
10
+ index: string;
11
+ parts: string;
12
+ });
13
+ validate(connections: readonly Connection<SQLiteTable>[]): void;
14
+ refresh({ clock, signal, }: {
15
+ readonly clock: PipelineClock;
16
+ readonly signal?: AbortSignal;
17
+ }): Promise<void>;
18
+ }
@@ -0,0 +1,98 @@
1
+ import { Declaration } from '@zukhruf/sqlite-drift';
2
+ import { transaction } from '@zukhruf/sqlite-transaction';
3
+ import { DerivedDataset, errorMessage, } from '@eltjs/elt';
4
+ import { SQLiteDerivedStatus, SQLiteDestination, openDestination, quote, } from '@eltjs/elt-sqlite';
5
+ import { copiesInto } from '../copies.js';
6
+ // The keyword index of the passages of a vectorizer: the table <name> keeps
7
+ // the id, source, seq and text of each passage, and the FTS5 table <index>
8
+ // indexes its text, as @zukhruf/retrieval's SqliteBM25Retriever reads it
9
+ // (its ADR 0004). Triggers keep the index in step with the table, and the
10
+ // table, the index and the triggers are one declaration, so a change to any
11
+ // of them makes all of them again, and the refill fills the index through the
12
+ // insert trigger (ADR 0002). A refresh writes the passages that changed and
13
+ // removes the ones that are gone in one transaction, so a reader sees the
14
+ // index of one refresh or of the next, never a part of one.
15
+ export class KeywordIndex extends DerivedDataset {
16
+ name;
17
+ // The FTS5 table, which the passages view joins by rowid.
18
+ index;
19
+ #into;
20
+ #parts;
21
+ #declaration;
22
+ // name: the table of the passages' keywords. index: its FTS5 table. parts:
23
+ // the raw parts table of the chunks, which keeps source, seq and text.
24
+ constructor({ into, name, index, parts, }) {
25
+ super();
26
+ this.name = name;
27
+ this.index = index;
28
+ this.#into = into;
29
+ this.#parts = parts;
30
+ const table = quote(name);
31
+ const fts = quote(index);
32
+ const removal = `INSERT INTO ${fts} (${fts}, "rowid", "text") VALUES ('delete', old."rowid", old."text");`;
33
+ const addition = `INSERT INTO ${fts} ("rowid", "text") VALUES (new."rowid", new."text");`;
34
+ this.#declaration = new Declaration([
35
+ `CREATE TABLE ${table} ("rowid" INTEGER PRIMARY KEY, "id" TEXT NOT NULL UNIQUE, "source" TEXT NOT NULL, "seq" INTEGER NOT NULL, "text" TEXT NOT NULL, UNIQUE ("source", "seq")) STRICT`,
36
+ `CREATE VIRTUAL TABLE ${fts} USING fts5("text", content = '${name.replaceAll("'", "''")}')`,
37
+ `CREATE TRIGGER ${quote(`${name}_ai`)} AFTER INSERT ON ${table} BEGIN ${addition} END`,
38
+ `CREATE TRIGGER ${quote(`${name}_ad`)} AFTER DELETE ON ${table} BEGIN ${removal} END`,
39
+ `CREATE TRIGGER ${quote(`${name}_au`)} AFTER UPDATE ON ${table} BEGIN ${removal} ${addition} END`,
40
+ ], { rows: 'replace' });
41
+ Object.freeze(this);
42
+ }
43
+ validate(connections) {
44
+ const made = copiesInto(connections, (destination) => destination instanceof SQLiteDestination &&
45
+ destination.path === this.#into.path)
46
+ .flatMap(({ to }) => [to.name, to.raw])
47
+ .map((name) => name.toLowerCase());
48
+ for (const name of [this.name, this.index])
49
+ if (made.includes(name.toLowerCase()))
50
+ throw new TypeError(`Keyword index ${this.name} needs ${name}, which a copy of the pipeline makes`);
51
+ }
52
+ async refresh({ clock, signal, }) {
53
+ using database = openDestination(this.#into.path);
54
+ const status = new SQLiteDerivedStatus(database, this.name, 'computed', clock);
55
+ const table = quote(this.name);
56
+ const parts = quote(this.#parts);
57
+ let counts;
58
+ try {
59
+ counts = transaction(database, () => {
60
+ this.#declaration.apply(database);
61
+ // SQLite parses the ON CONFLICT of an INSERT of a SELECT only after
62
+ // a WHERE.
63
+ database
64
+ .prepare(`INSERT INTO ${table} ("id", "source", "seq", "text") SELECT p."source" || ':' || p."seq", p."source", p."seq", p."text" FROM ${parts} AS p WHERE true ON CONFLICT ("id") DO UPDATE SET "text" = excluded."text" WHERE ${table}."text" IS NOT excluded."text"`)
65
+ .run();
66
+ database
67
+ .prepare(`DELETE FROM ${table} WHERE NOT EXISTS (SELECT 1 FROM ${parts} AS p WHERE p."source" = ${table}."source" AND p."seq" = ${table}."seq")`)
68
+ .run();
69
+ const row = database
70
+ .prepare(`SELECT (SELECT count(*) FROM ${parts}) AS "inputs", (SELECT count(*) FROM ${table}) AS "computed"`)
71
+ .get();
72
+ return {
73
+ inputs: Number(row?.inputs),
74
+ computed: Number(row?.computed),
75
+ };
76
+ }, { mode: 'immediate' });
77
+ }
78
+ catch (error) {
79
+ // The chunks have no parts table yet while they wait for their input,
80
+ // so the index waits with them.
81
+ if (this.#missingParts(error)) {
82
+ await status.waiting();
83
+ return;
84
+ }
85
+ // A stop is not the dataset's failure.
86
+ if (signal?.aborted !== true)
87
+ await status.failed(errorMessage(error));
88
+ throw error;
89
+ }
90
+ await status.current({ ...counts, empty: 0, failed: 0, pending: 0 });
91
+ }
92
+ #missingParts(error) {
93
+ return (Error.isError(error) &&
94
+ /^no such table: (?:main\.)?(.+)$/
95
+ .exec(error.message)?.[1]
96
+ ?.toLowerCase() === this.#parts.toLowerCase());
97
+ }
98
+ }
@@ -0,0 +1,35 @@
1
+ import { CompositeDataset, type Connection, type DerivedDataset } from '@eltjs/elt';
2
+ import { SQLiteDestination, SQLiteTable, View } from '@eltjs/elt-sqlite';
3
+ import { type ChunkingOptions, type EmbeddingOptions, type Loading, type SourceKey } from '../options.ts';
4
+ type Origin = {
5
+ readonly into: SQLiteDestination;
6
+ readonly from: SQLiteTable;
7
+ } | {
8
+ readonly from: View;
9
+ };
10
+ export type SqliteContract = {
11
+ readonly passages: string;
12
+ readonly vectors: string;
13
+ readonly index: string;
14
+ };
15
+ export declare class Vectorizer extends CompositeDataset<SQLiteTable> {
16
+ #private;
17
+ readonly name: string;
18
+ readonly members: readonly [
19
+ DerivedDataset<SQLiteTable>,
20
+ ...DerivedDataset<SQLiteTable>[]
21
+ ];
22
+ readonly contract: SqliteContract;
23
+ readonly into: SQLiteDestination;
24
+ constructor(options: Origin & {
25
+ readonly name: string;
26
+ readonly description: string;
27
+ readonly key: SourceKey;
28
+ readonly loading: Loading;
29
+ readonly chunking: ChunkingOptions;
30
+ readonly embedding: EmbeddingOptions;
31
+ readonly metadata?: readonly string[];
32
+ });
33
+ validate(connections: readonly Connection<SQLiteTable>[]): void;
34
+ }
35
+ export {};
@@ -0,0 +1,236 @@
1
+ import { CompositeDataset, DocumentText, } from '@eltjs/elt';
2
+ import { ComputedDataset, SQLiteDestination, SQLiteTable, View, quote, rawTable, } from '@eltjs/elt-sqlite';
3
+ import { Embedding } from '@eltjs/embedding';
4
+ import { copiesInto } from '../copies.js';
5
+ import { refuseUndeclaredColumns } from '../declared-columns.js';
6
+ import { keyColumns, refuseColumns, } from '../options.js';
7
+ import { passageRule } from '../passage-rules.js';
8
+ import { KeywordIndex } from './keyword-index.js';
9
+ // The columns of the passages of @zukhruf/retrieval on SQLite, which no
10
+ // metadata column may take (its ADR 0001).
11
+ const contractColumns = [
12
+ 'rowid',
13
+ 'id',
14
+ 'source',
15
+ 'seq',
16
+ 'start',
17
+ 'end',
18
+ 'text',
19
+ ];
20
+ // One declaration that keeps the passage contract of @zukhruf/retrieval in
21
+ // step with what a pipeline loads into one SQLite file, as pgai's
22
+ // create_vectorizer does in Postgres: the passages of each source row with
23
+ // its metadata, the vector of each passage with the identity of its model,
24
+ // and a keyword index of the passages (ADR 0001). Each relation is a member
25
+ // that the pipeline refreshes in order, so a member's failure fails only the
26
+ // vectorizer (elt ADR 0034). Every relation's name starts with name.
27
+ export class Vectorizer extends CompositeDataset {
28
+ name;
29
+ members;
30
+ contract;
31
+ // The file of the relations, which a host opens for the store.
32
+ into;
33
+ #from;
34
+ #key;
35
+ #loading;
36
+ #metadata;
37
+ // name: the start of the name of each relation. key: the column, or
38
+ // columns, that identify a source row. loading: what text of a row the
39
+ // passages cut. metadata: the columns of the source row that each passage
40
+ // gives beside its text; none when absent (Airbyte metadata_fields).
41
+ constructor(options) {
42
+ super();
43
+ const { name, description, key, loading, chunking, embedding } = options;
44
+ const metadata = options.metadata ?? [];
45
+ refuseColumns({
46
+ vectorizer: name,
47
+ key,
48
+ metadata,
49
+ contract: contractColumns,
50
+ });
51
+ this.name = name;
52
+ this.into = 'into' in options ? options.into : options.from.into;
53
+ this.#from = options.from;
54
+ this.#key = key;
55
+ this.#loading = loading;
56
+ this.#metadata = Object.freeze([...metadata]);
57
+ const into = this.into;
58
+ const columns = keyColumns(key);
59
+ const source = options.from instanceof SQLiteTable
60
+ ? quote(options.from.raw)
61
+ : quote(options.from.name);
62
+ const keyDescriptions = Object.fromEntries(columns.map((column) => [
63
+ column,
64
+ `The ${column} column of the key of the source row.`,
65
+ ]));
66
+ const names = {
67
+ text: `${name}_text`,
68
+ documents: `${name}_documents`,
69
+ chunks: `${name}_chunks`,
70
+ keywords: `${name}_keywords`,
71
+ passages: `${name}_passages`,
72
+ chunkTexts: `${name}_chunk_texts`,
73
+ chunkVectors: `${name}_chunk_vectors`,
74
+ passageVectors: `${name}_passage_vectors`,
75
+ status: `${name}_status`,
76
+ index: `${name}_passages_fts`,
77
+ };
78
+ const rawParts = rawTable(`${names.chunks}_parts`);
79
+ const parts = quote(rawParts);
80
+ const vectors = quote(rawTable(names.chunkVectors));
81
+ // The text of a stored file is the input of the chunks through a view
82
+ // keyed by the source key, since rows can share a file (elt ADR 0027).
83
+ let files = [];
84
+ let input = options.from;
85
+ if ('file' in loading) {
86
+ const text = new ComputedDataset({
87
+ into,
88
+ name: names.text,
89
+ description: `The text of each file of the vectorizer ${name}. ${description}`,
90
+ from: [options.from],
91
+ compute: new DocumentText({
92
+ parser: loading.parser,
93
+ files: loading.files,
94
+ column: loading.file,
95
+ }),
96
+ });
97
+ input = new View({
98
+ into,
99
+ name: names.documents,
100
+ description: `The text of the file of each source row of the vectorizer ${name}. ${description}`,
101
+ columns: {
102
+ ...keyDescriptions,
103
+ content: 'The text the parser extracted from the file.',
104
+ },
105
+ sql: `SELECT ${columns.map((column) => `s.${quote(column)}`).join(', ')}, t."content" FROM ${source} AS s JOIN ${quote(names.text)} AS t ON t."ref" = s.${quote(loading.file)} WHERE t."status" = 'computed'`,
106
+ });
107
+ files = [text, input];
108
+ }
109
+ const chunks = new ComputedDataset({
110
+ into,
111
+ name: names.chunks,
112
+ description: `The passages of the vectorizer ${name}, one row for each source row. ${description}`,
113
+ from: [input],
114
+ compute: passageRule({
115
+ key,
116
+ fields: 'columns' in loading ? loading.columns : ['content'],
117
+ chunking,
118
+ }),
119
+ });
120
+ const keywords = new KeywordIndex({
121
+ into,
122
+ name: names.keywords,
123
+ index: names.index,
124
+ parts: rawParts,
125
+ });
126
+ const join = typeof key === 'string'
127
+ ? `s.${quote(key)} = p."source"`
128
+ : columns
129
+ .map((column, index) => `s.${quote(column)} = json_extract(p."source", '$[${index}]')`)
130
+ .join(' AND ');
131
+ const passages = new View({
132
+ into,
133
+ name: names.passages,
134
+ description: `The passages of the vectorizer ${name}, as @zukhruf/retrieval reads them. ${description}`,
135
+ columns: {
136
+ rowid: 'The rowid of the passage in the keyword index.',
137
+ id: 'The id of the passage: its source, a colon and its seq.',
138
+ source: 'The key of the source row that the passage is cut from: the value of its key column, or the JSON array of the values of its key columns.',
139
+ seq: 'The place of the passage in its source row, from 0.',
140
+ start: 'The offset of the first code point of the passage in the text of its row, from 0.',
141
+ end: 'The offset after the last code point of the passage in the text of its row.',
142
+ text: 'The text of the passage.',
143
+ ...Object.fromEntries(metadata.map((column) => [
144
+ column,
145
+ `The ${column} column of the source row.`,
146
+ ])),
147
+ },
148
+ sql: `SELECT k."rowid" AS "rowid", k."id", p."source", p."seq", p."start", p."end", p."text"${metadata
149
+ .map((column) => `, s.${quote(column)} AS ${quote(column)}`)
150
+ .join('')} FROM ${quote(names.keywords)} AS k JOIN ${parts} AS p ON p."source" = k."source" AND p."seq" = k."seq" JOIN ${source} AS s ON ${join}`,
151
+ });
152
+ // The text of each part by its part hash. Parts with one text share a
153
+ // part hash, and a computed dataset keeps the first input of a key, so a
154
+ // text is embedded once with no DISTINCT.
155
+ const chunkTexts = new View({
156
+ into,
157
+ name: names.chunkTexts,
158
+ description: `The text of each passage of the vectorizer ${name}, by its part hash. ${description}`,
159
+ columns: {
160
+ id: 'The part hash of the passage.',
161
+ text: 'The text of the passage.',
162
+ },
163
+ sql: `SELECT "part_hash" AS "id", "text" FROM ${quote(`${names.chunks}_parts`)}`,
164
+ });
165
+ const chunkVectors = new ComputedDataset({
166
+ into,
167
+ name: names.chunkVectors,
168
+ description: `The vector of each passage text of the vectorizer ${name}. ${description}`,
169
+ from: [chunkTexts],
170
+ compute: new Embedding({ ...embedding, key: 'id', fields: ['text'] }),
171
+ });
172
+ // A vector whose model failed is no answer to a search, so only computed
173
+ // ones show. The rule names the model as the retriever reads it.
174
+ const passageVectors = new View({
175
+ into,
176
+ name: names.passageVectors,
177
+ description: `The vector of each passage of the vectorizer ${name}, as @zukhruf/retrieval reads them. ${description}`,
178
+ columns: {
179
+ id: 'The id of the passage.',
180
+ vector: 'The unit vector of the passage text, float32 values.',
181
+ model: 'The model that made the vector: <provider>/<model id> (<n> dimensions).',
182
+ },
183
+ sql: `SELECT p."source" || ':' || p."seq" AS "id", v."vector", v."rule" AS "model" FROM ${parts} AS p JOIN ${vectors} AS v ON v."id" = p."part_hash" WHERE v."status" = 'computed'`,
184
+ });
185
+ const leaves = [
186
+ ...files,
187
+ chunks,
188
+ keywords,
189
+ passages,
190
+ chunkTexts,
191
+ chunkVectors,
192
+ passageVectors,
193
+ ];
194
+ const literal = (text) => `'${text.replaceAll("'", "''")}'`;
195
+ const status = new View({
196
+ into,
197
+ name: names.status,
198
+ description: `How far the relations of the vectorizer ${name} are in step with their source. ${description}`,
199
+ columns: {
200
+ state: 'failed when a relation failed, waiting when one waits for its input, refreshing when one refreshes, else current.',
201
+ as_of: 'The earliest as_of of the relations: the data that every relation holds. NULL until each holds some.',
202
+ pending_sources: 'The source rows that wait for their passages.',
203
+ pending_vectors: 'The passage texts that wait for their vectors.',
204
+ },
205
+ sql: `WITH "members" ("dataset") AS (VALUES ${leaves
206
+ .map(({ name: member }) => `(${literal(member)})`)
207
+ .join(', ')}), "rows" AS (SELECT m."dataset", coalesce(d."state", 'waiting') AS "state", d."as_of", coalesce(d."pending", 0) AS "pending" FROM "members" AS m LEFT JOIN "derived_status" AS d ON d."dataset" = m."dataset") SELECT CASE max(CASE "state" WHEN 'failed' THEN 3 WHEN 'waiting' THEN 2 WHEN 'refreshing' THEN 1 ELSE 0 END) WHEN 3 THEN 'failed' WHEN 2 THEN 'waiting' WHEN 1 THEN 'refreshing' ELSE 'current' END AS "state", CASE WHEN count("as_of") = count(*) THEN min("as_of") END AS "as_of", (SELECT "pending" FROM "rows" WHERE "dataset" = ${literal(names.chunks)}) AS "pending_sources", (SELECT "pending" FROM "rows" WHERE "dataset" = ${literal(names.chunkVectors)}) AS "pending_vectors" FROM "rows"`,
208
+ });
209
+ this.members = Object.freeze([...leaves, status]);
210
+ this.contract = Object.freeze({
211
+ passages: names.passages,
212
+ vectors: names.passageVectors,
213
+ index: names.index,
214
+ });
215
+ Object.freeze(this);
216
+ }
217
+ // A source table must be one that a copy loads into the file of the
218
+ // vectorizer, and the copy's stream must declare each column that the
219
+ // vectorizer reads. A View's columns are its own SQL's, so its first
220
+ // refresh tells, as for any view.
221
+ validate(connections) {
222
+ const from = this.#from;
223
+ if (!(from instanceof SQLiteTable))
224
+ return;
225
+ refuseUndeclaredColumns({
226
+ vectorizer: this.name,
227
+ from,
228
+ copies: copiesInto(connections, (destination) => destination instanceof SQLiteDestination &&
229
+ destination.path === this.into.path),
230
+ destination: this.into.path,
231
+ key: this.#key,
232
+ metadata: this.#metadata,
233
+ loading: this.#loading,
234
+ });
235
+ }
236
+ }
@@ -0,0 +1,2 @@
1
+ export { Vectorizer, type SqliteContract } from './sqlite/vectorizer.ts';
2
+ export type { ChunkingOptions, EmbeddingOptions, Loading, SourceKey, } from './options.ts';
package/dist/sqlite.js ADDED
@@ -0,0 +1 @@
1
+ export { Vectorizer } from './sqlite/vectorizer.js';