@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.
- package/LICENSE +202 -0
- package/README.md +823 -2
- 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/options.d.ts +28 -0
- package/dist/options.js +20 -0
- package/dist/passage-rules.d.ts +90 -0
- package/dist/passage-rules.js +156 -0
- 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.d.ts +18 -0
- package/dist/sqlite/keyword-index.js +98 -0
- package/dist/sqlite/vectorizer.d.ts +35 -0
- package/dist/sqlite/vectorizer.js +236 -0
- package/dist/sqlite.d.ts +2 -0
- package/dist/sqlite.js +1 -0
- 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 +74 -4
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { hash } from 'node:crypto';
|
|
2
|
+
import { poll } from '@zukhruf/async';
|
|
3
|
+
import { DerivedDataset, errorMessage, } from '@eltjs/elt';
|
|
4
|
+
import { SqlServerDerivedStatus, SqlServerSetupError, connectDestination, inMarts, inWarehouse, literal, marts, quote, sameDatabase, warehouse, } from '@eltjs/elt-sqlserver';
|
|
5
|
+
import { copiesInto } from '../copies.js';
|
|
6
|
+
// The collation of every passage id and source: UTF-16 code units, so a and A
|
|
7
|
+
// are two passages under a case-insensitive database, as @zukhruf/retrieval
|
|
8
|
+
// compares them.
|
|
9
|
+
const binary = 'Latin1_General_100_BIN2';
|
|
10
|
+
// The most characters of a passage id: a full-text key holds at most 900
|
|
11
|
+
// bytes, and NVARCHAR keeps two bytes for each UTF-16 unit. The chunks of the
|
|
12
|
+
// vectorizer fail an input whose ids are longer, so no part of it reaches
|
|
13
|
+
// the index.
|
|
14
|
+
export const mostIdCharacters = 450;
|
|
15
|
+
// The error of a full-text statement on a server with no Full-Text Search
|
|
16
|
+
// (Microsoft, "Database engine events and errors 7000 to 7999": "Full-Text
|
|
17
|
+
// Search is not installed, or a full-text component cannot be loaded.").
|
|
18
|
+
const noFullTextSearch = 7609;
|
|
19
|
+
// The error of a relation that no schema has.
|
|
20
|
+
const invalidObject = 208;
|
|
21
|
+
// How long the member waits between two reads of the state of the full-text
|
|
22
|
+
// index.
|
|
23
|
+
const populationPoll = 250;
|
|
24
|
+
const numberOf = (error) => Error.isError(error) && 'number' in error ? error.number : undefined;
|
|
25
|
+
// The keyword index of the passages of a vectorizer on SQL Server: the base
|
|
26
|
+
// table marts.<name> keeps the id, source, seq and text of each passage, and
|
|
27
|
+
// a full-text index on its text, with the id as its key, is what
|
|
28
|
+
// @zukhruf/retrieval's SqlServerKeywordRetriever reads through CONTAINSTABLE
|
|
29
|
+
// (its ADR 0004). The table is in marts, so a reader with SELECT on marts
|
|
30
|
+
// searches it (ADR 0002). SQL Server makes a full-text catalog and index only
|
|
31
|
+
// outside a transaction (error 574), so the member makes them as statements
|
|
32
|
+
// of their own, and the table keeps the hash of its declaration as the
|
|
33
|
+
// extended property elt_declaration: another declaration, such as another
|
|
34
|
+
// language, makes the table and its index again, and the refill gives each
|
|
35
|
+
// passage to the new index. A refresh writes the passages in one MERGE, then
|
|
36
|
+
// waits until the index has no population running and no change waiting, so
|
|
37
|
+
// current means that a search finds each passage.
|
|
38
|
+
export class KeywordIndex extends DerivedDataset {
|
|
39
|
+
name;
|
|
40
|
+
// The table, which the passages view reads, and which a view after it
|
|
41
|
+
// waits for while the index waits.
|
|
42
|
+
qualifiedName;
|
|
43
|
+
#into;
|
|
44
|
+
#table;
|
|
45
|
+
#parts;
|
|
46
|
+
#partsName;
|
|
47
|
+
#catalog;
|
|
48
|
+
#declaration;
|
|
49
|
+
#declared;
|
|
50
|
+
// name: the table of the passages' keywords in marts. parts: the raw parts
|
|
51
|
+
// table of the chunks in _warehouse, which keeps source, seq and text.
|
|
52
|
+
// language: the LCID of the word breaker of the full-text index, such as
|
|
53
|
+
// 1033 for English.
|
|
54
|
+
constructor({ into, name, parts, language, }) {
|
|
55
|
+
super();
|
|
56
|
+
if (!Number.isSafeInteger(language) || language < 0)
|
|
57
|
+
throw new RangeError(`Keyword index ${name} needs the LCID of a language, an integer of 0 or more; it got ${language}`);
|
|
58
|
+
this.name = name;
|
|
59
|
+
this.qualifiedName = `${marts}.${name}`;
|
|
60
|
+
this.#into = into;
|
|
61
|
+
this.#table = inMarts(name);
|
|
62
|
+
this.#parts = inWarehouse(parts);
|
|
63
|
+
this.#partsName = `${warehouse}.${parts}`;
|
|
64
|
+
this.#catalog = quote(name);
|
|
65
|
+
const key = quote(`pk_elt_${hash('sha256', this.qualifiedName).slice(0, 16)}`);
|
|
66
|
+
this.#declaration = Object.freeze([
|
|
67
|
+
`CREATE TABLE ${this.#table} ([id] NVARCHAR(${mostIdCharacters}) COLLATE ${binary} NOT NULL CONSTRAINT ${key} PRIMARY KEY, [source] NVARCHAR(${mostIdCharacters}) COLLATE ${binary} NOT NULL, [seq] INT NOT NULL, [text] NVARCHAR(MAX) NOT NULL)`,
|
|
68
|
+
`CREATE FULLTEXT INDEX ON ${this.#table} ([text] LANGUAGE ${language}) KEY INDEX ${key} ON ${this.#catalog} WITH STOPLIST = OFF, CHANGE_TRACKING AUTO`,
|
|
69
|
+
]);
|
|
70
|
+
this.#declared = hash('sha256', this.#declaration.join(';\n'));
|
|
71
|
+
Object.freeze(this);
|
|
72
|
+
}
|
|
73
|
+
validate(connections) {
|
|
74
|
+
const made = copiesInto(connections, (destination) => sameDatabase(destination, this.#into)).map(({ to }) => `${marts}.${to.name}`.toLowerCase());
|
|
75
|
+
if (made.includes(this.qualifiedName.toLowerCase()))
|
|
76
|
+
throw new TypeError(`Keyword index ${this.name} needs ${this.qualifiedName}, which a copy of the pipeline makes`);
|
|
77
|
+
}
|
|
78
|
+
async refresh({ clock, signal, }) {
|
|
79
|
+
await using session = await connectDestination(this.#into, clock);
|
|
80
|
+
const status = new SqlServerDerivedStatus(session, this.qualifiedName, 'computed', clock);
|
|
81
|
+
try {
|
|
82
|
+
// The chunks have no parts table yet while they wait for their input,
|
|
83
|
+
// so the index waits with them, and makes nothing.
|
|
84
|
+
try {
|
|
85
|
+
await session.query(`SELECT TOP (0) 1 AS [part] FROM ${this.#parts}`);
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
if (!this.#missingParts(error))
|
|
89
|
+
throw error;
|
|
90
|
+
await status.waiting();
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
// Two refreshes of one index take turns, so neither makes the table
|
|
94
|
+
// while the other makes it. The lock is the session's, since the
|
|
95
|
+
// full-text statements run outside a transaction; it ends with the
|
|
96
|
+
// session.
|
|
97
|
+
await session.query(`DECLARE @result int;
|
|
98
|
+
EXEC @result = sp_getapplock @Resource = @resource, @LockMode = N'Exclusive', @LockOwner = N'Session', @LockTimeout = -1;
|
|
99
|
+
IF @result < 0 THROW 50000, N'The lock was not granted', 1;`, { resource: `elt:${this.qualifiedName}` });
|
|
100
|
+
await this.#declare(session);
|
|
101
|
+
const counts = await this.#write(session);
|
|
102
|
+
await status.refreshing({ ...counts, empty: 0, failed: 0, pending: 0 });
|
|
103
|
+
await this.#populated(session, clock, signal);
|
|
104
|
+
await status.current({ ...counts, empty: 0, failed: 0, pending: 0 });
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
// A stop is not the dataset's failure.
|
|
108
|
+
if (signal?.aborted !== true)
|
|
109
|
+
await status.failed(errorMessage(error));
|
|
110
|
+
throw error;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
// Makes the catalog when the database has none, and the table and its
|
|
114
|
+
// full-text index again when the table does not keep the hash of this
|
|
115
|
+
// declaration or has no full-text index. A server with no Full-Text Search
|
|
116
|
+
// refuses the catalog, before the member makes anything.
|
|
117
|
+
async #declare(session) {
|
|
118
|
+
try {
|
|
119
|
+
await session.query(`IF NOT EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE [name] = ${literal(this.name)}) CREATE FULLTEXT CATALOG ${this.#catalog}`);
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
if (numberOf(error) !== noFullTextSearch)
|
|
123
|
+
throw error;
|
|
124
|
+
throw new SqlServerSetupError(`Keyword index ${this.name} needs Full-Text Search, and the server has none: install it (on Linux, the package mssql-server-fts), or use Azure SQL Database, which has it`, { cause: error });
|
|
125
|
+
}
|
|
126
|
+
const [stored] = await session.query(`SELECT (SELECT CAST([value] AS nvarchar(100)) FROM sys.extended_properties WHERE [class] = 1 AND [major_id] = OBJECT_ID(@table) AND [minor_id] = 0 AND [name] = N'elt_declaration') AS [declared],
|
|
127
|
+
(SELECT COUNT(*) FROM sys.fulltext_indexes WHERE [object_id] = OBJECT_ID(@table)) AS [indexed]`, { table: this.#table });
|
|
128
|
+
if (stored?.declared === this.#declared && Number(stored.indexed) === 1)
|
|
129
|
+
return;
|
|
130
|
+
await session.query(`IF EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE [object_id] = OBJECT_ID(${literal(this.#table)})) DROP FULLTEXT INDEX ON ${this.#table}`);
|
|
131
|
+
await session.query(`DROP TABLE IF EXISTS ${this.#table}`);
|
|
132
|
+
for (const statement of this.#declaration)
|
|
133
|
+
await session.query(statement);
|
|
134
|
+
// Last, so a make that stopped half way is made again by the next
|
|
135
|
+
// refresh.
|
|
136
|
+
await session.query(`EXEC sp_addextendedproperty @name = N'elt_declaration', @value = @declared, @level0type = N'SCHEMA', @level0name = @schema, @level1type = N'TABLE', @level1name = @table`, { declared: this.#declared, schema: marts, table: this.name });
|
|
137
|
+
}
|
|
138
|
+
// Writes each passage whose text changed and removes each one that no part
|
|
139
|
+
// has, in one MERGE, and gives the parts and the passages.
|
|
140
|
+
async #write(session) {
|
|
141
|
+
await session.query(`MERGE ${this.#table} AS k
|
|
142
|
+
USING (SELECT CONCAT(p.[source], N':', p.[seq]) COLLATE ${binary} AS [id], p.[source], p.[seq], p.[text] FROM ${this.#parts} AS p) AS n
|
|
143
|
+
ON k.[id] = n.[id]
|
|
144
|
+
WHEN MATCHED AND k.[text] COLLATE ${binary} <> n.[text] COLLATE ${binary} THEN UPDATE SET [text] = n.[text]
|
|
145
|
+
WHEN NOT MATCHED BY TARGET THEN INSERT ([id], [source], [seq], [text]) VALUES (n.[id], n.[source], n.[seq], n.[text])
|
|
146
|
+
WHEN NOT MATCHED BY SOURCE THEN DELETE;`);
|
|
147
|
+
const [row] = await session.query(`SELECT (SELECT COUNT_BIG(*) FROM ${this.#parts}) AS [inputs], (SELECT COUNT_BIG(*) FROM ${this.#table}) AS [computed]`);
|
|
148
|
+
return { inputs: Number(row?.inputs), computed: Number(row?.computed) };
|
|
149
|
+
}
|
|
150
|
+
// Waits on the clock of the pipeline, under the signal of the refresh,
|
|
151
|
+
// until the full-text index has no population running and no change
|
|
152
|
+
// waiting. Both are needed: no change waits while the first population
|
|
153
|
+
// still runs. OBJECTPROPERTYEX gives a sql_variant, so each is cast.
|
|
154
|
+
async #populated(session, clock, signal) {
|
|
155
|
+
await poll(async () => {
|
|
156
|
+
const [state] = await session.query(`SELECT CAST(OBJECTPROPERTYEX(OBJECT_ID(@table), 'TableFulltextPopulateStatus') AS INT) AS [populating],
|
|
157
|
+
CAST(OBJECTPROPERTYEX(OBJECT_ID(@table), 'TableFulltextPendingChanges') AS INT) AS [pending]`, { table: this.#table }, { signal });
|
|
158
|
+
return Number(state?.populating) === 0 && Number(state?.pending) === 0
|
|
159
|
+
? true
|
|
160
|
+
: undefined;
|
|
161
|
+
}, { interval: populationPoll, signal, clock });
|
|
162
|
+
}
|
|
163
|
+
#missingParts(error) {
|
|
164
|
+
return (numberOf(error) === invalidObject &&
|
|
165
|
+
Error.isError(error) &&
|
|
166
|
+
error.message.toLowerCase() ===
|
|
167
|
+
`invalid object name '${this.#partsName}'.`.toLowerCase());
|
|
168
|
+
}
|
|
169
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { CompositeDataset, type Connection, type DerivedDataset } from '@eltjs/elt';
|
|
2
|
+
import { SqlServerDestination, SqlServerTable, View } from '@eltjs/elt-sqlserver';
|
|
3
|
+
import { type ChunkingOptions, type EmbeddingOptions, type Loading, type SourceKey } from '../options.ts';
|
|
4
|
+
type Origin = {
|
|
5
|
+
readonly into: SqlServerDestination;
|
|
6
|
+
readonly from: SqlServerTable;
|
|
7
|
+
} | {
|
|
8
|
+
readonly from: View;
|
|
9
|
+
};
|
|
10
|
+
export type SqlServerContract = {
|
|
11
|
+
readonly schema: string;
|
|
12
|
+
readonly passages: string;
|
|
13
|
+
readonly vectors: string;
|
|
14
|
+
readonly index: {
|
|
15
|
+
readonly table: string;
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
export declare class Vectorizer extends CompositeDataset<SqlServerTable> {
|
|
19
|
+
#private;
|
|
20
|
+
readonly name: string;
|
|
21
|
+
readonly members: readonly [
|
|
22
|
+
DerivedDataset<SqlServerTable>,
|
|
23
|
+
...DerivedDataset<SqlServerTable>[]
|
|
24
|
+
];
|
|
25
|
+
readonly contract: SqlServerContract;
|
|
26
|
+
readonly into: SqlServerDestination;
|
|
27
|
+
constructor(options: Origin & {
|
|
28
|
+
readonly name: string;
|
|
29
|
+
readonly description: string;
|
|
30
|
+
readonly key: SourceKey;
|
|
31
|
+
readonly loading: Loading;
|
|
32
|
+
readonly chunking: ChunkingOptions;
|
|
33
|
+
readonly embedding: EmbeddingOptions;
|
|
34
|
+
readonly metadata?: readonly string[];
|
|
35
|
+
readonly keywords?: {
|
|
36
|
+
readonly language?: number;
|
|
37
|
+
};
|
|
38
|
+
readonly indexing?: {
|
|
39
|
+
readonly vectors: 'none';
|
|
40
|
+
};
|
|
41
|
+
});
|
|
42
|
+
validate(connections: readonly Connection<SqlServerTable>[]): void;
|
|
43
|
+
}
|
|
44
|
+
export {};
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { CompositeDataset, DocumentText, } from '@eltjs/elt';
|
|
2
|
+
import { ComputedDataset, SqlServerTable, View, inMarts, inWarehouse, literal, marts, quote, rawTable, sameDatabase, } from '@eltjs/elt-sqlserver';
|
|
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, mostIdCharacters } from './keyword-index.js';
|
|
9
|
+
// The columns of the passages of @zukhruf/retrieval on SQL Server, which no
|
|
10
|
+
// metadata column may take (its ADR 0001).
|
|
11
|
+
const contractColumns = [
|
|
12
|
+
'id',
|
|
13
|
+
'source',
|
|
14
|
+
'seq',
|
|
15
|
+
'start',
|
|
16
|
+
'end',
|
|
17
|
+
'text',
|
|
18
|
+
];
|
|
19
|
+
// The collation of every passage id and source that the views compare:
|
|
20
|
+
// UTF-16 code units, so a and A are two sources under a case-insensitive
|
|
21
|
+
// database, as elt keeps them apart (elt-sqlserver ADR 0004).
|
|
22
|
+
const binary = 'COLLATE Latin1_General_100_BIN2';
|
|
23
|
+
// The language of the keyword index when the host names none: English, the
|
|
24
|
+
// LCID 1033, as the Postgres vectorizer reads English when it names none.
|
|
25
|
+
const english = 1033;
|
|
26
|
+
// One declaration that keeps the passage contract of @zukhruf/retrieval in
|
|
27
|
+
// step with what a pipeline loads into one SQL Server database: the passages
|
|
28
|
+
// of each source row with its metadata, the vector of each passage with the
|
|
29
|
+
// identity of its model, and a keyword index of the passages, a full-text
|
|
30
|
+
// index (ADR 0001). Each relation is a member that the pipeline refreshes in
|
|
31
|
+
// order, so a member's failure fails only the vectorizer (elt ADR 0034). The
|
|
32
|
+
// views of the contract live in marts and read the raw tables in _warehouse,
|
|
33
|
+
// the rows of now; a reader with SELECT on marts reads them through the
|
|
34
|
+
// ownership chain. Every relation's name starts with name.
|
|
35
|
+
export class Vectorizer extends CompositeDataset {
|
|
36
|
+
name;
|
|
37
|
+
members;
|
|
38
|
+
contract;
|
|
39
|
+
// The database of the relations, which a host connects to for the store.
|
|
40
|
+
into;
|
|
41
|
+
#from;
|
|
42
|
+
#key;
|
|
43
|
+
#loading;
|
|
44
|
+
#metadata;
|
|
45
|
+
// name: the start of the name of each relation. key: the column, or
|
|
46
|
+
// columns, that identify a source row. loading: what text of a row the
|
|
47
|
+
// passages cut. metadata: the columns of the source row that each passage
|
|
48
|
+
// gives beside its text; none when absent (Airbyte metadata_fields).
|
|
49
|
+
// keywords: the LCID of the language of the full-text index, 1033
|
|
50
|
+
// (English) when absent. indexing: the index of the vectors, which is none:
|
|
51
|
+
// a search compares every vector with VECTOR_DISTANCE, as the DiskANN
|
|
52
|
+
// index of SQL Server 2025 does not serve the contract yet (zukhruf #5475).
|
|
53
|
+
constructor(options) {
|
|
54
|
+
super();
|
|
55
|
+
const { name, description, key, loading, chunking, embedding } = options;
|
|
56
|
+
const metadata = options.metadata ?? [];
|
|
57
|
+
refuseColumns({
|
|
58
|
+
vectorizer: name,
|
|
59
|
+
key,
|
|
60
|
+
metadata,
|
|
61
|
+
contract: contractColumns,
|
|
62
|
+
});
|
|
63
|
+
this.name = name;
|
|
64
|
+
this.into = 'into' in options ? options.into : options.from.into;
|
|
65
|
+
this.#from = options.from;
|
|
66
|
+
this.#key = key;
|
|
67
|
+
this.#loading = loading;
|
|
68
|
+
this.#metadata = Object.freeze([...metadata]);
|
|
69
|
+
const into = this.into;
|
|
70
|
+
const columns = keyColumns(key);
|
|
71
|
+
const source = options.from instanceof SqlServerTable
|
|
72
|
+
? inWarehouse(options.from.raw)
|
|
73
|
+
: inMarts(options.from.name);
|
|
74
|
+
const keyDescriptions = Object.fromEntries(columns.map((column) => [
|
|
75
|
+
column,
|
|
76
|
+
`The ${column} column of the key of the source row.`,
|
|
77
|
+
]));
|
|
78
|
+
const names = {
|
|
79
|
+
text: `${name}_text`,
|
|
80
|
+
documents: `${name}_documents`,
|
|
81
|
+
chunks: `${name}_chunks`,
|
|
82
|
+
keywords: `${name}_keywords`,
|
|
83
|
+
passages: `${name}_passages`,
|
|
84
|
+
chunkTexts: `${name}_chunk_texts`,
|
|
85
|
+
chunkVectors: `${name}_chunk_vectors`,
|
|
86
|
+
passageVectors: `${name}_passage_vectors`,
|
|
87
|
+
status: `${name}_status`,
|
|
88
|
+
};
|
|
89
|
+
const rawParts = rawTable(`${names.chunks}_parts`);
|
|
90
|
+
const parts = inWarehouse(rawParts);
|
|
91
|
+
const vectors = inWarehouse(rawTable(names.chunkVectors));
|
|
92
|
+
// The text of a stored file is the input of the chunks through a view
|
|
93
|
+
// keyed by the source key, since rows can share a file (elt ADR 0027).
|
|
94
|
+
// Names of files compare by their bytes (elt-sqlserver ADR 0015).
|
|
95
|
+
let files = [];
|
|
96
|
+
let input = options.from;
|
|
97
|
+
if ('file' in loading) {
|
|
98
|
+
const text = new ComputedDataset({
|
|
99
|
+
into,
|
|
100
|
+
name: names.text,
|
|
101
|
+
description: `The text of each file of the vectorizer ${name}. ${description}`,
|
|
102
|
+
from: [options.from],
|
|
103
|
+
compute: new DocumentText({
|
|
104
|
+
parser: loading.parser,
|
|
105
|
+
files: loading.files,
|
|
106
|
+
column: loading.file,
|
|
107
|
+
}),
|
|
108
|
+
});
|
|
109
|
+
input = new View({
|
|
110
|
+
into,
|
|
111
|
+
name: names.documents,
|
|
112
|
+
description: `The text of the file of each source row of the vectorizer ${name}. ${description}`,
|
|
113
|
+
columns: {
|
|
114
|
+
...keyDescriptions,
|
|
115
|
+
content: 'The text the parser extracted from the file.',
|
|
116
|
+
},
|
|
117
|
+
sql: `SELECT ${columns.map((column) => `s.${quote(column)}`).join(', ')}, t.[content] FROM ${source} AS s JOIN ${inMarts(names.text)} AS t ON t.[ref] ${binary} = s.${quote(loading.file)} ${binary} WHERE t.[status] = N'computed'`,
|
|
118
|
+
});
|
|
119
|
+
files = [text, input];
|
|
120
|
+
}
|
|
121
|
+
const chunks = new ComputedDataset({
|
|
122
|
+
into,
|
|
123
|
+
name: names.chunks,
|
|
124
|
+
description: `The passages of the vectorizer ${name}, one row for each source row. ${description}`,
|
|
125
|
+
from: [input],
|
|
126
|
+
// A passage id is the key of the keyword index, NVARCHAR(450), so an
|
|
127
|
+
// input with a longer id is a rule failure of its own.
|
|
128
|
+
compute: passageRule({
|
|
129
|
+
key,
|
|
130
|
+
fields: 'columns' in loading ? loading.columns : ['content'],
|
|
131
|
+
chunking,
|
|
132
|
+
maxIdLength: mostIdCharacters,
|
|
133
|
+
}),
|
|
134
|
+
});
|
|
135
|
+
const keywords = new KeywordIndex({
|
|
136
|
+
into,
|
|
137
|
+
name: names.keywords,
|
|
138
|
+
parts: rawParts,
|
|
139
|
+
language: options.keywords?.language ?? english,
|
|
140
|
+
});
|
|
141
|
+
// The source joins as text, in binary: the source of a passage is the
|
|
142
|
+
// text of the key value as the destination reads it back.
|
|
143
|
+
const keyText = (column) => `CONVERT(NVARCHAR(MAX), s.${quote(column)}) ${binary}`;
|
|
144
|
+
const join = typeof key === 'string'
|
|
145
|
+
? `${keyText(key)} = p.[source] ${binary}`
|
|
146
|
+
: columns
|
|
147
|
+
.map((column, index) => `${keyText(column)} = JSON_VALUE(p.[source], '$[${index}]') ${binary}`)
|
|
148
|
+
.join(' AND ');
|
|
149
|
+
const passages = new View({
|
|
150
|
+
into,
|
|
151
|
+
name: names.passages,
|
|
152
|
+
description: `The passages of the vectorizer ${name}, as @zukhruf/retrieval reads them. ${description}`,
|
|
153
|
+
columns: {
|
|
154
|
+
id: 'The id of the passage: its source, a colon and its seq.',
|
|
155
|
+
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.',
|
|
156
|
+
seq: 'The place of the passage in its source row, from 0.',
|
|
157
|
+
start: 'The offset of the first code point of the passage in the text of its row, from 0.',
|
|
158
|
+
end: 'The offset after the last code point of the passage in the text of its row.',
|
|
159
|
+
text: 'The text of the passage.',
|
|
160
|
+
...Object.fromEntries(metadata.map((column) => [
|
|
161
|
+
column,
|
|
162
|
+
`The ${column} column of the source row.`,
|
|
163
|
+
])),
|
|
164
|
+
},
|
|
165
|
+
sql: `SELECT CAST(k.[id] AS NVARCHAR(${mostIdCharacters})) ${binary} AS [id], p.[source], p.[seq], p.[start], p.[end], p.[text]${metadata
|
|
166
|
+
.map((column) => `, s.${quote(column)} AS ${quote(column)}`)
|
|
167
|
+
.join('')} FROM ${inMarts(names.keywords)} AS k JOIN ${parts} AS p ON p.[source] ${binary} = k.[source] AND p.[seq] = k.[seq] JOIN ${source} AS s ON ${join}`,
|
|
168
|
+
});
|
|
169
|
+
// The text of each part by its part hash. Parts with one text share a
|
|
170
|
+
// part hash, and a computed dataset keeps the first input of a key, so a
|
|
171
|
+
// text is embedded once with no DISTINCT.
|
|
172
|
+
const chunkTexts = new View({
|
|
173
|
+
into,
|
|
174
|
+
name: names.chunkTexts,
|
|
175
|
+
description: `The text of each passage of the vectorizer ${name}, by its part hash. ${description}`,
|
|
176
|
+
columns: {
|
|
177
|
+
id: 'The part hash of the passage.',
|
|
178
|
+
text: 'The text of the passage.',
|
|
179
|
+
},
|
|
180
|
+
sql: `SELECT [part_hash] AS [id], [text] FROM ${inMarts(`${names.chunks}_parts`)}`,
|
|
181
|
+
});
|
|
182
|
+
// No vector index: indexing is { vectors: 'none' } only (zukhruf #5475).
|
|
183
|
+
const chunkVectors = new ComputedDataset({
|
|
184
|
+
into,
|
|
185
|
+
name: names.chunkVectors,
|
|
186
|
+
description: `The vector of each passage text of the vectorizer ${name}. ${description}`,
|
|
187
|
+
from: [chunkTexts],
|
|
188
|
+
compute: new Embedding({ ...embedding, key: 'id', fields: ['text'] }),
|
|
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.
|
|
192
|
+
const passageVectors = new View({
|
|
193
|
+
into,
|
|
194
|
+
name: names.passageVectors,
|
|
195
|
+
description: `The vector of each passage of the vectorizer ${name}, as @zukhruf/retrieval reads them. ${description}`,
|
|
196
|
+
columns: {
|
|
197
|
+
id: 'The id of the passage.',
|
|
198
|
+
vector: 'The unit vector of the passage text, float32 values.',
|
|
199
|
+
model: 'The model that made the vector: <provider>/<model id> (<n> dimensions).',
|
|
200
|
+
},
|
|
201
|
+
sql: `SELECT CONCAT(p.[source], N':', p.[seq]) ${binary} 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] = N'computed'`,
|
|
202
|
+
});
|
|
203
|
+
const leaves = [
|
|
204
|
+
...files,
|
|
205
|
+
chunks,
|
|
206
|
+
keywords,
|
|
207
|
+
passages,
|
|
208
|
+
chunkTexts,
|
|
209
|
+
chunkVectors,
|
|
210
|
+
passageVectors,
|
|
211
|
+
];
|
|
212
|
+
const status = new View({
|
|
213
|
+
into,
|
|
214
|
+
name: names.status,
|
|
215
|
+
description: `How far the relations of the vectorizer ${name} are in step with their source. ${description}`,
|
|
216
|
+
columns: {
|
|
217
|
+
state: 'failed when a relation failed, waiting when one waits for its input, refreshing when one refreshes, else current.',
|
|
218
|
+
as_of: 'The earliest as_of of the relations: the data that every relation holds. NULL until each holds some.',
|
|
219
|
+
pending_sources: 'The source rows that wait for their passages.',
|
|
220
|
+
pending_vectors: 'The passage texts that wait for their vectors.',
|
|
221
|
+
},
|
|
222
|
+
sql: `WITH [members] ([dataset]) AS (SELECT [dataset] FROM (VALUES ${leaves
|
|
223
|
+
.map((member) => `(${literal(member.qualifiedName)})`)
|
|
224
|
+
.join(', ')}) AS v ([dataset])), [rows] AS (SELECT m.[dataset], COALESCE(d.[state], N'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 N'failed' THEN 3 WHEN N'waiting' THEN 2 WHEN N'refreshing' THEN 1 ELSE 0 END) WHEN 3 THEN N'failed' WHEN 2 THEN N'waiting' WHEN 1 THEN N'refreshing' ELSE N'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]`,
|
|
225
|
+
});
|
|
226
|
+
this.members = Object.freeze([...leaves, status]);
|
|
227
|
+
this.contract = Object.freeze({
|
|
228
|
+
schema: marts,
|
|
229
|
+
passages: names.passages,
|
|
230
|
+
vectors: names.passageVectors,
|
|
231
|
+
index: Object.freeze({ table: names.keywords }),
|
|
232
|
+
});
|
|
233
|
+
Object.freeze(this);
|
|
234
|
+
}
|
|
235
|
+
// A source table must be one that a copy loads into the database of the
|
|
236
|
+
// vectorizer, and the copy's stream must declare each column that the
|
|
237
|
+
// vectorizer reads. A View's columns are its own SQL's, so its first
|
|
238
|
+
// refresh tells, as for any view.
|
|
239
|
+
validate(connections) {
|
|
240
|
+
const from = this.#from;
|
|
241
|
+
if (!(from instanceof SqlServerTable))
|
|
242
|
+
return;
|
|
243
|
+
refuseUndeclaredColumns({
|
|
244
|
+
vectorizer: this.name,
|
|
245
|
+
from,
|
|
246
|
+
copies: copiesInto(connections, (destination) => sameDatabase(destination, this.into)),
|
|
247
|
+
destination: 'its database',
|
|
248
|
+
key: this.#key,
|
|
249
|
+
metadata: this.#metadata,
|
|
250
|
+
loading: this.#loading,
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { Vectorizer } from './sqlserver/vectorizer.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,76 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@eltjs/vectorizer",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.13.8",
|
|
4
|
+
"description": "One declaration that keeps the passage contract of @zukhruf/retrieval in step with an elt pipeline: passages with metadata, their vectors with the model identity, and a keyword index.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/ezzabuzaid/elt",
|
|
9
|
+
"directory": "packages/vectorizer"
|
|
10
|
+
},
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/ezzabuzaid/elt/issues"
|
|
13
|
+
},
|
|
14
|
+
"homepage": "https://github.com/ezzabuzaid/elt/tree/main/packages/vectorizer#readme",
|
|
15
|
+
"keywords": [
|
|
16
|
+
"elt",
|
|
17
|
+
"rag",
|
|
18
|
+
"vectorizer",
|
|
19
|
+
"embedding",
|
|
20
|
+
"chunking",
|
|
21
|
+
"bm25",
|
|
22
|
+
"fts5",
|
|
23
|
+
"sqlite",
|
|
24
|
+
"postgresql",
|
|
25
|
+
"pgvector"
|
|
26
|
+
],
|
|
27
|
+
"type": "module",
|
|
28
|
+
"exports": {
|
|
29
|
+
"./package.json": "./package.json",
|
|
30
|
+
"./sqlite": {
|
|
31
|
+
"types": "./dist/sqlite.d.ts",
|
|
32
|
+
"default": "./dist/sqlite.js"
|
|
33
|
+
},
|
|
34
|
+
"./postgresql": {
|
|
35
|
+
"types": "./dist/postgresql.d.ts",
|
|
36
|
+
"default": "./dist/postgresql.js"
|
|
37
|
+
},
|
|
38
|
+
"./sqlserver": {
|
|
39
|
+
"types": "./dist/sqlserver.d.ts",
|
|
40
|
+
"default": "./dist/sqlserver.js"
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
"files": [
|
|
44
|
+
"dist",
|
|
45
|
+
"!dist/spec/**",
|
|
46
|
+
"!**/*.tsbuildinfo",
|
|
47
|
+
"!**/*.test.*"
|
|
48
|
+
],
|
|
49
|
+
"publishConfig": {
|
|
50
|
+
"access": "public"
|
|
51
|
+
},
|
|
52
|
+
"dependencies": {
|
|
53
|
+
"@eltjs/chunking": "^0.13.8",
|
|
54
|
+
"@eltjs/elt": "^0.13.8",
|
|
55
|
+
"@eltjs/elt-postgresql": "^0.13.8",
|
|
56
|
+
"@eltjs/elt-sqlite": "^0.13.8",
|
|
57
|
+
"@eltjs/elt-sqlserver": "^0.13.8",
|
|
58
|
+
"@eltjs/embedding": "^0.13.8",
|
|
59
|
+
"@zukhruf/async": "^0.8.105",
|
|
60
|
+
"@zukhruf/sqlite-drift": "^0.8.105",
|
|
61
|
+
"@zukhruf/sqlite-transaction": "^0.8.105",
|
|
62
|
+
"ai": "^7.0.165",
|
|
63
|
+
"postgres": "^3.4.9"
|
|
64
|
+
},
|
|
65
|
+
"devDependencies": {
|
|
66
|
+
"@ai-sdk/provider": "^4.0.37",
|
|
67
|
+
"@types/mssql": "^12.3.0",
|
|
68
|
+
"@zukhruf/fs": "^0.8.105",
|
|
69
|
+
"@zukhruf/retrieval": "^0.8.105",
|
|
70
|
+
"@zukhruf/sqlite-open": "^0.8.105",
|
|
71
|
+
"@zukhruf/testing": "^0.8.105",
|
|
72
|
+
"@zukhruf/vectors": "^0.8.105",
|
|
73
|
+
"gpt-tokenizer": "^4.1.2",
|
|
74
|
+
"mssql": "^12.7.4"
|
|
75
|
+
}
|
|
76
|
+
}
|