@eltjs/vectorizer 0.13.7 → 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.
- package/README.md +364 -3
- package/dist/copies.d.ts +2 -0
- package/dist/copies.js +8 -0
- package/dist/declared-columns.d.ts +18 -0
- package/dist/declared-columns.js +23 -0
- package/dist/passage-rules.d.ts +16 -9
- package/dist/passage-rules.js +49 -16
- package/dist/postgresql/keyword-index.d.ts +18 -0
- package/dist/postgresql/keyword-index.js +106 -0
- package/dist/postgresql/vectorizer.d.ts +45 -0
- package/dist/postgresql/vectorizer.js +260 -0
- package/dist/postgresql.d.ts +2 -0
- package/dist/postgresql.js +1 -0
- package/dist/sqlite/keyword-index.js +2 -3
- package/dist/sqlite/vectorizer.js +12 -19
- package/dist/sqlserver/keyword-index.d.ts +19 -0
- package/dist/sqlserver/keyword-index.js +169 -0
- package/dist/sqlserver/vectorizer.d.ts +44 -0
- package/dist/sqlserver/vectorizer.js +253 -0
- package/dist/sqlserver.d.ts +2 -0
- package/dist/sqlserver.js +1 -0
- package/package.json +24 -8
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { hash } from 'node:crypto';
|
|
2
|
+
import postgres from 'postgres';
|
|
3
|
+
import { DerivedDataset, errorMessage, } from '@eltjs/elt';
|
|
4
|
+
import { PostgresDerivedStatus, PostgresDestination, inWarehouse, quote, rawTable, warehouse, } from '@eltjs/elt-postgresql';
|
|
5
|
+
import { copiesInto } from '../copies.js';
|
|
6
|
+
// The keyword index of the passages of a vectorizer: the table
|
|
7
|
+
// _warehouse.raw_<name> keeps the id, source, seq and text of each passage,
|
|
8
|
+
// and its keywords column, the tsvector that Postgres generates from the text
|
|
9
|
+
// with the text search configuration, which a GIN index indexes, as
|
|
10
|
+
// @zukhruf/retrieval's PgvectorKeywordRetriever reads it (its ADR 0004). The
|
|
11
|
+
// table and its index are one declaration, whose hash the table keeps as its
|
|
12
|
+
// comment: a change of the declaration, such as another configuration, drops
|
|
13
|
+
// the table, and each view over it, and makes it again, and the refill gives
|
|
14
|
+
// each passage its keywords in the new configuration (ADR 0002). A refresh
|
|
15
|
+
// writes the passages that changed and removes the ones that are gone in one
|
|
16
|
+
// transaction, so a reader sees the index of one refresh or of the next,
|
|
17
|
+
// never a part of one.
|
|
18
|
+
export class KeywordIndex extends DerivedDataset {
|
|
19
|
+
name;
|
|
20
|
+
// The table of the index, which the passages view reads, and which a view
|
|
21
|
+
// after it waits for while the index waits.
|
|
22
|
+
qualifiedName;
|
|
23
|
+
#into;
|
|
24
|
+
#table;
|
|
25
|
+
#parts;
|
|
26
|
+
#partsTable;
|
|
27
|
+
#declaration;
|
|
28
|
+
#declared;
|
|
29
|
+
// name: the name of the index, whose table is raw_<name>. parts: the raw
|
|
30
|
+
// parts table of the chunks, which keeps source, seq and text, in
|
|
31
|
+
// _warehouse. configuration: the text search configuration of the
|
|
32
|
+
// keywords.
|
|
33
|
+
constructor({ into, name, parts, configuration, }) {
|
|
34
|
+
super();
|
|
35
|
+
this.name = name;
|
|
36
|
+
this.#into = into;
|
|
37
|
+
const raw = rawTable(name);
|
|
38
|
+
this.#table = raw;
|
|
39
|
+
this.qualifiedName = `${warehouse}.${raw}`;
|
|
40
|
+
this.#parts = inWarehouse(parts);
|
|
41
|
+
this.#partsTable = `${warehouse}.${parts}`;
|
|
42
|
+
const table = inWarehouse(raw);
|
|
43
|
+
this.#declaration = Object.freeze([
|
|
44
|
+
`CREATE TABLE ${table} ("id" text COLLATE "C" PRIMARY KEY, "source" text NOT NULL, "seq" integer NOT NULL, "text" text NOT NULL, "keywords" tsvector GENERATED ALWAYS AS (to_tsvector('${configuration.replaceAll("'", "''")}'::regconfig, "text")) STORED, UNIQUE ("source", "seq"))`,
|
|
45
|
+
`CREATE INDEX ${quote(`${raw}_gin`)} ON ${table} USING gin ("keywords")`,
|
|
46
|
+
]);
|
|
47
|
+
this.#declared = hash('sha256', this.#declaration.join(';\n'));
|
|
48
|
+
Object.freeze(this);
|
|
49
|
+
}
|
|
50
|
+
validate(connections) {
|
|
51
|
+
const made = copiesInto(connections, (destination) => destination instanceof PostgresDestination &&
|
|
52
|
+
destination.url === this.#into.url).map(({ to }) => to.raw);
|
|
53
|
+
if (made.includes(this.#table))
|
|
54
|
+
throw new TypeError(`Keyword index ${this.name} needs ${this.qualifiedName}, which a copy of the pipeline makes`);
|
|
55
|
+
}
|
|
56
|
+
async refresh({ clock, signal, }) {
|
|
57
|
+
await using stack = new AsyncDisposableStack();
|
|
58
|
+
const sql = postgres(this.#into.url, {
|
|
59
|
+
max: 1,
|
|
60
|
+
onnotice: () => { },
|
|
61
|
+
connection: { application_name: 'elt-derived' },
|
|
62
|
+
});
|
|
63
|
+
stack.defer(() => sql.end({ timeout: 5 }));
|
|
64
|
+
const status = new PostgresDerivedStatus(sql, this.qualifiedName, 'computed', clock);
|
|
65
|
+
const table = inWarehouse(this.#table);
|
|
66
|
+
const parts = this.#parts;
|
|
67
|
+
let counts;
|
|
68
|
+
try {
|
|
69
|
+
counts = await sql.begin(async (transaction) => {
|
|
70
|
+
// Two refreshes of one index take turns, so neither makes the table
|
|
71
|
+
// while the other makes it.
|
|
72
|
+
await transaction `SELECT pg_advisory_xact_lock(hashtextextended(${`elt:${this.qualifiedName}`}, 0))`;
|
|
73
|
+
const [stored] = await transaction `
|
|
74
|
+
SELECT obj_description(to_regclass(${this.qualifiedName}), 'pg_class') AS "declared"`;
|
|
75
|
+
if (stored?.declared !== this.#declared) {
|
|
76
|
+
await transaction.unsafe(`DROP TABLE IF EXISTS ${table} CASCADE`);
|
|
77
|
+
for (const statement of this.#declaration)
|
|
78
|
+
await transaction.unsafe(statement);
|
|
79
|
+
await transaction.unsafe(`COMMENT ON TABLE ${table} IS '${this.#declared}'`);
|
|
80
|
+
}
|
|
81
|
+
await transaction.unsafe(`INSERT INTO ${table} ("id", "source", "seq", "text") SELECT p."source" || ':' || p."seq", p."source", p."seq", p."text" FROM ${parts} AS p ON CONFLICT ("id") DO UPDATE SET "text" = excluded."text" WHERE ${table}."text" IS DISTINCT FROM excluded."text"`);
|
|
82
|
+
await transaction.unsafe(`DELETE FROM ${table} AS k WHERE NOT EXISTS (SELECT 1 FROM ${parts} AS p WHERE p."source" = k."source" AND p."seq" = k."seq")`);
|
|
83
|
+
const [row] = await transaction.unsafe(`SELECT (SELECT count(*) FROM ${parts})::int AS "inputs", (SELECT count(*) FROM ${table})::int AS "computed"`);
|
|
84
|
+
return { inputs: Number(row?.inputs), computed: Number(row?.computed) };
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
// The chunks have no parts table yet while they wait for their input,
|
|
89
|
+
// so the index waits with them.
|
|
90
|
+
if (this.#missingParts(error)) {
|
|
91
|
+
await status.waiting();
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
// A stop is not the dataset's failure.
|
|
95
|
+
if (signal?.aborted !== true)
|
|
96
|
+
await status.failed(errorMessage(error));
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
await status.current({ ...counts, empty: 0, failed: 0, pending: 0 });
|
|
100
|
+
}
|
|
101
|
+
#missingParts(error) {
|
|
102
|
+
return (error instanceof postgres.PostgresError &&
|
|
103
|
+
error.code === '42P01' &&
|
|
104
|
+
error.message === `relation "${this.#partsTable}" does not exist`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { CompositeDataset, type Connection, type DerivedDataset } from '@eltjs/elt';
|
|
2
|
+
import { type Hnsw, PostgresDestination, PostgresTable, View } from '@eltjs/elt-postgresql';
|
|
3
|
+
import { type ChunkingOptions, type EmbeddingOptions, type Loading, type SourceKey } from '../options.ts';
|
|
4
|
+
type Origin = {
|
|
5
|
+
readonly into: PostgresDestination;
|
|
6
|
+
readonly from: PostgresTable;
|
|
7
|
+
} | {
|
|
8
|
+
readonly from: View;
|
|
9
|
+
};
|
|
10
|
+
export type PostgresContract = {
|
|
11
|
+
readonly schema: string;
|
|
12
|
+
readonly passages: string;
|
|
13
|
+
readonly vectors: string;
|
|
14
|
+
readonly index: {
|
|
15
|
+
readonly column: string;
|
|
16
|
+
readonly configuration: string;
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
export declare class Vectorizer extends CompositeDataset<PostgresTable> {
|
|
20
|
+
#private;
|
|
21
|
+
readonly name: string;
|
|
22
|
+
readonly members: readonly [
|
|
23
|
+
DerivedDataset<PostgresTable>,
|
|
24
|
+
...DerivedDataset<PostgresTable>[]
|
|
25
|
+
];
|
|
26
|
+
readonly contract: PostgresContract;
|
|
27
|
+
readonly into: PostgresDestination;
|
|
28
|
+
constructor(options: Origin & {
|
|
29
|
+
readonly name: string;
|
|
30
|
+
readonly description: string;
|
|
31
|
+
readonly key: SourceKey;
|
|
32
|
+
readonly loading: Loading;
|
|
33
|
+
readonly chunking: ChunkingOptions;
|
|
34
|
+
readonly embedding: EmbeddingOptions;
|
|
35
|
+
readonly metadata?: readonly string[];
|
|
36
|
+
readonly keywords?: {
|
|
37
|
+
readonly configuration?: string;
|
|
38
|
+
};
|
|
39
|
+
readonly indexing?: {
|
|
40
|
+
readonly vectors: Hnsw | 'none';
|
|
41
|
+
};
|
|
42
|
+
});
|
|
43
|
+
validate(connections: readonly Connection<PostgresTable>[]): void;
|
|
44
|
+
}
|
|
45
|
+
export {};
|
|
@@ -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 @@
|
|
|
1
|
+
export { Vectorizer } from './postgresql/vectorizer.js';
|
|
@@ -2,6 +2,7 @@ import { Declaration } from '@zukhruf/sqlite-drift';
|
|
|
2
2
|
import { transaction } from '@zukhruf/sqlite-transaction';
|
|
3
3
|
import { DerivedDataset, errorMessage, } from '@eltjs/elt';
|
|
4
4
|
import { SQLiteDerivedStatus, SQLiteDestination, openDestination, quote, } from '@eltjs/elt-sqlite';
|
|
5
|
+
import { copiesInto } from '../copies.js';
|
|
5
6
|
// The keyword index of the passages of a vectorizer: the table <name> keeps
|
|
6
7
|
// the id, source, seq and text of each passage, and the FTS5 table <index>
|
|
7
8
|
// indexes its text, as @zukhruf/retrieval's SqliteBM25Retriever reads it
|
|
@@ -40,10 +41,8 @@ export class KeywordIndex extends DerivedDataset {
|
|
|
40
41
|
Object.freeze(this);
|
|
41
42
|
}
|
|
42
43
|
validate(connections) {
|
|
43
|
-
const made = connections
|
|
44
|
-
.filter(({ destination }) => destination instanceof SQLiteDestination &&
|
|
44
|
+
const made = copiesInto(connections, (destination) => destination instanceof SQLiteDestination &&
|
|
45
45
|
destination.path === this.#into.path)
|
|
46
|
-
.flatMap(({ steps }) => steps)
|
|
47
46
|
.flatMap(({ to }) => [to.name, to.raw])
|
|
48
47
|
.map((name) => name.toLowerCase());
|
|
49
48
|
for (const name of [this.name, this.index])
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { CompositeDataset, DocumentText, } from '@eltjs/elt';
|
|
2
2
|
import { ComputedDataset, SQLiteDestination, SQLiteTable, View, quote, rawTable, } from '@eltjs/elt-sqlite';
|
|
3
3
|
import { Embedding } from '@eltjs/embedding';
|
|
4
|
+
import { copiesInto } from '../copies.js';
|
|
5
|
+
import { refuseUndeclaredColumns } from '../declared-columns.js';
|
|
4
6
|
import { keyColumns, refuseColumns, } from '../options.js';
|
|
5
7
|
import { passageRule } from '../passage-rules.js';
|
|
6
8
|
import { KeywordIndex } from './keyword-index.js';
|
|
@@ -220,24 +222,15 @@ export class Vectorizer extends CompositeDataset {
|
|
|
220
222
|
const from = this.#from;
|
|
221
223
|
if (!(from instanceof SQLiteTable))
|
|
222
224
|
return;
|
|
223
|
-
|
|
224
|
-
.
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
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`);
|
|
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
|
+
});
|
|
242
235
|
}
|
|
243
236
|
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type Connection, DerivedDataset, type PipelineClock } from '@eltjs/elt';
|
|
2
|
+
import { type SqlServerDestination, type SqlServerTable } from '@eltjs/elt-sqlserver';
|
|
3
|
+
export declare const mostIdCharacters = 450;
|
|
4
|
+
export declare class KeywordIndex extends DerivedDataset<SqlServerTable> {
|
|
5
|
+
#private;
|
|
6
|
+
readonly name: string;
|
|
7
|
+
readonly qualifiedName: string;
|
|
8
|
+
constructor({ into, name, parts, language, }: {
|
|
9
|
+
into: SqlServerDestination;
|
|
10
|
+
name: string;
|
|
11
|
+
parts: string;
|
|
12
|
+
language: number;
|
|
13
|
+
});
|
|
14
|
+
validate(connections: readonly Connection<SqlServerTable>[]): void;
|
|
15
|
+
refresh({ clock, signal, }: {
|
|
16
|
+
readonly clock: PipelineClock;
|
|
17
|
+
readonly signal?: AbortSignal;
|
|
18
|
+
}): Promise<void>;
|
|
19
|
+
}
|