@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 +202 -0
- package/README.md +462 -2
- package/dist/options.d.ts +28 -0
- package/dist/options.js +20 -0
- package/dist/passage-rules.d.ts +83 -0
- package/dist/passage-rules.js +123 -0
- package/dist/sqlite/keyword-index.d.ts +18 -0
- package/dist/sqlite/keyword-index.js +99 -0
- package/dist/sqlite/vectorizer.d.ts +35 -0
- package/dist/sqlite/vectorizer.js +243 -0
- package/dist/sqlite.d.ts +2 -0
- package/dist/sqlite.js +1 -0
- package/package.json +58 -4
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { EmbeddingModel } from 'ai';
|
|
2
|
+
import type { Tokenizer } from '@eltjs/chunking';
|
|
3
|
+
import type { DocumentParser, FileStorage, PipelineClock } from '@eltjs/elt';
|
|
4
|
+
export type SourceKey = string | readonly [string, string, ...string[]];
|
|
5
|
+
export type Loading = {
|
|
6
|
+
readonly columns: readonly [string, ...string[]];
|
|
7
|
+
} | {
|
|
8
|
+
readonly file: string;
|
|
9
|
+
readonly files: FileStorage;
|
|
10
|
+
readonly parser: () => DocumentParser;
|
|
11
|
+
};
|
|
12
|
+
export type ChunkingOptions = {
|
|
13
|
+
readonly tokenizer: Tokenizer;
|
|
14
|
+
readonly maxTokens: number;
|
|
15
|
+
readonly overlapTokens: number;
|
|
16
|
+
} | 'none';
|
|
17
|
+
export type EmbeddingOptions = {
|
|
18
|
+
readonly model: EmbeddingModel;
|
|
19
|
+
readonly dimensions: number;
|
|
20
|
+
readonly clock: Pick<PipelineClock, 'setTimeout' | 'clearTimeout'>;
|
|
21
|
+
};
|
|
22
|
+
export declare function keyColumns(key: SourceKey): readonly [string, ...string[]];
|
|
23
|
+
export declare function refuseColumns({ vectorizer, key, metadata, contract, }: {
|
|
24
|
+
readonly vectorizer: string;
|
|
25
|
+
readonly key: SourceKey;
|
|
26
|
+
readonly metadata: readonly string[];
|
|
27
|
+
readonly contract: readonly string[];
|
|
28
|
+
}): void;
|
package/dist/options.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// The columns of the key, in order.
|
|
2
|
+
export function keyColumns(key) {
|
|
3
|
+
return typeof key === 'string' ? [key] : key;
|
|
4
|
+
}
|
|
5
|
+
// Refuses a key column listed twice, a metadata column listed twice, and a
|
|
6
|
+
// metadata column that has the name of a column of the contract, which it
|
|
7
|
+
// would replace. Names compare as the engine compares them: in ASCII case.
|
|
8
|
+
export function refuseColumns({ vectorizer, key, metadata, contract, }) {
|
|
9
|
+
const fold = (name) => name.replaceAll(/[A-Z]/g, (letter) => letter.toLowerCase());
|
|
10
|
+
const repeated = (names) => names.find((name, index) => names.slice(0, index).some((before) => fold(before) === fold(name)));
|
|
11
|
+
const repeatedKey = repeated(keyColumns(key));
|
|
12
|
+
if (repeatedKey !== undefined)
|
|
13
|
+
throw new TypeError(`Vectorizer ${vectorizer} lists the key column ${repeatedKey} twice`);
|
|
14
|
+
const repeatedMetadata = repeated(metadata);
|
|
15
|
+
if (repeatedMetadata !== undefined)
|
|
16
|
+
throw new TypeError(`Vectorizer ${vectorizer} lists the metadata column ${repeatedMetadata} twice`);
|
|
17
|
+
const taken = metadata.find((name) => contract.some((column) => fold(column) === fold(name)));
|
|
18
|
+
if (taken !== undefined)
|
|
19
|
+
throw new TypeError(`Vectorizer ${vectorizer} cannot give the metadata column ${taken}: the passages have a column of that name (${contract.join(', ')})`);
|
|
20
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { Chunking } from '@eltjs/chunking';
|
|
2
|
+
import { type LoadedRow, type RuleValues, TableRule, type TableRuleResult } from '@eltjs/elt';
|
|
3
|
+
import { type ChunkingOptions, type SourceKey } from './options.ts';
|
|
4
|
+
export declare function sourceOf(key: SourceKey): (row: LoadedRow) => string | null;
|
|
5
|
+
export declare function passageRule({ key, fields, chunking, }: {
|
|
6
|
+
readonly key: SourceKey;
|
|
7
|
+
readonly fields: readonly [string, ...string[]];
|
|
8
|
+
readonly chunking: ChunkingOptions;
|
|
9
|
+
}): PassageChunks | OnePart;
|
|
10
|
+
export declare class PassageChunks extends TableRule<string, Chunking['output'], Chunking['place']> {
|
|
11
|
+
#private;
|
|
12
|
+
readonly key: {
|
|
13
|
+
name: string;
|
|
14
|
+
description: string;
|
|
15
|
+
};
|
|
16
|
+
readonly output: Chunking['output'];
|
|
17
|
+
readonly place: Chunking['place'];
|
|
18
|
+
readonly batch: number;
|
|
19
|
+
readonly concurrency: number;
|
|
20
|
+
constructor({ key, fields, chunking, }: {
|
|
21
|
+
key: SourceKey;
|
|
22
|
+
fields: readonly [string, ...string[]];
|
|
23
|
+
chunking: Exclude<ChunkingOptions, 'none'>;
|
|
24
|
+
});
|
|
25
|
+
read(row: LoadedRow): {
|
|
26
|
+
readonly key: string;
|
|
27
|
+
readonly input: string;
|
|
28
|
+
} | null;
|
|
29
|
+
identity(): Promise<string>;
|
|
30
|
+
compute(texts: readonly string[]): Promise<readonly TableRuleResult<RuleValues<Chunking['output']> & RuleValues<Chunking['place']>>[]>;
|
|
31
|
+
}
|
|
32
|
+
declare const whole: {
|
|
33
|
+
readonly text: {
|
|
34
|
+
readonly type: 'text';
|
|
35
|
+
readonly description: 'The text of the passage: the whole text of its row.';
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
declare const span: {
|
|
39
|
+
readonly start: {
|
|
40
|
+
readonly type: 'integer';
|
|
41
|
+
readonly description: 'The offset of the first code point of the passage: 0.';
|
|
42
|
+
};
|
|
43
|
+
readonly end: {
|
|
44
|
+
readonly type: 'integer';
|
|
45
|
+
readonly description: 'The offset after the last code point of the passage: the count of code points of the text.';
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
export declare class OnePart extends TableRule<string, typeof whole, typeof span> {
|
|
49
|
+
#private;
|
|
50
|
+
readonly key: {
|
|
51
|
+
name: string;
|
|
52
|
+
description: string;
|
|
53
|
+
};
|
|
54
|
+
readonly output: {
|
|
55
|
+
readonly text: {
|
|
56
|
+
readonly type: 'text';
|
|
57
|
+
readonly description: 'The text of the passage: the whole text of its row.';
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
readonly place: {
|
|
61
|
+
readonly start: {
|
|
62
|
+
readonly type: 'integer';
|
|
63
|
+
readonly description: 'The offset of the first code point of the passage: 0.';
|
|
64
|
+
};
|
|
65
|
+
readonly end: {
|
|
66
|
+
readonly type: 'integer';
|
|
67
|
+
readonly description: 'The offset after the last code point of the passage: the count of code points of the text.';
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
readonly batch = 32;
|
|
71
|
+
readonly concurrency = 1;
|
|
72
|
+
constructor({ key, fields, }: {
|
|
73
|
+
key: SourceKey;
|
|
74
|
+
fields: readonly [string, ...string[]];
|
|
75
|
+
});
|
|
76
|
+
read(row: LoadedRow): {
|
|
77
|
+
readonly key: string;
|
|
78
|
+
readonly input: string;
|
|
79
|
+
} | null;
|
|
80
|
+
identity(): Promise<string>;
|
|
81
|
+
compute(texts: readonly string[]): Promise<readonly TableRuleResult<RuleValues<typeof whole> & RuleValues<typeof span>>[]>;
|
|
82
|
+
}
|
|
83
|
+
export {};
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { Chunking } from '@eltjs/chunking';
|
|
2
|
+
import { TableRule, rowText, } from '@eltjs/elt';
|
|
3
|
+
import manifest from '../package.json' with { type: 'json' };
|
|
4
|
+
import { keyColumns } from './options.js';
|
|
5
|
+
// The key column of the chunks of a vectorizer, which Passage.source reads.
|
|
6
|
+
const source = {
|
|
7
|
+
name: 'source',
|
|
8
|
+
description: '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.',
|
|
9
|
+
};
|
|
10
|
+
// Passage.source of a loaded row, or null when the row has no key: the
|
|
11
|
+
// plain value of a key of one column, or the JSON array of the values of a
|
|
12
|
+
// key of several columns, as the destination reads them back (ADR 0001).
|
|
13
|
+
export function sourceOf(key) {
|
|
14
|
+
if (typeof key === 'string')
|
|
15
|
+
return (row) => {
|
|
16
|
+
const value = row[key];
|
|
17
|
+
return typeof value === 'string' || typeof value === 'number'
|
|
18
|
+
? String(value)
|
|
19
|
+
: null;
|
|
20
|
+
};
|
|
21
|
+
const columns = keyColumns(key);
|
|
22
|
+
return (row) => {
|
|
23
|
+
const values = columns.map((column) => row[column]);
|
|
24
|
+
return values.some((value) => value === null || value === undefined)
|
|
25
|
+
? null
|
|
26
|
+
: JSON.stringify(values);
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
// The rule that cuts the text of the fields of each source row: the chunks of
|
|
30
|
+
// @eltjs/chunking, or one passage for each row.
|
|
31
|
+
export function passageRule({ key, fields, chunking, }) {
|
|
32
|
+
return chunking === 'none'
|
|
33
|
+
? new OnePart({ key, fields })
|
|
34
|
+
: new PassageChunks({ key, fields, chunking });
|
|
35
|
+
}
|
|
36
|
+
// The chunks of Chunking, keyed by the source of each row (a Decorator):
|
|
37
|
+
// Chunking cuts and names what made the chunks; the vectorizer reads the key,
|
|
38
|
+
// which may span several columns.
|
|
39
|
+
export class PassageChunks extends TableRule {
|
|
40
|
+
key = source;
|
|
41
|
+
output;
|
|
42
|
+
place;
|
|
43
|
+
batch;
|
|
44
|
+
concurrency;
|
|
45
|
+
#chunking;
|
|
46
|
+
#source;
|
|
47
|
+
#fields;
|
|
48
|
+
constructor({ key, fields, chunking, }) {
|
|
49
|
+
super();
|
|
50
|
+
this.#chunking = new Chunking({ ...chunking, key: source.name, fields });
|
|
51
|
+
this.output = this.#chunking.output;
|
|
52
|
+
this.place = this.#chunking.place;
|
|
53
|
+
this.batch = this.#chunking.batch;
|
|
54
|
+
this.concurrency = this.#chunking.concurrency;
|
|
55
|
+
this.#source = sourceOf(key);
|
|
56
|
+
this.#fields = Object.freeze([...fields]);
|
|
57
|
+
Object.freeze(this);
|
|
58
|
+
}
|
|
59
|
+
read(row) {
|
|
60
|
+
return readPassage(row, this.#source, this.#fields);
|
|
61
|
+
}
|
|
62
|
+
identity() {
|
|
63
|
+
return this.#chunking.identity();
|
|
64
|
+
}
|
|
65
|
+
compute(texts) {
|
|
66
|
+
return this.#chunking.compute(texts);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const whole = {
|
|
70
|
+
text: {
|
|
71
|
+
type: 'text',
|
|
72
|
+
description: 'The text of the passage: the whole text of its row.',
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
const span = {
|
|
76
|
+
start: {
|
|
77
|
+
type: 'integer',
|
|
78
|
+
description: 'The offset of the first code point of the passage: 0.',
|
|
79
|
+
},
|
|
80
|
+
end: {
|
|
81
|
+
type: 'integer',
|
|
82
|
+
description: 'The offset after the last code point of the passage: the count of code points of the text.',
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
// One passage for each row, its whole text, so the passages of every chunking
|
|
86
|
+
// are rows of one parts table and one SQL reads them (pgai chunking_none).
|
|
87
|
+
// Offsets count code points, as ContextWindow of @zukhruf/retrieval merges
|
|
88
|
+
// by them.
|
|
89
|
+
export class OnePart extends TableRule {
|
|
90
|
+
key = source;
|
|
91
|
+
output = whole;
|
|
92
|
+
place = span;
|
|
93
|
+
// Taking the text is synchronous work, as cutting it is.
|
|
94
|
+
batch = 32;
|
|
95
|
+
concurrency = 1;
|
|
96
|
+
#source;
|
|
97
|
+
#fields;
|
|
98
|
+
constructor({ key, fields, }) {
|
|
99
|
+
super();
|
|
100
|
+
this.#source = sourceOf(key);
|
|
101
|
+
this.#fields = Object.freeze([...fields]);
|
|
102
|
+
Object.freeze(this);
|
|
103
|
+
}
|
|
104
|
+
read(row) {
|
|
105
|
+
return readPassage(row, this.#source, this.#fields);
|
|
106
|
+
}
|
|
107
|
+
// The code makes every passage, so its version names them (elt ADR 0005).
|
|
108
|
+
async identity() {
|
|
109
|
+
return `${manifest.name}@${manifest.version} none`;
|
|
110
|
+
}
|
|
111
|
+
async compute(texts) {
|
|
112
|
+
return texts.map((text) => ({
|
|
113
|
+
parts: [{ text, start: 0, end: [...text].length }],
|
|
114
|
+
}));
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function readPassage(row, source, fields) {
|
|
118
|
+
const key = source(row);
|
|
119
|
+
if (key === null)
|
|
120
|
+
return null;
|
|
121
|
+
const text = rowText(row, fields);
|
|
122
|
+
return text === null ? null : { key, input: text };
|
|
123
|
+
}
|
|
@@ -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,99 @@
|
|
|
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
|
+
// The keyword index of the passages of a vectorizer: the table <name> keeps
|
|
6
|
+
// the id, source, seq and text of each passage, and the FTS5 table <index>
|
|
7
|
+
// indexes its text, as @zukhruf/retrieval's SqliteBM25Retriever reads it
|
|
8
|
+
// (its ADR 0004). Triggers keep the index in step with the table, and the
|
|
9
|
+
// table, the index and the triggers are one declaration, so a change to any
|
|
10
|
+
// of them makes all of them again, and the refill fills the index through the
|
|
11
|
+
// insert trigger (ADR 0002). A refresh writes the passages that changed and
|
|
12
|
+
// removes the ones that are gone in one transaction, so a reader sees the
|
|
13
|
+
// index of one refresh or of the next, never a part of one.
|
|
14
|
+
export class KeywordIndex extends DerivedDataset {
|
|
15
|
+
name;
|
|
16
|
+
// The FTS5 table, which the passages view joins by rowid.
|
|
17
|
+
index;
|
|
18
|
+
#into;
|
|
19
|
+
#parts;
|
|
20
|
+
#declaration;
|
|
21
|
+
// name: the table of the passages' keywords. index: its FTS5 table. parts:
|
|
22
|
+
// the raw parts table of the chunks, which keeps source, seq and text.
|
|
23
|
+
constructor({ into, name, index, parts, }) {
|
|
24
|
+
super();
|
|
25
|
+
this.name = name;
|
|
26
|
+
this.index = index;
|
|
27
|
+
this.#into = into;
|
|
28
|
+
this.#parts = parts;
|
|
29
|
+
const table = quote(name);
|
|
30
|
+
const fts = quote(index);
|
|
31
|
+
const removal = `INSERT INTO ${fts} (${fts}, "rowid", "text") VALUES ('delete', old."rowid", old."text");`;
|
|
32
|
+
const addition = `INSERT INTO ${fts} ("rowid", "text") VALUES (new."rowid", new."text");`;
|
|
33
|
+
this.#declaration = new Declaration([
|
|
34
|
+
`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`,
|
|
35
|
+
`CREATE VIRTUAL TABLE ${fts} USING fts5("text", content = '${name.replaceAll("'", "''")}')`,
|
|
36
|
+
`CREATE TRIGGER ${quote(`${name}_ai`)} AFTER INSERT ON ${table} BEGIN ${addition} END`,
|
|
37
|
+
`CREATE TRIGGER ${quote(`${name}_ad`)} AFTER DELETE ON ${table} BEGIN ${removal} END`,
|
|
38
|
+
`CREATE TRIGGER ${quote(`${name}_au`)} AFTER UPDATE ON ${table} BEGIN ${removal} ${addition} END`,
|
|
39
|
+
], { rows: 'replace' });
|
|
40
|
+
Object.freeze(this);
|
|
41
|
+
}
|
|
42
|
+
validate(connections) {
|
|
43
|
+
const made = connections
|
|
44
|
+
.filter(({ destination }) => destination instanceof SQLiteDestination &&
|
|
45
|
+
destination.path === this.#into.path)
|
|
46
|
+
.flatMap(({ steps }) => steps)
|
|
47
|
+
.flatMap(({ to }) => [to.name, to.raw])
|
|
48
|
+
.map((name) => name.toLowerCase());
|
|
49
|
+
for (const name of [this.name, this.index])
|
|
50
|
+
if (made.includes(name.toLowerCase()))
|
|
51
|
+
throw new TypeError(`Keyword index ${this.name} needs ${name}, which a copy of the pipeline makes`);
|
|
52
|
+
}
|
|
53
|
+
async refresh({ clock, signal, }) {
|
|
54
|
+
using database = openDestination(this.#into.path);
|
|
55
|
+
const status = new SQLiteDerivedStatus(database, this.name, 'computed', clock);
|
|
56
|
+
const table = quote(this.name);
|
|
57
|
+
const parts = quote(this.#parts);
|
|
58
|
+
let counts;
|
|
59
|
+
try {
|
|
60
|
+
counts = transaction(database, () => {
|
|
61
|
+
this.#declaration.apply(database);
|
|
62
|
+
// SQLite parses the ON CONFLICT of an INSERT of a SELECT only after
|
|
63
|
+
// a WHERE.
|
|
64
|
+
database
|
|
65
|
+
.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"`)
|
|
66
|
+
.run();
|
|
67
|
+
database
|
|
68
|
+
.prepare(`DELETE FROM ${table} WHERE NOT EXISTS (SELECT 1 FROM ${parts} AS p WHERE p."source" = ${table}."source" AND p."seq" = ${table}."seq")`)
|
|
69
|
+
.run();
|
|
70
|
+
const row = database
|
|
71
|
+
.prepare(`SELECT (SELECT count(*) FROM ${parts}) AS "inputs", (SELECT count(*) FROM ${table}) AS "computed"`)
|
|
72
|
+
.get();
|
|
73
|
+
return {
|
|
74
|
+
inputs: Number(row?.inputs),
|
|
75
|
+
computed: Number(row?.computed),
|
|
76
|
+
};
|
|
77
|
+
}, { mode: 'immediate' });
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
// The chunks have no parts table yet while they wait for their input,
|
|
81
|
+
// so the index waits with them.
|
|
82
|
+
if (this.#missingParts(error)) {
|
|
83
|
+
await status.waiting();
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
// A stop is not the dataset's failure.
|
|
87
|
+
if (signal?.aborted !== true)
|
|
88
|
+
await status.failed(errorMessage(error));
|
|
89
|
+
throw error;
|
|
90
|
+
}
|
|
91
|
+
await status.current({ ...counts, empty: 0, failed: 0, pending: 0 });
|
|
92
|
+
}
|
|
93
|
+
#missingParts(error) {
|
|
94
|
+
return (Error.isError(error) &&
|
|
95
|
+
/^no such table: (?:main\.)?(.+)$/
|
|
96
|
+
.exec(error.message)?.[1]
|
|
97
|
+
?.toLowerCase() === this.#parts.toLowerCase());
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -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,243 @@
|
|
|
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 { keyColumns, refuseColumns, } from '../options.js';
|
|
5
|
+
import { passageRule } from '../passage-rules.js';
|
|
6
|
+
import { KeywordIndex } from './keyword-index.js';
|
|
7
|
+
// The columns of the passages of @zukhruf/retrieval on SQLite, which no
|
|
8
|
+
// metadata column may take (its ADR 0001).
|
|
9
|
+
const contractColumns = [
|
|
10
|
+
'rowid',
|
|
11
|
+
'id',
|
|
12
|
+
'source',
|
|
13
|
+
'seq',
|
|
14
|
+
'start',
|
|
15
|
+
'end',
|
|
16
|
+
'text',
|
|
17
|
+
];
|
|
18
|
+
// One declaration that keeps the passage contract of @zukhruf/retrieval in
|
|
19
|
+
// step with what a pipeline loads into one SQLite file, as pgai's
|
|
20
|
+
// create_vectorizer does in Postgres: the passages of each source row with
|
|
21
|
+
// its metadata, the vector of each passage with the identity of its model,
|
|
22
|
+
// and a keyword index of the passages (ADR 0001). Each relation is a member
|
|
23
|
+
// that the pipeline refreshes in order, so a member's failure fails only the
|
|
24
|
+
// vectorizer (elt ADR 0034). Every relation's name starts with name.
|
|
25
|
+
export class Vectorizer extends CompositeDataset {
|
|
26
|
+
name;
|
|
27
|
+
members;
|
|
28
|
+
contract;
|
|
29
|
+
// The file of the relations, which a host opens for the store.
|
|
30
|
+
into;
|
|
31
|
+
#from;
|
|
32
|
+
#key;
|
|
33
|
+
#loading;
|
|
34
|
+
#metadata;
|
|
35
|
+
// name: the start of the name of each relation. key: the column, or
|
|
36
|
+
// columns, that identify a source row. loading: what text of a row the
|
|
37
|
+
// passages cut. metadata: the columns of the source row that each passage
|
|
38
|
+
// gives beside its text; none when absent (Airbyte metadata_fields).
|
|
39
|
+
constructor(options) {
|
|
40
|
+
super();
|
|
41
|
+
const { name, description, key, loading, chunking, embedding } = options;
|
|
42
|
+
const metadata = options.metadata ?? [];
|
|
43
|
+
refuseColumns({
|
|
44
|
+
vectorizer: name,
|
|
45
|
+
key,
|
|
46
|
+
metadata,
|
|
47
|
+
contract: contractColumns,
|
|
48
|
+
});
|
|
49
|
+
this.name = name;
|
|
50
|
+
this.into = 'into' in options ? options.into : options.from.into;
|
|
51
|
+
this.#from = options.from;
|
|
52
|
+
this.#key = key;
|
|
53
|
+
this.#loading = loading;
|
|
54
|
+
this.#metadata = Object.freeze([...metadata]);
|
|
55
|
+
const into = this.into;
|
|
56
|
+
const columns = keyColumns(key);
|
|
57
|
+
const source = options.from instanceof SQLiteTable
|
|
58
|
+
? quote(options.from.raw)
|
|
59
|
+
: quote(options.from.name);
|
|
60
|
+
const keyDescriptions = Object.fromEntries(columns.map((column) => [
|
|
61
|
+
column,
|
|
62
|
+
`The ${column} column of the key of the source row.`,
|
|
63
|
+
]));
|
|
64
|
+
const names = {
|
|
65
|
+
text: `${name}_text`,
|
|
66
|
+
documents: `${name}_documents`,
|
|
67
|
+
chunks: `${name}_chunks`,
|
|
68
|
+
keywords: `${name}_keywords`,
|
|
69
|
+
passages: `${name}_passages`,
|
|
70
|
+
chunkTexts: `${name}_chunk_texts`,
|
|
71
|
+
chunkVectors: `${name}_chunk_vectors`,
|
|
72
|
+
passageVectors: `${name}_passage_vectors`,
|
|
73
|
+
status: `${name}_status`,
|
|
74
|
+
index: `${name}_passages_fts`,
|
|
75
|
+
};
|
|
76
|
+
const rawParts = rawTable(`${names.chunks}_parts`);
|
|
77
|
+
const parts = quote(rawParts);
|
|
78
|
+
const vectors = quote(rawTable(names.chunkVectors));
|
|
79
|
+
// The text of a stored file is the input of the chunks through a view
|
|
80
|
+
// keyed by the source key, since rows can share a file (elt ADR 0027).
|
|
81
|
+
let files = [];
|
|
82
|
+
let input = options.from;
|
|
83
|
+
if ('file' in loading) {
|
|
84
|
+
const text = new ComputedDataset({
|
|
85
|
+
into,
|
|
86
|
+
name: names.text,
|
|
87
|
+
description: `The text of each file of the vectorizer ${name}. ${description}`,
|
|
88
|
+
from: [options.from],
|
|
89
|
+
compute: new DocumentText({
|
|
90
|
+
parser: loading.parser,
|
|
91
|
+
files: loading.files,
|
|
92
|
+
column: loading.file,
|
|
93
|
+
}),
|
|
94
|
+
});
|
|
95
|
+
input = new View({
|
|
96
|
+
into,
|
|
97
|
+
name: names.documents,
|
|
98
|
+
description: `The text of the file of each source row of the vectorizer ${name}. ${description}`,
|
|
99
|
+
columns: {
|
|
100
|
+
...keyDescriptions,
|
|
101
|
+
content: 'The text the parser extracted from the file.',
|
|
102
|
+
},
|
|
103
|
+
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'`,
|
|
104
|
+
});
|
|
105
|
+
files = [text, input];
|
|
106
|
+
}
|
|
107
|
+
const chunks = new ComputedDataset({
|
|
108
|
+
into,
|
|
109
|
+
name: names.chunks,
|
|
110
|
+
description: `The passages of the vectorizer ${name}, one row for each source row. ${description}`,
|
|
111
|
+
from: [input],
|
|
112
|
+
compute: passageRule({
|
|
113
|
+
key,
|
|
114
|
+
fields: 'columns' in loading ? loading.columns : ['content'],
|
|
115
|
+
chunking,
|
|
116
|
+
}),
|
|
117
|
+
});
|
|
118
|
+
const keywords = new KeywordIndex({
|
|
119
|
+
into,
|
|
120
|
+
name: names.keywords,
|
|
121
|
+
index: names.index,
|
|
122
|
+
parts: rawParts,
|
|
123
|
+
});
|
|
124
|
+
const join = typeof key === 'string'
|
|
125
|
+
? `s.${quote(key)} = p."source"`
|
|
126
|
+
: columns
|
|
127
|
+
.map((column, index) => `s.${quote(column)} = json_extract(p."source", '$[${index}]')`)
|
|
128
|
+
.join(' AND ');
|
|
129
|
+
const passages = new View({
|
|
130
|
+
into,
|
|
131
|
+
name: names.passages,
|
|
132
|
+
description: `The passages of the vectorizer ${name}, as @zukhruf/retrieval reads them. ${description}`,
|
|
133
|
+
columns: {
|
|
134
|
+
rowid: 'The rowid of the passage in the keyword index.',
|
|
135
|
+
id: 'The id of the passage: its source, a colon and its seq.',
|
|
136
|
+
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.',
|
|
137
|
+
seq: 'The place of the passage in its source row, from 0.',
|
|
138
|
+
start: 'The offset of the first code point of the passage in the text of its row, from 0.',
|
|
139
|
+
end: 'The offset after the last code point of the passage in the text of its row.',
|
|
140
|
+
text: 'The text of the passage.',
|
|
141
|
+
...Object.fromEntries(metadata.map((column) => [
|
|
142
|
+
column,
|
|
143
|
+
`The ${column} column of the source row.`,
|
|
144
|
+
])),
|
|
145
|
+
},
|
|
146
|
+
sql: `SELECT k."rowid" AS "rowid", k."id", p."source", p."seq", p."start", p."end", p."text"${metadata
|
|
147
|
+
.map((column) => `, s.${quote(column)} AS ${quote(column)}`)
|
|
148
|
+
.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}`,
|
|
149
|
+
});
|
|
150
|
+
// The text of each part by its part hash. Parts with one text share a
|
|
151
|
+
// part hash, and a computed dataset keeps the first input of a key, so a
|
|
152
|
+
// text is embedded once with no DISTINCT.
|
|
153
|
+
const chunkTexts = new View({
|
|
154
|
+
into,
|
|
155
|
+
name: names.chunkTexts,
|
|
156
|
+
description: `The text of each passage of the vectorizer ${name}, by its part hash. ${description}`,
|
|
157
|
+
columns: {
|
|
158
|
+
id: 'The part hash of the passage.',
|
|
159
|
+
text: 'The text of the passage.',
|
|
160
|
+
},
|
|
161
|
+
sql: `SELECT "part_hash" AS "id", "text" FROM ${quote(`${names.chunks}_parts`)}`,
|
|
162
|
+
});
|
|
163
|
+
const chunkVectors = new ComputedDataset({
|
|
164
|
+
into,
|
|
165
|
+
name: names.chunkVectors,
|
|
166
|
+
description: `The vector of each passage text of the vectorizer ${name}. ${description}`,
|
|
167
|
+
from: [chunkTexts],
|
|
168
|
+
compute: new Embedding({ ...embedding, key: 'id', fields: ['text'] }),
|
|
169
|
+
});
|
|
170
|
+
// A vector whose model failed is no answer to a search, so only computed
|
|
171
|
+
// ones show. The rule names the model as the retriever reads it.
|
|
172
|
+
const passageVectors = new View({
|
|
173
|
+
into,
|
|
174
|
+
name: names.passageVectors,
|
|
175
|
+
description: `The vector of each passage of the vectorizer ${name}, as @zukhruf/retrieval reads them. ${description}`,
|
|
176
|
+
columns: {
|
|
177
|
+
id: 'The id of the passage.',
|
|
178
|
+
vector: 'The unit vector of the passage text, float32 values.',
|
|
179
|
+
model: 'The model that made the vector: <provider>/<model id> (<n> dimensions).',
|
|
180
|
+
},
|
|
181
|
+
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'`,
|
|
182
|
+
});
|
|
183
|
+
const leaves = [
|
|
184
|
+
...files,
|
|
185
|
+
chunks,
|
|
186
|
+
keywords,
|
|
187
|
+
passages,
|
|
188
|
+
chunkTexts,
|
|
189
|
+
chunkVectors,
|
|
190
|
+
passageVectors,
|
|
191
|
+
];
|
|
192
|
+
const literal = (text) => `'${text.replaceAll("'", "''")}'`;
|
|
193
|
+
const status = new View({
|
|
194
|
+
into,
|
|
195
|
+
name: names.status,
|
|
196
|
+
description: `How far the relations of the vectorizer ${name} are in step with their source. ${description}`,
|
|
197
|
+
columns: {
|
|
198
|
+
state: 'failed when a relation failed, waiting when one waits for its input, refreshing when one refreshes, else current.',
|
|
199
|
+
as_of: 'The earliest as_of of the relations: the data that every relation holds. NULL until each holds some.',
|
|
200
|
+
pending_sources: 'The source rows that wait for their passages.',
|
|
201
|
+
pending_vectors: 'The passage texts that wait for their vectors.',
|
|
202
|
+
},
|
|
203
|
+
sql: `WITH "members" ("dataset") AS (VALUES ${leaves
|
|
204
|
+
.map(({ name: member }) => `(${literal(member)})`)
|
|
205
|
+
.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"`,
|
|
206
|
+
});
|
|
207
|
+
this.members = Object.freeze([...leaves, status]);
|
|
208
|
+
this.contract = Object.freeze({
|
|
209
|
+
passages: names.passages,
|
|
210
|
+
vectors: names.passageVectors,
|
|
211
|
+
index: names.index,
|
|
212
|
+
});
|
|
213
|
+
Object.freeze(this);
|
|
214
|
+
}
|
|
215
|
+
// A source table must be one that a copy loads into the file of the
|
|
216
|
+
// vectorizer, and the copy's stream must declare each column that the
|
|
217
|
+
// vectorizer reads. A View's columns are its own SQL's, so its first
|
|
218
|
+
// refresh tells, as for any view.
|
|
219
|
+
validate(connections) {
|
|
220
|
+
const from = this.#from;
|
|
221
|
+
if (!(from instanceof SQLiteTable))
|
|
222
|
+
return;
|
|
223
|
+
const copy = connections
|
|
224
|
+
.filter(({ destination }) => destination instanceof SQLiteDestination &&
|
|
225
|
+
destination.path === this.into.path)
|
|
226
|
+
.flatMap(({ steps }) => steps)
|
|
227
|
+
.find(({ to }) => to === from);
|
|
228
|
+
if (copy === undefined)
|
|
229
|
+
throw new TypeError(`Vectorizer ${this.name} reads ${from.name}, which no copy of the pipeline loads into ${this.into.path}`);
|
|
230
|
+
const declared = new Set([
|
|
231
|
+
...Object.keys(copy.from.jsonSchema.properties ?? {}),
|
|
232
|
+
...from.columns.map(({ name }) => name),
|
|
233
|
+
]);
|
|
234
|
+
const loading = this.#loading;
|
|
235
|
+
for (const column of [
|
|
236
|
+
...keyColumns(this.#key),
|
|
237
|
+
...this.#metadata,
|
|
238
|
+
...('columns' in loading ? loading.columns : [loading.file]),
|
|
239
|
+
])
|
|
240
|
+
if (!declared.has(column))
|
|
241
|
+
throw new TypeError(`Vectorizer ${this.name} reads the column ${column} of ${from.name}, which the stream ${copy.from.name} does not declare`);
|
|
242
|
+
}
|
|
243
|
+
}
|
package/dist/sqlite.d.ts
ADDED
package/dist/sqlite.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { Vectorizer } from './sqlite/vectorizer.js';
|