@videoq-jp/langchainjs-postgres 0.0.0-stage → 0.3.0
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 +21 -0
- package/README.md +333 -2
- package/dist/index.cjs +1794 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +568 -0
- package/dist/index.d.ts +568 -0
- package/dist/index.js +1749 -0
- package/dist/index.js.map +1 -0
- package/package.json +87 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1749 @@
|
|
|
1
|
+
// src/engine.ts
|
|
2
|
+
import { Pool } from "pg";
|
|
3
|
+
var Column = class {
|
|
4
|
+
name;
|
|
5
|
+
dataType;
|
|
6
|
+
nullable;
|
|
7
|
+
constructor(name, dataType, nullable = true) {
|
|
8
|
+
if (typeof name !== "string") {
|
|
9
|
+
throw new TypeError("Column name must be type string");
|
|
10
|
+
}
|
|
11
|
+
if (typeof dataType !== "string") {
|
|
12
|
+
throw new TypeError("Column data_type must be type string");
|
|
13
|
+
}
|
|
14
|
+
this.name = name;
|
|
15
|
+
this.dataType = dataType;
|
|
16
|
+
this.nullable = nullable;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
function escapePostgresIdentifier(name) {
|
|
20
|
+
return name.replace(/"/g, '""');
|
|
21
|
+
}
|
|
22
|
+
function normalizeColumn(col) {
|
|
23
|
+
if (col instanceof Column) {
|
|
24
|
+
return { name: col.name, dataType: col.dataType, nullable: col.nullable };
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
name: col.name,
|
|
28
|
+
dataType: col.dataType,
|
|
29
|
+
nullable: col.nullable ?? true
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
var PGEngine = class _PGEngine {
|
|
33
|
+
/** The underlying `pg` connection pool. Exposed for advanced use cases. */
|
|
34
|
+
pool;
|
|
35
|
+
constructor(pool) {
|
|
36
|
+
this.pool = pool;
|
|
37
|
+
}
|
|
38
|
+
/** Create a PGEngine instance from an existing `pg.Pool`. */
|
|
39
|
+
static fromPool(pool) {
|
|
40
|
+
return new _PGEngine(pool);
|
|
41
|
+
}
|
|
42
|
+
/** Create a PGEngine instance from a Postgres connection string. */
|
|
43
|
+
static fromConnectionString(url, poolConfig = {}) {
|
|
44
|
+
const pool = new Pool({ ...poolConfig, connectionString: url });
|
|
45
|
+
return new _PGEngine(pool);
|
|
46
|
+
}
|
|
47
|
+
/** Dispose of the connection pool. */
|
|
48
|
+
async close() {
|
|
49
|
+
await this.pool.end();
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Create a table for saving vectors to be used with {@link PGVectorStore}.
|
|
53
|
+
*
|
|
54
|
+
* @throws if the table already exists, or if the data type of the id
|
|
55
|
+
* column is not a valid PostgreSQL data type.
|
|
56
|
+
*/
|
|
57
|
+
async initVectorstoreTable(tableName, vectorSize, options = {}) {
|
|
58
|
+
const schemaName = escapePostgresIdentifier(options.schemaName ?? "public");
|
|
59
|
+
const escapedTableName = escapePostgresIdentifier(tableName);
|
|
60
|
+
const hybridSearchDefaultColumnName = `${options.contentColumn ?? "content"}_tsv`;
|
|
61
|
+
const contentColumn = escapePostgresIdentifier(
|
|
62
|
+
options.contentColumn ?? "content"
|
|
63
|
+
);
|
|
64
|
+
const embeddingColumn = escapePostgresIdentifier(
|
|
65
|
+
options.embeddingColumn ?? "embedding"
|
|
66
|
+
);
|
|
67
|
+
const metadataColumns = (options.metadataColumns ?? []).map(
|
|
68
|
+
normalizeColumn
|
|
69
|
+
);
|
|
70
|
+
for (const col of metadataColumns)
|
|
71
|
+
col.name = escapePostgresIdentifier(col.name);
|
|
72
|
+
const idColumnInput = options.idColumn ?? "langchain_id";
|
|
73
|
+
let idColumnName;
|
|
74
|
+
let idDataType;
|
|
75
|
+
if (typeof idColumnInput === "string") {
|
|
76
|
+
idColumnName = escapePostgresIdentifier(idColumnInput);
|
|
77
|
+
idDataType = "UUID";
|
|
78
|
+
} else {
|
|
79
|
+
const normalized = normalizeColumn(idColumnInput);
|
|
80
|
+
idColumnName = escapePostgresIdentifier(normalized.name);
|
|
81
|
+
idDataType = normalized.dataType;
|
|
82
|
+
}
|
|
83
|
+
const metadataJsonColumn = options.metadataJsonColumn ?? "langchain_metadata";
|
|
84
|
+
const storeMetadata = options.storeMetadata ?? true;
|
|
85
|
+
await this.pool.query("CREATE EXTENSION IF NOT EXISTS vector");
|
|
86
|
+
if (options.overwriteExisting) {
|
|
87
|
+
await this.pool.query(
|
|
88
|
+
`DROP TABLE IF EXISTS "${schemaName}"."${escapedTableName}"`
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
let hybridSearchColumn = "";
|
|
92
|
+
const hybridSearchConfig = options.hybridSearchConfig;
|
|
93
|
+
if (hybridSearchConfig) {
|
|
94
|
+
const hybridSearchColumnName = escapePostgresIdentifier(
|
|
95
|
+
hybridSearchConfig.tsvColumn || hybridSearchDefaultColumnName
|
|
96
|
+
);
|
|
97
|
+
hybridSearchConfig.tsvColumn = hybridSearchColumnName;
|
|
98
|
+
hybridSearchColumn = `,"${hybridSearchColumnName}" TSVECTOR NOT NULL`;
|
|
99
|
+
}
|
|
100
|
+
let query = `CREATE TABLE "${schemaName}"."${escapedTableName}"(
|
|
101
|
+
"${idColumnName}" ${idDataType} PRIMARY KEY,
|
|
102
|
+
"${contentColumn}" TEXT NOT NULL,
|
|
103
|
+
"${embeddingColumn}" vector(${vectorSize}) NOT NULL
|
|
104
|
+
${hybridSearchColumn}`;
|
|
105
|
+
for (const column of metadataColumns) {
|
|
106
|
+
const nullable = column.nullable ? "" : "NOT NULL";
|
|
107
|
+
query += `,
|
|
108
|
+
"${column.name}" ${column.dataType} ${nullable}`;
|
|
109
|
+
}
|
|
110
|
+
if (storeMetadata) {
|
|
111
|
+
query += `,
|
|
112
|
+
"${metadataJsonColumn}" JSON`;
|
|
113
|
+
}
|
|
114
|
+
query += "\n);";
|
|
115
|
+
await this.pool.query(query);
|
|
116
|
+
}
|
|
117
|
+
/** Drop the vector store table. */
|
|
118
|
+
async dropTable(tableName, options = {}) {
|
|
119
|
+
const schemaName = options.schemaName ?? "public";
|
|
120
|
+
await this.pool.query(
|
|
121
|
+
`DROP TABLE IF EXISTS "${schemaName}"."${tableName}";`
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
// src/vectorstore.ts
|
|
127
|
+
import { Document } from "@langchain/core/documents";
|
|
128
|
+
import { maximalMarginalRelevance } from "@langchain/core/utils/math";
|
|
129
|
+
import {
|
|
130
|
+
VectorStore
|
|
131
|
+
} from "@langchain/core/vectorstores";
|
|
132
|
+
import { randomUUID } from "crypto";
|
|
133
|
+
|
|
134
|
+
// src/filter.ts
|
|
135
|
+
var ParamBuilder = class {
|
|
136
|
+
values = [];
|
|
137
|
+
add(value) {
|
|
138
|
+
this.values.push(value);
|
|
139
|
+
return `$${this.values.length}`;
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
var COMPARISONS_TO_NATIVE = {
|
|
143
|
+
$eq: "=",
|
|
144
|
+
$ne: "!=",
|
|
145
|
+
$lt: "<",
|
|
146
|
+
$lte: "<=",
|
|
147
|
+
$gt: ">",
|
|
148
|
+
$gte: ">="
|
|
149
|
+
};
|
|
150
|
+
var SPECIAL_CASED_OPERATORS = /* @__PURE__ */ new Set(["$in", "$nin", "$between", "$exists"]);
|
|
151
|
+
var TEXT_OPERATORS = /* @__PURE__ */ new Set(["$like", "$ilike"]);
|
|
152
|
+
var LOGICAL_OPERATORS = /* @__PURE__ */ new Set(["$and", "$or", "$not"]);
|
|
153
|
+
var SUPPORTED_OPERATORS = /* @__PURE__ */ new Set([
|
|
154
|
+
...Object.keys(COMPARISONS_TO_NATIVE),
|
|
155
|
+
...TEXT_OPERATORS,
|
|
156
|
+
...LOGICAL_OPERATORS,
|
|
157
|
+
...SPECIAL_CASED_OPERATORS
|
|
158
|
+
]);
|
|
159
|
+
function inferPostgresType(value) {
|
|
160
|
+
if (typeof value === "number") {
|
|
161
|
+
return Number.isInteger(value) ? "INTEGER" : "FLOAT";
|
|
162
|
+
}
|
|
163
|
+
if (typeof value === "string") return "TEXT";
|
|
164
|
+
if (typeof value === "boolean") return "BOOLEAN";
|
|
165
|
+
if (value instanceof Date) return "TIMESTAMP";
|
|
166
|
+
return void 0;
|
|
167
|
+
}
|
|
168
|
+
function isIdentifier(value) {
|
|
169
|
+
return /^[A-Za-z_][A-Za-z0-9_]*$/.test(value);
|
|
170
|
+
}
|
|
171
|
+
function buildFieldSelector(field, ctx) {
|
|
172
|
+
let fieldSelector = field;
|
|
173
|
+
const fieldColumn = field.split(".")[0];
|
|
174
|
+
if (ctx.metadataJsonColumn && !ctx.metadataColumns.includes(fieldColumn) && ![ctx.idColumn, ctx.contentColumn, ctx.embeddingColumn].includes(
|
|
175
|
+
fieldColumn
|
|
176
|
+
)) {
|
|
177
|
+
fieldSelector = `${ctx.metadataJsonColumn}.${fieldSelector}`;
|
|
178
|
+
}
|
|
179
|
+
const hasJsonPath = fieldSelector.includes(".");
|
|
180
|
+
if (hasJsonPath) {
|
|
181
|
+
const parts = fieldSelector.split(".");
|
|
182
|
+
fieldSelector = parts.map(
|
|
183
|
+
(part, ind) => ind === 0 ? part : `${ind === parts.length - 1 ? ">" : ""}'${part}'`
|
|
184
|
+
).join("->");
|
|
185
|
+
}
|
|
186
|
+
return { selector: fieldSelector, hasJsonPath };
|
|
187
|
+
}
|
|
188
|
+
function handleFieldFilter(field, value, ctx) {
|
|
189
|
+
if (typeof field !== "string") {
|
|
190
|
+
throw new Error(`field should be a string but got: ${typeof field}`);
|
|
191
|
+
}
|
|
192
|
+
if (field.startsWith("$")) {
|
|
193
|
+
throw new Error(
|
|
194
|
+
`Invalid filter condition. Expected a field but got an operator: ${field}`
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
if (!(isIdentifier(field) || field.split(".").every(isIdentifier))) {
|
|
198
|
+
throw new Error(
|
|
199
|
+
`Invalid field name: ${field}. Expected a valid identifier.`
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
let operator;
|
|
203
|
+
let filterValue;
|
|
204
|
+
if (value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date)) {
|
|
205
|
+
const entries = Object.entries(value);
|
|
206
|
+
if (entries.length !== 1) {
|
|
207
|
+
throw new Error(
|
|
208
|
+
`Invalid filter condition. Expected a value which is a dictionary with a single key that corresponds to an operator but got a dictionary with ${entries.length} keys.`
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
[operator, filterValue] = entries[0];
|
|
212
|
+
if (!SUPPORTED_OPERATORS.has(operator)) {
|
|
213
|
+
throw new Error(
|
|
214
|
+
`Invalid operator: ${operator}. Expected one of ${[...SUPPORTED_OPERATORS].join(", ")}`
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
} else {
|
|
218
|
+
operator = "$eq";
|
|
219
|
+
filterValue = value;
|
|
220
|
+
}
|
|
221
|
+
const { selector, hasJsonPath } = buildFieldSelector(field, ctx);
|
|
222
|
+
let fieldSelector = selector;
|
|
223
|
+
if (hasJsonPath) {
|
|
224
|
+
const sample = Array.isArray(filterValue) ? filterValue[0] : filterValue;
|
|
225
|
+
const postgresType = inferPostgresType(sample);
|
|
226
|
+
if (!postgresType) {
|
|
227
|
+
throw new Error(`Unsupported type for value: ${JSON.stringify(sample)}`);
|
|
228
|
+
}
|
|
229
|
+
if (postgresType !== "TEXT" && operator !== "$exists") {
|
|
230
|
+
fieldSelector = `(${fieldSelector})::${postgresType}`;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
if (operator in COMPARISONS_TO_NATIVE) {
|
|
234
|
+
const native = COMPARISONS_TO_NATIVE[operator];
|
|
235
|
+
const placeholder = ctx.params.add(filterValue);
|
|
236
|
+
return `${fieldSelector} ${native} ${placeholder}`;
|
|
237
|
+
}
|
|
238
|
+
if (operator === "$between") {
|
|
239
|
+
const [low, high] = filterValue;
|
|
240
|
+
const lowPlaceholder = ctx.params.add(low);
|
|
241
|
+
const highPlaceholder = ctx.params.add(high);
|
|
242
|
+
return `(${fieldSelector} BETWEEN ${lowPlaceholder} AND ${highPlaceholder})`;
|
|
243
|
+
}
|
|
244
|
+
if (operator === "$in" || operator === "$nin") {
|
|
245
|
+
const values = filterValue;
|
|
246
|
+
for (const val of values) {
|
|
247
|
+
if (typeof val === "boolean" || !["string", "number"].includes(typeof val)) {
|
|
248
|
+
throw new Error(`Unsupported type for value: ${JSON.stringify(val)}`);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
const placeholder = ctx.params.add(values);
|
|
252
|
+
return operator === "$in" ? `${fieldSelector} = ANY(${placeholder})` : `${fieldSelector} <> ALL(${placeholder})`;
|
|
253
|
+
}
|
|
254
|
+
if (operator === "$like" || operator === "$ilike") {
|
|
255
|
+
const placeholder = ctx.params.add(filterValue);
|
|
256
|
+
return operator === "$like" ? `(${fieldSelector} LIKE ${placeholder})` : `(${fieldSelector} ILIKE ${placeholder})`;
|
|
257
|
+
}
|
|
258
|
+
if (operator === "$exists") {
|
|
259
|
+
if (typeof filterValue !== "boolean") {
|
|
260
|
+
throw new Error(
|
|
261
|
+
`Expected a boolean value for $exists operator, but got: ${filterValue}`
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
return filterValue ? `(${fieldSelector} IS NOT NULL)` : `(${fieldSelector} IS NULL)`;
|
|
265
|
+
}
|
|
266
|
+
throw new Error(`Unsupported operator: ${operator}`);
|
|
267
|
+
}
|
|
268
|
+
function combineFilterClause(filters, handleField) {
|
|
269
|
+
if (typeof filters !== "object" || filters === null || Array.isArray(filters)) {
|
|
270
|
+
throw new Error(
|
|
271
|
+
`Invalid type: Expected an object but got type: ${typeof filters}`
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
const entries = Object.entries(filters);
|
|
275
|
+
if (entries.length === 1) {
|
|
276
|
+
const [key, value] = entries[0];
|
|
277
|
+
if (key.startsWith("$")) {
|
|
278
|
+
const lower = key.toLowerCase();
|
|
279
|
+
if (!["$and", "$or", "$not"].includes(lower)) {
|
|
280
|
+
throw new Error(
|
|
281
|
+
`Invalid filter condition. Expected $and, $or or $not but got: ${key}`
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
if (lower === "$and" || lower === "$or") {
|
|
285
|
+
if (!Array.isArray(value)) {
|
|
286
|
+
throw new Error(
|
|
287
|
+
`Expected a list, but got ${typeof value} for value: ${value}`
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
const op = lower === "$and" ? "AND" : "OR";
|
|
291
|
+
const clauses = value.map((el) => combineFilterClause(el, handleField));
|
|
292
|
+
if (clauses.length > 1) return `(${clauses.join(` ${op} `)})`;
|
|
293
|
+
if (clauses.length === 1) return clauses[0];
|
|
294
|
+
throw new Error(
|
|
295
|
+
"Invalid filter condition. Expected a dictionary but got an empty dictionary"
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
if (Array.isArray(value)) {
|
|
299
|
+
const clauses = value.map(
|
|
300
|
+
(item) => combineFilterClause(item, handleField)
|
|
301
|
+
);
|
|
302
|
+
return `(${clauses.map((c) => `NOT ${c}`).join(" AND ")})`;
|
|
303
|
+
}
|
|
304
|
+
if (typeof value === "object" && value !== null) {
|
|
305
|
+
return `(NOT ${combineFilterClause(value, handleField)})`;
|
|
306
|
+
}
|
|
307
|
+
throw new Error(
|
|
308
|
+
`Invalid filter condition. Expected a dictionary or a list but got: ${typeof value}`
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
return handleField(key, value);
|
|
312
|
+
}
|
|
313
|
+
if (entries.length > 1) {
|
|
314
|
+
for (const [key] of entries) {
|
|
315
|
+
if (key.startsWith("$")) {
|
|
316
|
+
throw new Error(
|
|
317
|
+
`Invalid filter condition. Expected a field but got: ${key}`
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
const clauses = entries.map(([k, v]) => handleField(k, v));
|
|
322
|
+
if (clauses.length > 1) return `(${clauses.join(" AND ")})`;
|
|
323
|
+
if (clauses.length === 1) return clauses[0];
|
|
324
|
+
}
|
|
325
|
+
return "";
|
|
326
|
+
}
|
|
327
|
+
function createFilterClause(filters, ctx) {
|
|
328
|
+
return combineFilterClause(
|
|
329
|
+
filters,
|
|
330
|
+
(field, value) => handleFieldFilter(field, value, ctx)
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// src/indexes.ts
|
|
335
|
+
var DistanceStrategy = {
|
|
336
|
+
EUCLIDEAN: {
|
|
337
|
+
operator: "<->",
|
|
338
|
+
searchFunction: "l2_distance",
|
|
339
|
+
indexFunction: "vector_l2_ops"
|
|
340
|
+
},
|
|
341
|
+
COSINE_DISTANCE: {
|
|
342
|
+
operator: "<=>",
|
|
343
|
+
searchFunction: "cosine_distance",
|
|
344
|
+
indexFunction: "vector_cosine_ops"
|
|
345
|
+
},
|
|
346
|
+
INNER_PRODUCT: {
|
|
347
|
+
operator: "<#>",
|
|
348
|
+
searchFunction: "inner_product",
|
|
349
|
+
indexFunction: "vector_ip_ops"
|
|
350
|
+
}
|
|
351
|
+
};
|
|
352
|
+
var DEFAULT_DISTANCE_STRATEGY = DistanceStrategy.COSINE_DISTANCE;
|
|
353
|
+
var DEFAULT_INDEX_NAME_SUFFIX = "langchainvectorindex";
|
|
354
|
+
function validateIdentifier(identifier) {
|
|
355
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(identifier)) {
|
|
356
|
+
throw new Error(
|
|
357
|
+
`Invalid identifier: ${identifier}. Identifiers must start with a letter or underscore, and subsequent characters can be letters, digits, or underscores.`
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
var BaseIndex = class {
|
|
362
|
+
name;
|
|
363
|
+
indexType = "base";
|
|
364
|
+
distanceStrategy;
|
|
365
|
+
partialIndexes;
|
|
366
|
+
extensionName;
|
|
367
|
+
constructor(args = {}) {
|
|
368
|
+
this.name = args.name;
|
|
369
|
+
this.distanceStrategy = args.distanceStrategy ?? DEFAULT_DISTANCE_STRATEGY;
|
|
370
|
+
this.partialIndexes = args.partialIndexes;
|
|
371
|
+
this.extensionName = args.extensionName;
|
|
372
|
+
if (this.extensionName) validateIdentifier(this.extensionName);
|
|
373
|
+
if (this.indexType) validateIdentifier(this.indexType);
|
|
374
|
+
}
|
|
375
|
+
getIndexFunction() {
|
|
376
|
+
return this.distanceStrategy.indexFunction;
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
var ExactNearestNeighbor = class extends BaseIndex {
|
|
380
|
+
indexType = "exactnearestneighbor";
|
|
381
|
+
indexOptions() {
|
|
382
|
+
return "";
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
var QueryOptions = class {
|
|
386
|
+
};
|
|
387
|
+
var HNSWIndex = class extends BaseIndex {
|
|
388
|
+
indexType = "hnsw";
|
|
389
|
+
m;
|
|
390
|
+
efConstruction;
|
|
391
|
+
constructor(args = {}) {
|
|
392
|
+
super(args);
|
|
393
|
+
this.m = args.m ?? 16;
|
|
394
|
+
this.efConstruction = args.efConstruction ?? 64;
|
|
395
|
+
}
|
|
396
|
+
indexOptions() {
|
|
397
|
+
return `(m = ${this.m}, ef_construction = ${this.efConstruction})`;
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
var HNSWQueryOptions = class extends QueryOptions {
|
|
401
|
+
efSearch;
|
|
402
|
+
constructor(args = {}) {
|
|
403
|
+
super();
|
|
404
|
+
this.efSearch = args.efSearch ?? 40;
|
|
405
|
+
}
|
|
406
|
+
toParameter() {
|
|
407
|
+
return [`hnsw.ef_search = ${this.efSearch}`];
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
var IVFFlatIndex = class extends BaseIndex {
|
|
411
|
+
indexType = "ivfflat";
|
|
412
|
+
lists;
|
|
413
|
+
constructor(args = {}) {
|
|
414
|
+
super(args);
|
|
415
|
+
this.lists = args.lists ?? 100;
|
|
416
|
+
}
|
|
417
|
+
indexOptions() {
|
|
418
|
+
return `(lists = ${this.lists})`;
|
|
419
|
+
}
|
|
420
|
+
};
|
|
421
|
+
var IVFFlatQueryOptions = class extends QueryOptions {
|
|
422
|
+
probes;
|
|
423
|
+
constructor(args = {}) {
|
|
424
|
+
super();
|
|
425
|
+
this.probes = args.probes ?? 1;
|
|
426
|
+
}
|
|
427
|
+
toParameter() {
|
|
428
|
+
return [`ivfflat.probes = ${this.probes}`];
|
|
429
|
+
}
|
|
430
|
+
};
|
|
431
|
+
|
|
432
|
+
// src/vectorstore.ts
|
|
433
|
+
function vectorToSql(embedding) {
|
|
434
|
+
return `[${embedding.join(",")}]`;
|
|
435
|
+
}
|
|
436
|
+
var PGVectorStore = class _PGVectorStore extends VectorStore {
|
|
437
|
+
engine;
|
|
438
|
+
tableName;
|
|
439
|
+
schemaName;
|
|
440
|
+
contentColumn;
|
|
441
|
+
embeddingColumn;
|
|
442
|
+
metadataColumns;
|
|
443
|
+
idColumn;
|
|
444
|
+
metadataJsonColumn;
|
|
445
|
+
distanceStrategy;
|
|
446
|
+
k;
|
|
447
|
+
fetchK;
|
|
448
|
+
lambdaMult;
|
|
449
|
+
indexQueryOptions;
|
|
450
|
+
hybridSearchConfig;
|
|
451
|
+
constructor(embeddings, args) {
|
|
452
|
+
super(embeddings, {});
|
|
453
|
+
this.engine = args.engine;
|
|
454
|
+
this.tableName = args.tableName;
|
|
455
|
+
this.schemaName = args.schemaName;
|
|
456
|
+
this.contentColumn = args.contentColumn;
|
|
457
|
+
this.embeddingColumn = args.embeddingColumn;
|
|
458
|
+
this.metadataColumns = args.metadataColumns;
|
|
459
|
+
this.idColumn = args.idColumn;
|
|
460
|
+
this.metadataJsonColumn = args.metadataJsonColumn;
|
|
461
|
+
this.distanceStrategy = args.distanceStrategy;
|
|
462
|
+
this.k = args.k;
|
|
463
|
+
this.fetchK = args.fetchK;
|
|
464
|
+
this.lambdaMult = args.lambdaMult;
|
|
465
|
+
this.indexQueryOptions = args.indexQueryOptions;
|
|
466
|
+
this.hybridSearchConfig = args.hybridSearchConfig;
|
|
467
|
+
}
|
|
468
|
+
_vectorstoreType() {
|
|
469
|
+
return "pgvector";
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Create a {@link PGVectorStore} bound to an existing table.
|
|
473
|
+
* Use {@link PGEngine.initVectorstoreTable} first to create the table.
|
|
474
|
+
*/
|
|
475
|
+
static async initialize(engine, embeddings, tableName, options = {}) {
|
|
476
|
+
if (typeof embeddings.embedQueryInline === "function" && typeof embeddings.embedQueryInlineTemplate !== "function") {
|
|
477
|
+
throw new Error(
|
|
478
|
+
"The provided embeddings use an outdated inline embedding implementation that is susceptible to SQL injection. Please update your provider to a version that supports embedQueryInlineTemplate."
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
let metadataColumns = options.metadataColumns ?? [];
|
|
482
|
+
if (metadataColumns.length && options.ignoreMetadataColumns?.length) {
|
|
483
|
+
throw new Error(
|
|
484
|
+
"Can not use both metadataColumns and ignoreMetadataColumns."
|
|
485
|
+
);
|
|
486
|
+
}
|
|
487
|
+
const schemaName = options.schemaName ?? "public";
|
|
488
|
+
const idColumn = options.idColumn ?? "langchain_id";
|
|
489
|
+
const contentColumn = options.contentColumn ?? "content";
|
|
490
|
+
const embeddingColumn = options.embeddingColumn ?? "embedding";
|
|
491
|
+
const { rows } = await engine.pool.query(
|
|
492
|
+
"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = $1 AND table_schema = $2",
|
|
493
|
+
[tableName, schemaName]
|
|
494
|
+
);
|
|
495
|
+
const columns = new Map(
|
|
496
|
+
rows.map((row) => [
|
|
497
|
+
row.column_name,
|
|
498
|
+
row.data_type
|
|
499
|
+
])
|
|
500
|
+
);
|
|
501
|
+
if (!columns.has(idColumn)) {
|
|
502
|
+
throw new Error(`Id column, ${idColumn}, does not exist.`);
|
|
503
|
+
}
|
|
504
|
+
if (!columns.has(contentColumn)) {
|
|
505
|
+
throw new Error(`Content column, ${contentColumn}, does not exist.`);
|
|
506
|
+
}
|
|
507
|
+
const contentType = columns.get(contentColumn);
|
|
508
|
+
if (contentType !== "text" && !contentType.includes("char")) {
|
|
509
|
+
throw new Error(
|
|
510
|
+
`Content column, ${contentColumn}, is type, ${contentType}. It must be a type of character string.`
|
|
511
|
+
);
|
|
512
|
+
}
|
|
513
|
+
const hybridSearchConfig = options.hybridSearchConfig;
|
|
514
|
+
if (hybridSearchConfig) {
|
|
515
|
+
const tsvColumnName = hybridSearchConfig.tsvColumn || `${contentColumn}_tsv`;
|
|
516
|
+
if (columns.get(tsvColumnName) !== "tsvector") {
|
|
517
|
+
hybridSearchConfig.tsvColumn = "";
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
if (!columns.has(embeddingColumn)) {
|
|
521
|
+
throw new Error(`Embedding column, ${embeddingColumn}, does not exist.`);
|
|
522
|
+
}
|
|
523
|
+
const embeddingType = columns.get(embeddingColumn);
|
|
524
|
+
if (!["USER-DEFINED", "vector"].includes(embeddingType)) {
|
|
525
|
+
throw new Error(
|
|
526
|
+
`Embedding column, ${embeddingColumn}, is not type Vector.`
|
|
527
|
+
);
|
|
528
|
+
}
|
|
529
|
+
let metadataJsonColumn = options.metadataJsonColumn === null ? void 0 : options.metadataJsonColumn ?? "langchain_metadata";
|
|
530
|
+
if (metadataJsonColumn && !columns.has(metadataJsonColumn)) {
|
|
531
|
+
metadataJsonColumn = void 0;
|
|
532
|
+
}
|
|
533
|
+
for (const column of metadataColumns) {
|
|
534
|
+
if (!columns.has(column)) {
|
|
535
|
+
throw new Error(`Metadata column, ${column}, does not exist.`);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
if (options.ignoreMetadataColumns?.length) {
|
|
539
|
+
const ignored = /* @__PURE__ */ new Set([
|
|
540
|
+
...options.ignoreMetadataColumns,
|
|
541
|
+
idColumn,
|
|
542
|
+
contentColumn,
|
|
543
|
+
embeddingColumn
|
|
544
|
+
]);
|
|
545
|
+
metadataColumns = [...columns.keys()].filter((c) => !ignored.has(c));
|
|
546
|
+
}
|
|
547
|
+
return new _PGVectorStore(embeddings, {
|
|
548
|
+
engine,
|
|
549
|
+
tableName,
|
|
550
|
+
schemaName,
|
|
551
|
+
contentColumn,
|
|
552
|
+
embeddingColumn,
|
|
553
|
+
metadataColumns,
|
|
554
|
+
idColumn,
|
|
555
|
+
metadataJsonColumn,
|
|
556
|
+
distanceStrategy: options.distanceStrategy ?? DEFAULT_DISTANCE_STRATEGY,
|
|
557
|
+
k: options.k ?? 4,
|
|
558
|
+
fetchK: options.fetchK ?? 20,
|
|
559
|
+
lambdaMult: options.lambdaMult ?? 0.5,
|
|
560
|
+
indexQueryOptions: options.indexQueryOptions,
|
|
561
|
+
hybridSearchConfig
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
static async fromTexts(texts, metadatas, embeddings, dbConfig) {
|
|
565
|
+
const { engine, tableName, ids, ...options } = dbConfig;
|
|
566
|
+
const store = await _PGVectorStore.initialize(
|
|
567
|
+
engine,
|
|
568
|
+
embeddings,
|
|
569
|
+
tableName,
|
|
570
|
+
options
|
|
571
|
+
);
|
|
572
|
+
const metadatasArray = Array.isArray(metadatas) ? metadatas : texts.map(() => metadatas);
|
|
573
|
+
await store.addDocuments(
|
|
574
|
+
texts.map(
|
|
575
|
+
(text, i) => new Document({
|
|
576
|
+
pageContent: text,
|
|
577
|
+
metadata: metadatasArray[i] ?? {}
|
|
578
|
+
})
|
|
579
|
+
),
|
|
580
|
+
ids ? { ids } : void 0
|
|
581
|
+
);
|
|
582
|
+
return store;
|
|
583
|
+
}
|
|
584
|
+
static async fromDocuments(docs, embeddings, dbConfig) {
|
|
585
|
+
const { engine, tableName, ids, ...options } = dbConfig;
|
|
586
|
+
const store = await _PGVectorStore.initialize(
|
|
587
|
+
engine,
|
|
588
|
+
embeddings,
|
|
589
|
+
tableName,
|
|
590
|
+
options
|
|
591
|
+
);
|
|
592
|
+
await store.addDocuments(docs, ids ? { ids } : void 0);
|
|
593
|
+
return store;
|
|
594
|
+
}
|
|
595
|
+
filterContext(params) {
|
|
596
|
+
return {
|
|
597
|
+
metadataJsonColumn: this.metadataJsonColumn,
|
|
598
|
+
metadataColumns: this.metadataColumns,
|
|
599
|
+
idColumn: this.idColumn,
|
|
600
|
+
contentColumn: this.contentColumn,
|
|
601
|
+
embeddingColumn: this.embeddingColumn,
|
|
602
|
+
params
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
rowToDocument(row) {
|
|
606
|
+
const metadata = (this.metadataJsonColumn ? row[this.metadataJsonColumn] : void 0) ?? {};
|
|
607
|
+
for (const col of this.metadataColumns) metadata[col] = row[col];
|
|
608
|
+
return new Document({
|
|
609
|
+
pageContent: row[this.contentColumn],
|
|
610
|
+
metadata,
|
|
611
|
+
id: String(row[this.idColumn])
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
async addEmbeddings(texts, embeddings, metadatas, ids) {
|
|
615
|
+
const finalIds = texts.map((_, i) => ids?.[i] ?? randomUUID());
|
|
616
|
+
const finalMetadatas = metadatas && metadatas.length === texts.length ? metadatas : texts.map(() => ({}));
|
|
617
|
+
const client = await this.engine.pool.connect();
|
|
618
|
+
try {
|
|
619
|
+
for (let i = 0; i < texts.length; i += 1) {
|
|
620
|
+
const id = finalIds[i];
|
|
621
|
+
const content = texts[i];
|
|
622
|
+
const embedding = embeddings[i];
|
|
623
|
+
const metadata = { ...finalMetadatas[i] ?? {} };
|
|
624
|
+
const columns = [
|
|
625
|
+
this.idColumn,
|
|
626
|
+
this.contentColumn,
|
|
627
|
+
this.embeddingColumn
|
|
628
|
+
];
|
|
629
|
+
const values = [id, content];
|
|
630
|
+
const valueExprs = ["$1", "$2"];
|
|
631
|
+
if (embedding.length === 0 && typeof this.embeddings.embedQueryInlineTemplate === "function") {
|
|
632
|
+
valueExprs[1] = "$2::text";
|
|
633
|
+
valueExprs.push(this.embeddings.embedQueryInlineTemplate("$2"));
|
|
634
|
+
} else {
|
|
635
|
+
values.push(vectorToSql(embedding));
|
|
636
|
+
valueExprs.push("$3");
|
|
637
|
+
}
|
|
638
|
+
if (this.hybridSearchConfig?.tsvColumn) {
|
|
639
|
+
columns.push(this.hybridSearchConfig.tsvColumn);
|
|
640
|
+
values.push(content);
|
|
641
|
+
const lang = this.hybridSearchConfig.tsvLang;
|
|
642
|
+
valueExprs.push(
|
|
643
|
+
lang ? `to_tsvector('${lang}', $${values.length})` : `to_tsvector($${values.length})`
|
|
644
|
+
);
|
|
645
|
+
}
|
|
646
|
+
for (const col of this.metadataColumns) {
|
|
647
|
+
if (col in metadata) {
|
|
648
|
+
const value = metadata[col];
|
|
649
|
+
values.push(
|
|
650
|
+
value !== null && typeof value === "object" ? JSON.stringify(value) : value
|
|
651
|
+
);
|
|
652
|
+
columns.push(col);
|
|
653
|
+
valueExprs.push(`$${values.length}`);
|
|
654
|
+
delete metadata[col];
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
if (this.metadataJsonColumn) {
|
|
658
|
+
columns.push(this.metadataJsonColumn);
|
|
659
|
+
values.push(JSON.stringify(metadata));
|
|
660
|
+
valueExprs.push(`$${values.length}`);
|
|
661
|
+
}
|
|
662
|
+
const columnList = columns.map((c) => `"${c}"`).join(", ");
|
|
663
|
+
const valuesList = valueExprs.join(", ");
|
|
664
|
+
let upsert = `ON CONFLICT ("${this.idColumn}") DO UPDATE SET "${this.contentColumn}" = EXCLUDED."${this.contentColumn}", "${this.embeddingColumn}" = EXCLUDED."${this.embeddingColumn}"`;
|
|
665
|
+
if (this.hybridSearchConfig?.tsvColumn) {
|
|
666
|
+
upsert += `, "${this.hybridSearchConfig.tsvColumn}" = EXCLUDED."${this.hybridSearchConfig.tsvColumn}"`;
|
|
667
|
+
}
|
|
668
|
+
if (this.metadataJsonColumn) {
|
|
669
|
+
upsert += `, "${this.metadataJsonColumn}" = EXCLUDED."${this.metadataJsonColumn}"`;
|
|
670
|
+
}
|
|
671
|
+
for (const col of this.metadataColumns) {
|
|
672
|
+
upsert += `, "${col}" = EXCLUDED."${col}"`;
|
|
673
|
+
}
|
|
674
|
+
const query = `INSERT INTO "${this.schemaName}"."${this.tableName}" (${columnList}) VALUES (${valuesList}) ${upsert};`;
|
|
675
|
+
await client.query(query, values);
|
|
676
|
+
}
|
|
677
|
+
} finally {
|
|
678
|
+
client.release();
|
|
679
|
+
}
|
|
680
|
+
return finalIds;
|
|
681
|
+
}
|
|
682
|
+
async addVectors(vectors, documents, options) {
|
|
683
|
+
const texts = documents.map((d) => d.pageContent);
|
|
684
|
+
const metadatas = documents.map((d) => d.metadata ?? {});
|
|
685
|
+
const ids = options?.ids ?? documents.map((d) => d.id);
|
|
686
|
+
return this.addEmbeddings(texts, vectors, metadatas, ids);
|
|
687
|
+
}
|
|
688
|
+
async addDocuments(documents, options) {
|
|
689
|
+
const texts = documents.map((d) => d.pageContent);
|
|
690
|
+
const embeddings = this.hasInlineEmbeddings() ? texts.map(() => []) : await this.embeddings.embedDocuments(texts);
|
|
691
|
+
return this.addVectors(embeddings, documents, options);
|
|
692
|
+
}
|
|
693
|
+
/** Embed raw texts and add them to the table. */
|
|
694
|
+
async addTexts(texts, metadatas, ids) {
|
|
695
|
+
const embeddings = this.hasInlineEmbeddings() ? texts.map(() => []) : await this.embeddings.embedDocuments(texts);
|
|
696
|
+
return this.addEmbeddings(texts, embeddings, metadatas, ids);
|
|
697
|
+
}
|
|
698
|
+
hasInlineEmbeddings() {
|
|
699
|
+
return typeof this.embeddings.embedQueryInlineTemplate === "function";
|
|
700
|
+
}
|
|
701
|
+
async delete(params = {}) {
|
|
702
|
+
const { ids, filter } = params;
|
|
703
|
+
if (!ids?.length && !filter) return;
|
|
704
|
+
const paramBuilder = new ParamBuilder();
|
|
705
|
+
const whereClauses = [];
|
|
706
|
+
if (ids?.length) {
|
|
707
|
+
const placeholders = ids.map((id) => paramBuilder.add(id));
|
|
708
|
+
whereClauses.push(`"${this.idColumn}" IN (${placeholders.join(", ")})`);
|
|
709
|
+
}
|
|
710
|
+
if (filter) {
|
|
711
|
+
whereClauses.push(
|
|
712
|
+
createFilterClause(filter, this.filterContext(paramBuilder))
|
|
713
|
+
);
|
|
714
|
+
}
|
|
715
|
+
const query = `DELETE FROM "${this.schemaName}"."${this.tableName}" WHERE ${whereClauses.join(" AND ")}`;
|
|
716
|
+
await this.engine.pool.query(query, paramBuilder.values);
|
|
717
|
+
}
|
|
718
|
+
async queryCollection(embedding, options = {}) {
|
|
719
|
+
const hybridSearchConfig = options.hybridSearchConfig ?? this.hybridSearchConfig;
|
|
720
|
+
const finalK = options.k ?? this.k;
|
|
721
|
+
const denseLimit = hybridSearchConfig ? hybridSearchConfig.primaryTopK : finalK;
|
|
722
|
+
const { operator, searchFunction } = this.distanceStrategy;
|
|
723
|
+
const columns = [
|
|
724
|
+
this.idColumn,
|
|
725
|
+
this.contentColumn,
|
|
726
|
+
this.embeddingColumn,
|
|
727
|
+
...this.metadataColumns
|
|
728
|
+
];
|
|
729
|
+
if (this.metadataJsonColumn) columns.push(this.metadataJsonColumn);
|
|
730
|
+
const columnNames = columns.map((c) => `"${c}"`).join(", ");
|
|
731
|
+
const params = new ParamBuilder();
|
|
732
|
+
let whereFilters = "";
|
|
733
|
+
if (options.filter) {
|
|
734
|
+
const clause = createFilterClause(
|
|
735
|
+
options.filter,
|
|
736
|
+
this.filterContext(params)
|
|
737
|
+
);
|
|
738
|
+
if (clause) whereFilters = `WHERE ${clause}`;
|
|
739
|
+
}
|
|
740
|
+
let inlineEmbeddingExpression;
|
|
741
|
+
if (embedding.length === 0 && options.query !== void 0 && typeof this.embeddings.embedQueryInlineTemplate === "function") {
|
|
742
|
+
inlineEmbeddingExpression = this.embeddings.embedQueryInlineTemplate(
|
|
743
|
+
params.add(options.query)
|
|
744
|
+
);
|
|
745
|
+
}
|
|
746
|
+
const embeddingCte = inlineEmbeddingExpression !== void 0 ? `WITH __langchain_query_embedding AS MATERIALIZED (SELECT ${inlineEmbeddingExpression} AS embedding) ` : "";
|
|
747
|
+
const embeddingExpression = inlineEmbeddingExpression !== void 0 ? "(SELECT embedding FROM __langchain_query_embedding)" : params.add(vectorToSql(embedding));
|
|
748
|
+
const denseLimitPlaceholder = params.add(denseLimit);
|
|
749
|
+
const denseQuery = `${embeddingCte}SELECT ${columnNames}, ${searchFunction}("${this.embeddingColumn}", ${embeddingExpression}) as distance
|
|
750
|
+
FROM "${this.schemaName}"."${this.tableName}" ${whereFilters}
|
|
751
|
+
ORDER BY "${this.embeddingColumn}" ${operator} ${embeddingExpression} LIMIT ${denseLimitPlaceholder};`;
|
|
752
|
+
let denseResults;
|
|
753
|
+
const client = await this.engine.pool.connect();
|
|
754
|
+
try {
|
|
755
|
+
if (this.indexQueryOptions) {
|
|
756
|
+
for (const option of this.indexQueryOptions.toParameter()) {
|
|
757
|
+
await client.query(`SET LOCAL ${option};`);
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
const result = await client.query(denseQuery, params.values);
|
|
761
|
+
denseResults = result.rows;
|
|
762
|
+
} finally {
|
|
763
|
+
client.release();
|
|
764
|
+
}
|
|
765
|
+
const ftsQuery = hybridSearchConfig?.ftsQuery || options.ftsQuery || "";
|
|
766
|
+
if (hybridSearchConfig && ftsQuery) {
|
|
767
|
+
hybridSearchConfig.fusionFunctionParameters = {
|
|
768
|
+
...hybridSearchConfig.fusionFunctionParameters,
|
|
769
|
+
fetchTopK: finalK
|
|
770
|
+
};
|
|
771
|
+
const sparseParams = new ParamBuilder();
|
|
772
|
+
let sparseWhere = "";
|
|
773
|
+
if (options.filter) {
|
|
774
|
+
const clause = createFilterClause(
|
|
775
|
+
options.filter,
|
|
776
|
+
this.filterContext(sparseParams)
|
|
777
|
+
);
|
|
778
|
+
if (clause) sparseWhere = `AND (${clause})`;
|
|
779
|
+
}
|
|
780
|
+
const lang = hybridSearchConfig.tsvLang;
|
|
781
|
+
const ftsQueryPlaceholder = sparseParams.add(ftsQuery);
|
|
782
|
+
const queryTsv = lang ? `plainto_tsquery('${lang}', ${ftsQueryPlaceholder})` : `plainto_tsquery(${ftsQueryPlaceholder})`;
|
|
783
|
+
const contentTsv = hybridSearchConfig.tsvColumn ? `"${hybridSearchConfig.tsvColumn}"` : lang ? `to_tsvector('${lang}', "${this.contentColumn}")` : `to_tsvector("${this.contentColumn}")`;
|
|
784
|
+
const secondaryLimitPlaceholder = sparseParams.add(
|
|
785
|
+
hybridSearchConfig.secondaryTopK
|
|
786
|
+
);
|
|
787
|
+
const sparseQuery = `SELECT ${columnNames}, ts_rank_cd(${contentTsv}, ${queryTsv}) as distance
|
|
788
|
+
FROM "${this.schemaName}"."${this.tableName}"
|
|
789
|
+
WHERE ${contentTsv} @@ ${queryTsv} ${sparseWhere}
|
|
790
|
+
ORDER BY distance DESC LIMIT ${secondaryLimitPlaceholder};`;
|
|
791
|
+
const sparseResult = await this.engine.pool.query(
|
|
792
|
+
sparseQuery,
|
|
793
|
+
sparseParams.values
|
|
794
|
+
);
|
|
795
|
+
return hybridSearchConfig.fusionFunction(
|
|
796
|
+
denseResults,
|
|
797
|
+
sparseResult.rows,
|
|
798
|
+
{
|
|
799
|
+
...hybridSearchConfig.fusionFunctionParameters,
|
|
800
|
+
distanceStrategy: this.distanceStrategy
|
|
801
|
+
}
|
|
802
|
+
);
|
|
803
|
+
}
|
|
804
|
+
return denseResults;
|
|
805
|
+
}
|
|
806
|
+
async similaritySearch(query, k, filter) {
|
|
807
|
+
const results = await this.similaritySearchWithScore(query, k, filter);
|
|
808
|
+
return results.map(([doc]) => doc);
|
|
809
|
+
}
|
|
810
|
+
async similaritySearchWithScore(query, k, filter) {
|
|
811
|
+
const embedding = this.hasInlineEmbeddings() ? [] : await this.embeddings.embedQuery(query);
|
|
812
|
+
if (this.hybridSearchConfig && !this.hybridSearchConfig.ftsQuery) {
|
|
813
|
+
this.hybridSearchConfig.ftsQuery = query;
|
|
814
|
+
}
|
|
815
|
+
return this.similaritySearchVectorWithScoreInternal(
|
|
816
|
+
embedding,
|
|
817
|
+
k,
|
|
818
|
+
filter,
|
|
819
|
+
query
|
|
820
|
+
);
|
|
821
|
+
}
|
|
822
|
+
async similaritySearchByVector(embedding, k, filter) {
|
|
823
|
+
const results = await this.similaritySearchVectorWithScore(
|
|
824
|
+
embedding,
|
|
825
|
+
k ?? this.k,
|
|
826
|
+
filter
|
|
827
|
+
);
|
|
828
|
+
return results.map(([doc]) => doc);
|
|
829
|
+
}
|
|
830
|
+
async similaritySearchVectorWithScore(embedding, k, filter) {
|
|
831
|
+
return this.similaritySearchVectorWithScoreInternal(embedding, k, filter);
|
|
832
|
+
}
|
|
833
|
+
async similaritySearchVectorWithScoreInternal(embedding, k, filter, query) {
|
|
834
|
+
const rows = await this.queryCollection(embedding, {
|
|
835
|
+
k,
|
|
836
|
+
filter,
|
|
837
|
+
query,
|
|
838
|
+
ftsQuery: query
|
|
839
|
+
});
|
|
840
|
+
return rows.map((row) => [this.rowToDocument(row), Number(row.distance)]);
|
|
841
|
+
}
|
|
842
|
+
async maxMarginalRelevanceSearch(query, options) {
|
|
843
|
+
const embedding = await this.embeddings.embedQuery(query);
|
|
844
|
+
return this.maxMarginalRelevanceSearchByVector(embedding, {
|
|
845
|
+
k: options.k,
|
|
846
|
+
fetchK: options.fetchK,
|
|
847
|
+
lambda: options.lambda,
|
|
848
|
+
filter: options.filter
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
async maxMarginalRelevanceSearchByVector(embedding, options = {}) {
|
|
852
|
+
const results = await this.maxMarginalRelevanceSearchWithScoreByVector(
|
|
853
|
+
embedding,
|
|
854
|
+
options
|
|
855
|
+
);
|
|
856
|
+
return results.map(([doc]) => doc);
|
|
857
|
+
}
|
|
858
|
+
async maxMarginalRelevanceSearchWithScoreByVector(embedding, options = {}) {
|
|
859
|
+
const fetchK = options.fetchK ?? this.fetchK;
|
|
860
|
+
const k = options.k ?? this.k;
|
|
861
|
+
const lambdaMult = options.lambda ?? this.lambdaMult;
|
|
862
|
+
const rows = await this.queryCollection(embedding, {
|
|
863
|
+
k: fetchK,
|
|
864
|
+
filter: options.filter
|
|
865
|
+
});
|
|
866
|
+
const embeddingList = rows.map(
|
|
867
|
+
(row) => JSON.parse(row[this.embeddingColumn])
|
|
868
|
+
);
|
|
869
|
+
const selected = new Set(
|
|
870
|
+
maximalMarginalRelevance(embedding, embeddingList, lambdaMult, k)
|
|
871
|
+
);
|
|
872
|
+
return rows.map((row) => [
|
|
873
|
+
this.rowToDocument(row),
|
|
874
|
+
Number(row.distance)
|
|
875
|
+
]).filter((_, i) => selected.has(i));
|
|
876
|
+
}
|
|
877
|
+
/** Create a full-text-search (TSV) index for hybrid search. */
|
|
878
|
+
async applyHybridSearchIndex(concurrently = false) {
|
|
879
|
+
const cfg = this.hybridSearchConfig;
|
|
880
|
+
if (!cfg || !cfg.indexType || !cfg.indexName) {
|
|
881
|
+
throw new Error("Hybrid Search Config cannot create index.");
|
|
882
|
+
}
|
|
883
|
+
const lang = cfg.tsvLang;
|
|
884
|
+
const tsvColumnName = cfg.tsvColumn || (lang ? `to_tsvector('${lang}', ${this.contentColumn})` : `to_tsvector(${this.contentColumn})`);
|
|
885
|
+
const query = `CREATE INDEX ${concurrently ? "CONCURRENTLY" : ""} ${cfg.indexName} ON "${this.schemaName}"."${this.tableName}" USING ${cfg.indexType}(${tsvColumnName});`;
|
|
886
|
+
await this.engine.pool.query(query);
|
|
887
|
+
}
|
|
888
|
+
/** Create a vector index on the embedding column. Pass an {@link ExactNearestNeighbor} to drop the index instead. */
|
|
889
|
+
async applyVectorIndex(index, name, options = {}) {
|
|
890
|
+
if (index instanceof ExactNearestNeighbor) {
|
|
891
|
+
await this.dropVectorIndex();
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
if (index.extensionName) {
|
|
895
|
+
await this.engine.pool.query(
|
|
896
|
+
`CREATE EXTENSION IF NOT EXISTS ${index.extensionName}`
|
|
897
|
+
);
|
|
898
|
+
}
|
|
899
|
+
const indexFunction = index.getIndexFunction();
|
|
900
|
+
const filterClause = index.partialIndexes?.length ? `WHERE (${index.partialIndexes.join(" AND ")})` : "";
|
|
901
|
+
const withOptions = `WITH ${index.indexOptions()}`;
|
|
902
|
+
const indexName = name ?? index.name ?? `${this.tableName}${DEFAULT_INDEX_NAME_SUFFIX}`;
|
|
903
|
+
index.name ??= indexName;
|
|
904
|
+
const stmt = `CREATE INDEX ${options.concurrently ? "CONCURRENTLY" : ""} "${indexName}" ON "${this.schemaName}"."${this.tableName}" USING ${index.indexType} ("${this.embeddingColumn}" ${indexFunction}) ${withOptions} ${filterClause};`;
|
|
905
|
+
await this.engine.pool.query(stmt);
|
|
906
|
+
}
|
|
907
|
+
async reindex(indexName) {
|
|
908
|
+
const name = indexName ?? `${this.tableName}${DEFAULT_INDEX_NAME_SUFFIX}`;
|
|
909
|
+
await this.engine.pool.query(
|
|
910
|
+
`REINDEX INDEX "${this.schemaName}"."${name}";`
|
|
911
|
+
);
|
|
912
|
+
}
|
|
913
|
+
async dropVectorIndex(indexName) {
|
|
914
|
+
const name = indexName ?? `${this.tableName}${DEFAULT_INDEX_NAME_SUFFIX}`;
|
|
915
|
+
await this.engine.pool.query(
|
|
916
|
+
`DROP INDEX IF EXISTS "${this.schemaName}"."${name}";`
|
|
917
|
+
);
|
|
918
|
+
}
|
|
919
|
+
async isValidIndex(indexName) {
|
|
920
|
+
const name = indexName ?? `${this.tableName}${DEFAULT_INDEX_NAME_SUFFIX}`;
|
|
921
|
+
const result = await this.engine.pool.query(
|
|
922
|
+
"SELECT tablename, indexname FROM pg_indexes WHERE tablename = $1 AND schemaname = $2 AND indexname = $3;",
|
|
923
|
+
[this.tableName, this.schemaName, name]
|
|
924
|
+
);
|
|
925
|
+
return result.rows.length === 1;
|
|
926
|
+
}
|
|
927
|
+
async queryCollectionWithFilter(options) {
|
|
928
|
+
const columnNames = options.columns.map((c) => `"${c}"`).join(", ");
|
|
929
|
+
const params = new ParamBuilder();
|
|
930
|
+
let whereFilters = "";
|
|
931
|
+
if (options.filter) {
|
|
932
|
+
const clause = createFilterClause(
|
|
933
|
+
options.filter,
|
|
934
|
+
this.filterContext(params)
|
|
935
|
+
);
|
|
936
|
+
if (clause) whereFilters = `WHERE ${clause}`;
|
|
937
|
+
}
|
|
938
|
+
const limitPlaceholder = params.add(options.limit ?? null);
|
|
939
|
+
const offsetPlaceholder = params.add(options.offset ?? null);
|
|
940
|
+
const query = `SELECT ${columnNames} FROM "${this.schemaName}"."${this.tableName}" ${whereFilters} LIMIT ${limitPlaceholder} OFFSET ${offsetPlaceholder};`;
|
|
941
|
+
const result = await this.engine.pool.query(query, params.values);
|
|
942
|
+
return result.rows;
|
|
943
|
+
}
|
|
944
|
+
/** Retrieve documents using filters, similar to a Chroma-style `get()`. */
|
|
945
|
+
async get(options = {}) {
|
|
946
|
+
const filters = [];
|
|
947
|
+
if (options.ids?.length)
|
|
948
|
+
filters.push({ [this.idColumn]: { $in: options.ids } });
|
|
949
|
+
if (options.where) filters.push(options.where);
|
|
950
|
+
if (options.whereDocument)
|
|
951
|
+
filters.push({ [this.contentColumn]: options.whereDocument });
|
|
952
|
+
const finalFilter = filters.length ? { $and: filters } : void 0;
|
|
953
|
+
const include = options.include ?? ["metadatas", "documents"];
|
|
954
|
+
const fieldsMapping = {
|
|
955
|
+
embeddings: [this.embeddingColumn],
|
|
956
|
+
metadatas: this.metadataJsonColumn ? [...this.metadataColumns, this.metadataJsonColumn] : [...this.metadataColumns],
|
|
957
|
+
documents: [this.contentColumn]
|
|
958
|
+
};
|
|
959
|
+
const includedFields = ["ids"];
|
|
960
|
+
const columns = [this.idColumn];
|
|
961
|
+
for (const [field, cols] of Object.entries(fieldsMapping)) {
|
|
962
|
+
if (include.includes(field)) {
|
|
963
|
+
includedFields.push(field);
|
|
964
|
+
columns.push(...cols);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
const rows = await this.queryCollectionWithFilter({
|
|
968
|
+
limit: options.limit,
|
|
969
|
+
offset: options.offset,
|
|
970
|
+
filter: finalFilter,
|
|
971
|
+
columns
|
|
972
|
+
});
|
|
973
|
+
const finalResults = Object.fromEntries(
|
|
974
|
+
includedFields.map((f) => [f, []])
|
|
975
|
+
);
|
|
976
|
+
for (const row of rows) {
|
|
977
|
+
finalResults.ids.push(String(row[this.idColumn]));
|
|
978
|
+
if (includedFields.includes("metadatas")) {
|
|
979
|
+
const metadata = {
|
|
980
|
+
...(this.metadataJsonColumn ? row[this.metadataJsonColumn] : void 0) ?? {}
|
|
981
|
+
};
|
|
982
|
+
for (const col of this.metadataColumns) metadata[col] = row[col];
|
|
983
|
+
finalResults.metadatas.push(metadata);
|
|
984
|
+
}
|
|
985
|
+
if (includedFields.includes("documents")) {
|
|
986
|
+
finalResults.documents.push(row[this.contentColumn]);
|
|
987
|
+
}
|
|
988
|
+
if (includedFields.includes("embeddings")) {
|
|
989
|
+
finalResults.embeddings.push(JSON.parse(row[this.embeddingColumn]));
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
return finalResults;
|
|
993
|
+
}
|
|
994
|
+
async getByIds(ids) {
|
|
995
|
+
const columns = [
|
|
996
|
+
...this.metadataColumns,
|
|
997
|
+
this.idColumn,
|
|
998
|
+
this.contentColumn
|
|
999
|
+
];
|
|
1000
|
+
if (this.metadataJsonColumn) columns.push(this.metadataJsonColumn);
|
|
1001
|
+
const columnNames = columns.map((c) => `"${c}"`).join(", ");
|
|
1002
|
+
const params = new ParamBuilder();
|
|
1003
|
+
const placeholders = ids.map((id) => params.add(id));
|
|
1004
|
+
const query = `SELECT ${columnNames} FROM "${this.schemaName}"."${this.tableName}" WHERE "${this.idColumn}" IN (${placeholders.join(", ")});`;
|
|
1005
|
+
const result = await this.engine.pool.query(query, params.values);
|
|
1006
|
+
return result.rows.map((row) => this.rowToDocument(row));
|
|
1007
|
+
}
|
|
1008
|
+
};
|
|
1009
|
+
|
|
1010
|
+
// src/hybrid_search.ts
|
|
1011
|
+
function normalizeScores(results, isDistanceMetric) {
|
|
1012
|
+
if (results.length === 0) return [];
|
|
1013
|
+
const lastValue = (row) => {
|
|
1014
|
+
const values = Object.values(row);
|
|
1015
|
+
return Number(values[values.length - 1]);
|
|
1016
|
+
};
|
|
1017
|
+
const scores = results.map(lastValue);
|
|
1018
|
+
const minScore = Math.min(...scores);
|
|
1019
|
+
const maxScore = Math.max(...scores);
|
|
1020
|
+
const scoreRange = maxScore - minScore;
|
|
1021
|
+
if (scoreRange === 0) {
|
|
1022
|
+
return results.map((item) => ({ ...item, normalized_score: 1 }));
|
|
1023
|
+
}
|
|
1024
|
+
return results.map((item) => {
|
|
1025
|
+
const score = lastValue(item);
|
|
1026
|
+
const normalized = (score - minScore) / scoreRange;
|
|
1027
|
+
const normalizedScore = isDistanceMetric ? 1 - normalized : normalized;
|
|
1028
|
+
return { ...item, normalized_score: normalizedScore };
|
|
1029
|
+
});
|
|
1030
|
+
}
|
|
1031
|
+
var weightedSumRanking = (primarySearchResults, secondarySearchResults, params = {}) => {
|
|
1032
|
+
const primaryResultsWeight = params.primaryResultsWeight ?? 0.5;
|
|
1033
|
+
const secondaryResultsWeight = params.secondaryResultsWeight ?? 0.5;
|
|
1034
|
+
const fetchTopK = params.fetchTopK ?? 4;
|
|
1035
|
+
const distanceStrategy = params.distanceStrategy ?? DistanceStrategy.COSINE_DISTANCE;
|
|
1036
|
+
const isPrimaryDistance = distanceStrategy !== DistanceStrategy.INNER_PRODUCT;
|
|
1037
|
+
const normalizedPrimary = normalizeScores(
|
|
1038
|
+
primarySearchResults,
|
|
1039
|
+
isPrimaryDistance
|
|
1040
|
+
);
|
|
1041
|
+
const normalizedSecondary = normalizeScores(secondarySearchResults, false);
|
|
1042
|
+
const weightedScores = /* @__PURE__ */ new Map();
|
|
1043
|
+
for (const item of normalizedPrimary) {
|
|
1044
|
+
const docId = String(Object.values(item)[0]);
|
|
1045
|
+
const row = {
|
|
1046
|
+
...item,
|
|
1047
|
+
distance: item.normalized_score * primaryResultsWeight
|
|
1048
|
+
};
|
|
1049
|
+
weightedScores.set(docId, row);
|
|
1050
|
+
}
|
|
1051
|
+
for (const item of normalizedSecondary) {
|
|
1052
|
+
const docId = String(Object.values(item)[0]);
|
|
1053
|
+
const secondaryWeightedScore = item.normalized_score * secondaryResultsWeight;
|
|
1054
|
+
const existing = weightedScores.get(docId);
|
|
1055
|
+
if (existing) {
|
|
1056
|
+
existing.distance += secondaryWeightedScore;
|
|
1057
|
+
} else {
|
|
1058
|
+
weightedScores.set(docId, {
|
|
1059
|
+
...item,
|
|
1060
|
+
distance: secondaryWeightedScore
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
const ranked = [...weightedScores.values()].sort(
|
|
1065
|
+
(a, b) => b.distance - a.distance
|
|
1066
|
+
);
|
|
1067
|
+
for (const row of ranked) delete row.normalized_score;
|
|
1068
|
+
return ranked.slice(0, fetchTopK);
|
|
1069
|
+
};
|
|
1070
|
+
var reciprocalRankFusion = (primarySearchResults, secondarySearchResults, params = {}) => {
|
|
1071
|
+
const rrfK = params.rrfK ?? 60;
|
|
1072
|
+
const fetchTopK = params.fetchTopK ?? 4;
|
|
1073
|
+
const distanceStrategy = params.distanceStrategy ?? DistanceStrategy.COSINE_DISTANCE;
|
|
1074
|
+
const isSimilarityMetric = distanceStrategy === DistanceStrategy.INNER_PRODUCT;
|
|
1075
|
+
const rrfScores = /* @__PURE__ */ new Map();
|
|
1076
|
+
const sortedPrimary = [...primarySearchResults].sort(
|
|
1077
|
+
(a, b) => isSimilarityMetric ? b.distance - a.distance : a.distance - b.distance
|
|
1078
|
+
);
|
|
1079
|
+
sortedPrimary.forEach((row, rank) => {
|
|
1080
|
+
const docId = String(Object.values(row)[0]);
|
|
1081
|
+
if (!rrfScores.has(docId)) {
|
|
1082
|
+
rrfScores.set(docId, { ...row, distance: 0 });
|
|
1083
|
+
}
|
|
1084
|
+
rrfScores.get(docId).distance += 1 / (rank + rrfK);
|
|
1085
|
+
});
|
|
1086
|
+
const sortedSecondary = [...secondarySearchResults].sort(
|
|
1087
|
+
(a, b) => b.distance - a.distance
|
|
1088
|
+
);
|
|
1089
|
+
sortedSecondary.forEach((row, rank) => {
|
|
1090
|
+
const docId = String(Object.values(row)[0]);
|
|
1091
|
+
if (!rrfScores.has(docId)) {
|
|
1092
|
+
rrfScores.set(docId, { ...row, distance: 0 });
|
|
1093
|
+
}
|
|
1094
|
+
rrfScores.get(docId).distance += 1 / (rank + rrfK);
|
|
1095
|
+
});
|
|
1096
|
+
const ranked = [...rrfScores.values()].sort(
|
|
1097
|
+
(a, b) => b.distance - a.distance
|
|
1098
|
+
);
|
|
1099
|
+
return ranked.slice(0, fetchTopK);
|
|
1100
|
+
};
|
|
1101
|
+
var HybridSearchConfig = class {
|
|
1102
|
+
tsvColumn;
|
|
1103
|
+
tsvLang;
|
|
1104
|
+
ftsQuery;
|
|
1105
|
+
fusionFunction;
|
|
1106
|
+
fusionFunctionParameters;
|
|
1107
|
+
primaryTopK;
|
|
1108
|
+
secondaryTopK;
|
|
1109
|
+
indexName;
|
|
1110
|
+
indexType;
|
|
1111
|
+
constructor(args = {}) {
|
|
1112
|
+
this.tsvColumn = args.tsvColumn ?? "";
|
|
1113
|
+
this.tsvLang = args.tsvLang ?? "pg_catalog.english";
|
|
1114
|
+
this.ftsQuery = args.ftsQuery ?? "";
|
|
1115
|
+
this.fusionFunction = args.fusionFunction ?? weightedSumRanking;
|
|
1116
|
+
this.fusionFunctionParameters = args.fusionFunctionParameters ?? {};
|
|
1117
|
+
this.primaryTopK = args.primaryTopK ?? 4;
|
|
1118
|
+
this.secondaryTopK = args.secondaryTopK ?? 4;
|
|
1119
|
+
this.indexName = args.indexName ?? "langchain_tsv_index";
|
|
1120
|
+
this.indexType = args.indexType ?? "GIN";
|
|
1121
|
+
}
|
|
1122
|
+
};
|
|
1123
|
+
|
|
1124
|
+
// src/translator.ts
|
|
1125
|
+
import {
|
|
1126
|
+
Comparators,
|
|
1127
|
+
Operators,
|
|
1128
|
+
Visitor
|
|
1129
|
+
} from "@langchain/core/structured_query";
|
|
1130
|
+
var PGVectorTranslator = class extends Visitor {
|
|
1131
|
+
allowedOperators = [Operators.and, Operators.or];
|
|
1132
|
+
allowedComparators = [
|
|
1133
|
+
Comparators.eq,
|
|
1134
|
+
Comparators.ne,
|
|
1135
|
+
Comparators.gt,
|
|
1136
|
+
Comparators.lt,
|
|
1137
|
+
Comparators.gte,
|
|
1138
|
+
Comparators.lte
|
|
1139
|
+
];
|
|
1140
|
+
validateFunction(func) {
|
|
1141
|
+
if (!this.allowedOperators.includes(func) && !this.allowedComparators.includes(func)) {
|
|
1142
|
+
throw new Error(`Received disallowed function ${func}`);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
formatFunction(func) {
|
|
1146
|
+
this.validateFunction(func);
|
|
1147
|
+
return `$${func}`;
|
|
1148
|
+
}
|
|
1149
|
+
visitOperation(operation) {
|
|
1150
|
+
const args = operation.args?.map((arg) => arg.accept(this)) ?? [];
|
|
1151
|
+
return { [this.formatFunction(operation.operator)]: args };
|
|
1152
|
+
}
|
|
1153
|
+
visitComparison(comparison) {
|
|
1154
|
+
return {
|
|
1155
|
+
[comparison.attribute]: {
|
|
1156
|
+
[this.formatFunction(comparison.comparator)]: comparison.value
|
|
1157
|
+
}
|
|
1158
|
+
};
|
|
1159
|
+
}
|
|
1160
|
+
visitStructuredQuery(structuredQuery) {
|
|
1161
|
+
if (!structuredQuery.filter) return {};
|
|
1162
|
+
return {
|
|
1163
|
+
filter: structuredQuery.filter.accept(this)
|
|
1164
|
+
};
|
|
1165
|
+
}
|
|
1166
|
+
};
|
|
1167
|
+
|
|
1168
|
+
// src/chat_message_history.ts
|
|
1169
|
+
import { BaseListChatMessageHistory } from "@langchain/core/chat_history";
|
|
1170
|
+
import {
|
|
1171
|
+
mapChatMessagesToStoredMessages,
|
|
1172
|
+
mapStoredMessagesToChatMessages
|
|
1173
|
+
} from "@langchain/core/messages";
|
|
1174
|
+
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
1175
|
+
function createTableAndIndexSql(tableName) {
|
|
1176
|
+
const indexName = `idx_${tableName}_session_id`;
|
|
1177
|
+
return [
|
|
1178
|
+
`CREATE TABLE IF NOT EXISTS "${tableName}" (
|
|
1179
|
+
id SERIAL PRIMARY KEY,
|
|
1180
|
+
session_id UUID NOT NULL,
|
|
1181
|
+
message JSONB NOT NULL,
|
|
1182
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
1183
|
+
);`,
|
|
1184
|
+
`CREATE INDEX IF NOT EXISTS "${indexName}" ON "${tableName}" (session_id);`
|
|
1185
|
+
];
|
|
1186
|
+
}
|
|
1187
|
+
function assertSafeTableName(tableName) {
|
|
1188
|
+
if (!/^\w+$/.test(tableName)) {
|
|
1189
|
+
throw new Error(
|
|
1190
|
+
"Invalid table name. Table name must contain only alphanumeric characters and underscores."
|
|
1191
|
+
);
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
var PostgresChatMessageHistory = class extends BaseListChatMessageHistory {
|
|
1195
|
+
lc_namespace = ["langchain", "stores", "message", "postgres"];
|
|
1196
|
+
pool;
|
|
1197
|
+
tableName;
|
|
1198
|
+
sessionId;
|
|
1199
|
+
constructor(fields) {
|
|
1200
|
+
super();
|
|
1201
|
+
if (!UUID_RE.test(fields.sessionId)) {
|
|
1202
|
+
throw new Error(
|
|
1203
|
+
`Invalid session id. Session id must be a valid UUID. Got ${fields.sessionId}`
|
|
1204
|
+
);
|
|
1205
|
+
}
|
|
1206
|
+
assertSafeTableName(fields.tableName);
|
|
1207
|
+
this.pool = fields.pool;
|
|
1208
|
+
this.tableName = fields.tableName;
|
|
1209
|
+
this.sessionId = fields.sessionId;
|
|
1210
|
+
}
|
|
1211
|
+
/** Create the table schema in the database and create relevant indexes. */
|
|
1212
|
+
static async createTables(connection, tableName) {
|
|
1213
|
+
assertSafeTableName(tableName);
|
|
1214
|
+
for (const query of createTableAndIndexSql(tableName)) {
|
|
1215
|
+
await connection.query(query);
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
/**
|
|
1219
|
+
* Delete the table schema in the database.
|
|
1220
|
+
*
|
|
1221
|
+
* WARNING: This will delete the given table from the database including
|
|
1222
|
+
* all the data in the table and the schema of the table.
|
|
1223
|
+
*/
|
|
1224
|
+
static async dropTable(connection, tableName) {
|
|
1225
|
+
assertSafeTableName(tableName);
|
|
1226
|
+
await connection.query(`DROP TABLE IF EXISTS "${tableName}";`);
|
|
1227
|
+
}
|
|
1228
|
+
async getMessages() {
|
|
1229
|
+
const result = await this.pool.query(
|
|
1230
|
+
`SELECT message FROM "${this.tableName}" WHERE session_id = $1 ORDER BY id;`,
|
|
1231
|
+
[this.sessionId]
|
|
1232
|
+
);
|
|
1233
|
+
return mapStoredMessagesToChatMessages(
|
|
1234
|
+
result.rows.map((row) => row.message)
|
|
1235
|
+
);
|
|
1236
|
+
}
|
|
1237
|
+
async addMessage(message) {
|
|
1238
|
+
await this.addMessages([message]);
|
|
1239
|
+
}
|
|
1240
|
+
async addMessages(messages) {
|
|
1241
|
+
if (messages.length === 0) return;
|
|
1242
|
+
const stored = mapChatMessagesToStoredMessages(messages);
|
|
1243
|
+
const params = [];
|
|
1244
|
+
const valuesSql = stored.map((message) => {
|
|
1245
|
+
params.push(this.sessionId, JSON.stringify(message));
|
|
1246
|
+
return `($${params.length - 1}, $${params.length})`;
|
|
1247
|
+
});
|
|
1248
|
+
await this.pool.query(
|
|
1249
|
+
`INSERT INTO "${this.tableName}" (session_id, message) VALUES ${valuesSql.join(", ")}`,
|
|
1250
|
+
params
|
|
1251
|
+
);
|
|
1252
|
+
}
|
|
1253
|
+
async clear() {
|
|
1254
|
+
await this.pool.query(
|
|
1255
|
+
`DELETE FROM "${this.tableName}" WHERE session_id = $1;`,
|
|
1256
|
+
[this.sessionId]
|
|
1257
|
+
);
|
|
1258
|
+
}
|
|
1259
|
+
};
|
|
1260
|
+
|
|
1261
|
+
// src/legacy/vectorstore.ts
|
|
1262
|
+
import { Document as Document2 } from "@langchain/core/documents";
|
|
1263
|
+
import { maximalMarginalRelevance as maximalMarginalRelevance2 } from "@langchain/core/utils/math";
|
|
1264
|
+
import {
|
|
1265
|
+
VectorStore as VectorStore2
|
|
1266
|
+
} from "@langchain/core/vectorstores";
|
|
1267
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
1268
|
+
|
|
1269
|
+
// src/legacy/filter.ts
|
|
1270
|
+
var COMPARISONS_TO_JSONPATH = {
|
|
1271
|
+
$eq: "==",
|
|
1272
|
+
$ne: "!=",
|
|
1273
|
+
$lt: "<",
|
|
1274
|
+
$lte: "<=",
|
|
1275
|
+
$gt: ">",
|
|
1276
|
+
$gte: ">="
|
|
1277
|
+
};
|
|
1278
|
+
var SUPPORTED_OPERATORS2 = /* @__PURE__ */ new Set([
|
|
1279
|
+
...Object.keys(COMPARISONS_TO_JSONPATH),
|
|
1280
|
+
"$in",
|
|
1281
|
+
"$nin",
|
|
1282
|
+
"$between",
|
|
1283
|
+
"$exists",
|
|
1284
|
+
"$like",
|
|
1285
|
+
"$ilike",
|
|
1286
|
+
"$and",
|
|
1287
|
+
"$or",
|
|
1288
|
+
"$not"
|
|
1289
|
+
]);
|
|
1290
|
+
function isIdentifier2(value) {
|
|
1291
|
+
return /^[A-Za-z_][A-Za-z0-9_]*$/.test(value);
|
|
1292
|
+
}
|
|
1293
|
+
function handleFieldFilter2(field, value, params) {
|
|
1294
|
+
if (typeof field !== "string") {
|
|
1295
|
+
throw new Error(`field should be a string but got: ${typeof field}`);
|
|
1296
|
+
}
|
|
1297
|
+
if (field.startsWith("$")) {
|
|
1298
|
+
throw new Error(
|
|
1299
|
+
`Invalid filter condition. Expected a field but got an operator: ${field}`
|
|
1300
|
+
);
|
|
1301
|
+
}
|
|
1302
|
+
if (!isIdentifier2(field)) {
|
|
1303
|
+
throw new Error(
|
|
1304
|
+
`Invalid field name: ${field}. Expected a valid identifier.`
|
|
1305
|
+
);
|
|
1306
|
+
}
|
|
1307
|
+
let operator;
|
|
1308
|
+
let filterValue;
|
|
1309
|
+
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
|
|
1310
|
+
const entries = Object.entries(value);
|
|
1311
|
+
if (entries.length !== 1) {
|
|
1312
|
+
throw new Error(
|
|
1313
|
+
`Invalid filter condition. Expected a value which is a dictionary with a single key that corresponds to an operator but got a dictionary with ${entries.length} keys.`
|
|
1314
|
+
);
|
|
1315
|
+
}
|
|
1316
|
+
[operator, filterValue] = entries[0];
|
|
1317
|
+
if (!SUPPORTED_OPERATORS2.has(operator)) {
|
|
1318
|
+
throw new Error(`Invalid operator: ${operator}`);
|
|
1319
|
+
}
|
|
1320
|
+
} else {
|
|
1321
|
+
operator = "$eq";
|
|
1322
|
+
filterValue = value;
|
|
1323
|
+
}
|
|
1324
|
+
if (operator in COMPARISONS_TO_JSONPATH) {
|
|
1325
|
+
const native = COMPARISONS_TO_JSONPATH[operator];
|
|
1326
|
+
const pathPlaceholder = params.add(`$.${field} ${native} $value`);
|
|
1327
|
+
const valuePlaceholder = params.add(JSON.stringify({ value: filterValue }));
|
|
1328
|
+
return `jsonb_path_match(cmetadata, (${pathPlaceholder})::jsonpath, (${valuePlaceholder})::jsonb)`;
|
|
1329
|
+
}
|
|
1330
|
+
if (operator === "$between") {
|
|
1331
|
+
const [low, high] = filterValue;
|
|
1332
|
+
const lowPath = params.add(`$.${field} >= $value`);
|
|
1333
|
+
const lowVal = params.add(JSON.stringify({ value: low }));
|
|
1334
|
+
const highPath = params.add(`$.${field} <= $value`);
|
|
1335
|
+
const highVal = params.add(JSON.stringify({ value: high }));
|
|
1336
|
+
return `(jsonb_path_match(cmetadata, (${lowPath})::jsonpath, (${lowVal})::jsonb) AND jsonb_path_match(cmetadata, (${highPath})::jsonpath, (${highVal})::jsonb))`;
|
|
1337
|
+
}
|
|
1338
|
+
const fieldExpr = `(cmetadata->>'${field}')`;
|
|
1339
|
+
if (operator === "$in" || operator === "$nin") {
|
|
1340
|
+
const values = filterValue.map((v) => {
|
|
1341
|
+
if (typeof v === "boolean" || !["string", "number"].includes(typeof v)) {
|
|
1342
|
+
throw new Error(`Unsupported type for value: ${JSON.stringify(v)}`);
|
|
1343
|
+
}
|
|
1344
|
+
return String(v);
|
|
1345
|
+
});
|
|
1346
|
+
const placeholder = params.add(values);
|
|
1347
|
+
return operator === "$in" ? `${fieldExpr} = ANY(${placeholder})` : `${fieldExpr} <> ALL(${placeholder})`;
|
|
1348
|
+
}
|
|
1349
|
+
if (operator === "$like" || operator === "$ilike") {
|
|
1350
|
+
const placeholder = params.add(filterValue);
|
|
1351
|
+
return operator === "$like" ? `(${fieldExpr} LIKE ${placeholder})` : `(${fieldExpr} ILIKE ${placeholder})`;
|
|
1352
|
+
}
|
|
1353
|
+
if (operator === "$exists") {
|
|
1354
|
+
if (typeof filterValue !== "boolean") {
|
|
1355
|
+
throw new Error("Expected a boolean value for $exists operator");
|
|
1356
|
+
}
|
|
1357
|
+
const condition = `jsonb_exists(cmetadata, '${field}')`;
|
|
1358
|
+
return filterValue ? condition : `(NOT ${condition})`;
|
|
1359
|
+
}
|
|
1360
|
+
throw new Error(`Unsupported operator: ${operator}`);
|
|
1361
|
+
}
|
|
1362
|
+
function createLegacyFilterClause(filters, params) {
|
|
1363
|
+
return combineFilterClause(
|
|
1364
|
+
filters,
|
|
1365
|
+
(field, value) => handleFieldFilter2(field, value, params)
|
|
1366
|
+
);
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
// src/legacy/vectorstore.ts
|
|
1370
|
+
var LegacyDistanceStrategy = {
|
|
1371
|
+
EUCLIDEAN: "l2",
|
|
1372
|
+
COSINE: "cosine",
|
|
1373
|
+
MAX_INNER_PRODUCT: "inner"
|
|
1374
|
+
};
|
|
1375
|
+
var DEFAULT_COLLECTION_NAME = "langchain";
|
|
1376
|
+
function vectorToSql2(embedding) {
|
|
1377
|
+
return `[${embedding.join(",")}]`;
|
|
1378
|
+
}
|
|
1379
|
+
function distanceOperator(strategy) {
|
|
1380
|
+
switch (strategy) {
|
|
1381
|
+
case LegacyDistanceStrategy.EUCLIDEAN:
|
|
1382
|
+
return "<->";
|
|
1383
|
+
case LegacyDistanceStrategy.MAX_INNER_PRODUCT:
|
|
1384
|
+
return "<#>";
|
|
1385
|
+
case LegacyDistanceStrategy.COSINE:
|
|
1386
|
+
default:
|
|
1387
|
+
return "<=>";
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
var PGVector = class _PGVector extends VectorStore2 {
|
|
1391
|
+
engine;
|
|
1392
|
+
collectionName;
|
|
1393
|
+
collectionMetadata;
|
|
1394
|
+
distanceStrategy;
|
|
1395
|
+
preDeleteCollection;
|
|
1396
|
+
collectionId;
|
|
1397
|
+
constructor(embeddings, args) {
|
|
1398
|
+
super(embeddings, {});
|
|
1399
|
+
this.engine = args.engine;
|
|
1400
|
+
this.collectionName = args.collectionName;
|
|
1401
|
+
this.collectionMetadata = args.collectionMetadata;
|
|
1402
|
+
this.distanceStrategy = args.distanceStrategy;
|
|
1403
|
+
this.preDeleteCollection = args.preDeleteCollection;
|
|
1404
|
+
}
|
|
1405
|
+
_vectorstoreType() {
|
|
1406
|
+
return "pgvector";
|
|
1407
|
+
}
|
|
1408
|
+
static async initialize(engine, embeddings, options = {}) {
|
|
1409
|
+
const store = new _PGVector(embeddings, {
|
|
1410
|
+
engine,
|
|
1411
|
+
collectionName: options.collectionName ?? DEFAULT_COLLECTION_NAME,
|
|
1412
|
+
collectionMetadata: options.collectionMetadata,
|
|
1413
|
+
distanceStrategy: options.distanceStrategy ?? LegacyDistanceStrategy.COSINE,
|
|
1414
|
+
preDeleteCollection: options.preDeleteCollection ?? false
|
|
1415
|
+
});
|
|
1416
|
+
await store.createTablesIfNotExists();
|
|
1417
|
+
await store.createCollection();
|
|
1418
|
+
return store;
|
|
1419
|
+
}
|
|
1420
|
+
static async fromTexts(texts, metadatas, embeddings, dbConfig) {
|
|
1421
|
+
const { engine, ids, ...options } = dbConfig;
|
|
1422
|
+
const store = await _PGVector.initialize(engine, embeddings, options);
|
|
1423
|
+
const metadatasArray = Array.isArray(metadatas) ? metadatas : texts.map(() => metadatas);
|
|
1424
|
+
await store.addDocuments(
|
|
1425
|
+
texts.map(
|
|
1426
|
+
(text, i) => new Document2({
|
|
1427
|
+
pageContent: text,
|
|
1428
|
+
metadata: metadatasArray[i] ?? {}
|
|
1429
|
+
})
|
|
1430
|
+
),
|
|
1431
|
+
ids ? { ids } : void 0
|
|
1432
|
+
);
|
|
1433
|
+
return store;
|
|
1434
|
+
}
|
|
1435
|
+
static async fromDocuments(docs, embeddings, dbConfig) {
|
|
1436
|
+
const { engine, ids, ...options } = dbConfig;
|
|
1437
|
+
const store = await _PGVector.initialize(engine, embeddings, options);
|
|
1438
|
+
await store.addDocuments(docs, ids ? { ids } : void 0);
|
|
1439
|
+
return store;
|
|
1440
|
+
}
|
|
1441
|
+
async createTablesIfNotExists() {
|
|
1442
|
+
await this.engine.pool.query(
|
|
1443
|
+
"SELECT pg_advisory_xact_lock(1573678846307946496); CREATE EXTENSION IF NOT EXISTS vector;"
|
|
1444
|
+
);
|
|
1445
|
+
await this.engine.pool.query(`
|
|
1446
|
+
CREATE TABLE IF NOT EXISTS langchain_pg_collection (
|
|
1447
|
+
uuid UUID PRIMARY KEY,
|
|
1448
|
+
name VARCHAR NOT NULL UNIQUE,
|
|
1449
|
+
cmetadata JSON
|
|
1450
|
+
);
|
|
1451
|
+
`);
|
|
1452
|
+
await this.engine.pool.query(`
|
|
1453
|
+
CREATE TABLE IF NOT EXISTS langchain_pg_embedding (
|
|
1454
|
+
id VARCHAR PRIMARY KEY,
|
|
1455
|
+
collection_id UUID REFERENCES langchain_pg_collection(uuid) ON DELETE CASCADE,
|
|
1456
|
+
embedding vector,
|
|
1457
|
+
document VARCHAR,
|
|
1458
|
+
cmetadata JSONB
|
|
1459
|
+
);
|
|
1460
|
+
`);
|
|
1461
|
+
await this.engine.pool.query(`
|
|
1462
|
+
CREATE INDEX IF NOT EXISTS ix_cmetadata_gin
|
|
1463
|
+
ON langchain_pg_embedding USING gin (cmetadata jsonb_path_ops);
|
|
1464
|
+
`);
|
|
1465
|
+
}
|
|
1466
|
+
/** Delete the collection (its row and all embeddings, via `ON DELETE CASCADE`). */
|
|
1467
|
+
async deleteCollection() {
|
|
1468
|
+
await this.engine.pool.query(
|
|
1469
|
+
"DELETE FROM langchain_pg_collection WHERE name = $1",
|
|
1470
|
+
[this.collectionName]
|
|
1471
|
+
);
|
|
1472
|
+
this.collectionId = void 0;
|
|
1473
|
+
}
|
|
1474
|
+
async createCollection() {
|
|
1475
|
+
if (this.preDeleteCollection) await this.deleteCollection();
|
|
1476
|
+
const existing = await this.engine.pool.query(
|
|
1477
|
+
"SELECT uuid FROM langchain_pg_collection WHERE name = $1",
|
|
1478
|
+
[this.collectionName]
|
|
1479
|
+
);
|
|
1480
|
+
if (existing.rows.length > 0) {
|
|
1481
|
+
this.collectionId = existing.rows[0].uuid;
|
|
1482
|
+
return;
|
|
1483
|
+
}
|
|
1484
|
+
const id = randomUUID2();
|
|
1485
|
+
await this.engine.pool.query(
|
|
1486
|
+
"INSERT INTO langchain_pg_collection (uuid, name, cmetadata) VALUES ($1, $2, $3)",
|
|
1487
|
+
[
|
|
1488
|
+
id,
|
|
1489
|
+
this.collectionName,
|
|
1490
|
+
this.collectionMetadata ? JSON.stringify(this.collectionMetadata) : null
|
|
1491
|
+
]
|
|
1492
|
+
);
|
|
1493
|
+
this.collectionId = id;
|
|
1494
|
+
}
|
|
1495
|
+
requireCollectionId() {
|
|
1496
|
+
if (!this.collectionId) {
|
|
1497
|
+
throw new Error(
|
|
1498
|
+
"Collection not initialized. Use PGVector.initialize(...) rather than constructing directly."
|
|
1499
|
+
);
|
|
1500
|
+
}
|
|
1501
|
+
return this.collectionId;
|
|
1502
|
+
}
|
|
1503
|
+
rowToDocument(row) {
|
|
1504
|
+
return new Document2({
|
|
1505
|
+
pageContent: row.document,
|
|
1506
|
+
metadata: row.cmetadata ?? {},
|
|
1507
|
+
id: String(row.id)
|
|
1508
|
+
});
|
|
1509
|
+
}
|
|
1510
|
+
async addEmbeddings(texts, embeddings, metadatas, ids) {
|
|
1511
|
+
const collectionId = this.requireCollectionId();
|
|
1512
|
+
const finalIds = texts.map((_, i) => ids?.[i] ?? randomUUID2());
|
|
1513
|
+
const finalMetadatas = metadatas && metadatas.length === texts.length ? metadatas : texts.map(() => ({}));
|
|
1514
|
+
const client = await this.engine.pool.connect();
|
|
1515
|
+
try {
|
|
1516
|
+
for (let i = 0; i < texts.length; i += 1) {
|
|
1517
|
+
await client.query(
|
|
1518
|
+
`INSERT INTO langchain_pg_embedding (id, collection_id, embedding, document, cmetadata)
|
|
1519
|
+
VALUES ($1, $2, $3, $4, $5)
|
|
1520
|
+
ON CONFLICT (id) DO UPDATE SET
|
|
1521
|
+
collection_id = EXCLUDED.collection_id,
|
|
1522
|
+
embedding = EXCLUDED.embedding,
|
|
1523
|
+
document = EXCLUDED.document,
|
|
1524
|
+
cmetadata = EXCLUDED.cmetadata;`,
|
|
1525
|
+
[
|
|
1526
|
+
finalIds[i],
|
|
1527
|
+
collectionId,
|
|
1528
|
+
vectorToSql2(embeddings[i]),
|
|
1529
|
+
texts[i],
|
|
1530
|
+
JSON.stringify(finalMetadatas[i] ?? {})
|
|
1531
|
+
]
|
|
1532
|
+
);
|
|
1533
|
+
}
|
|
1534
|
+
} finally {
|
|
1535
|
+
client.release();
|
|
1536
|
+
}
|
|
1537
|
+
return finalIds;
|
|
1538
|
+
}
|
|
1539
|
+
async addVectors(vectors, documents, options) {
|
|
1540
|
+
const texts = documents.map((d) => d.pageContent);
|
|
1541
|
+
const metadatas = documents.map((d) => d.metadata ?? {});
|
|
1542
|
+
const ids = options?.ids ?? documents.map((d) => d.id);
|
|
1543
|
+
return this.addEmbeddings(texts, vectors, metadatas, ids);
|
|
1544
|
+
}
|
|
1545
|
+
async addDocuments(documents, options) {
|
|
1546
|
+
const texts = documents.map((d) => d.pageContent);
|
|
1547
|
+
const embeddings = await this.embeddings.embedDocuments(texts);
|
|
1548
|
+
return this.addVectors(embeddings, documents, options);
|
|
1549
|
+
}
|
|
1550
|
+
async addTexts(texts, metadatas, ids) {
|
|
1551
|
+
const embeddings = await this.embeddings.embedDocuments(texts);
|
|
1552
|
+
return this.addEmbeddings(texts, embeddings, metadatas, ids);
|
|
1553
|
+
}
|
|
1554
|
+
async delete(params = {}) {
|
|
1555
|
+
const collectionId = this.requireCollectionId();
|
|
1556
|
+
const { ids, filter } = params;
|
|
1557
|
+
const paramBuilder = new ParamBuilder();
|
|
1558
|
+
const collectionPlaceholder = paramBuilder.add(collectionId);
|
|
1559
|
+
const clauses = [`collection_id = ${collectionPlaceholder}`];
|
|
1560
|
+
if (ids?.length) {
|
|
1561
|
+
const placeholders = ids.map((id) => paramBuilder.add(id));
|
|
1562
|
+
clauses.push(`id IN (${placeholders.join(", ")})`);
|
|
1563
|
+
}
|
|
1564
|
+
if (filter) {
|
|
1565
|
+
clauses.push(createLegacyFilterClause(filter, paramBuilder));
|
|
1566
|
+
}
|
|
1567
|
+
await this.engine.pool.query(
|
|
1568
|
+
`DELETE FROM langchain_pg_embedding WHERE ${clauses.join(" AND ")}`,
|
|
1569
|
+
paramBuilder.values
|
|
1570
|
+
);
|
|
1571
|
+
}
|
|
1572
|
+
async queryCollection(embedding, k, filter) {
|
|
1573
|
+
const collectionId = this.requireCollectionId();
|
|
1574
|
+
const operator = distanceOperator(this.distanceStrategy);
|
|
1575
|
+
const params = new ParamBuilder();
|
|
1576
|
+
const collectionPlaceholder = params.add(collectionId);
|
|
1577
|
+
const clauses = [`collection_id = ${collectionPlaceholder}`];
|
|
1578
|
+
if (filter) {
|
|
1579
|
+
clauses.push(createLegacyFilterClause(filter, params));
|
|
1580
|
+
}
|
|
1581
|
+
const embeddingPlaceholder = params.add(vectorToSql2(embedding));
|
|
1582
|
+
const limitPlaceholder = params.add(k);
|
|
1583
|
+
const query = `SELECT id, document, cmetadata, embedding, embedding ${operator} ${embeddingPlaceholder} AS distance
|
|
1584
|
+
FROM langchain_pg_embedding
|
|
1585
|
+
WHERE ${clauses.join(" AND ")}
|
|
1586
|
+
ORDER BY embedding ${operator} ${embeddingPlaceholder}
|
|
1587
|
+
LIMIT ${limitPlaceholder};`;
|
|
1588
|
+
const result = await this.engine.pool.query(query, params.values);
|
|
1589
|
+
return result.rows;
|
|
1590
|
+
}
|
|
1591
|
+
async similaritySearchVectorWithScore(embedding, k, filter) {
|
|
1592
|
+
const rows = await this.queryCollection(embedding, k, filter);
|
|
1593
|
+
return rows.map((row) => [this.rowToDocument(row), Number(row.distance)]);
|
|
1594
|
+
}
|
|
1595
|
+
async maxMarginalRelevanceSearch(query, options) {
|
|
1596
|
+
const embedding = await this.embeddings.embedQuery(query);
|
|
1597
|
+
const results = await this.maxMarginalRelevanceSearchWithScoreByVector(
|
|
1598
|
+
embedding,
|
|
1599
|
+
options
|
|
1600
|
+
);
|
|
1601
|
+
return results.map(([doc]) => doc);
|
|
1602
|
+
}
|
|
1603
|
+
async maxMarginalRelevanceSearchWithScoreByVector(embedding, options = {}) {
|
|
1604
|
+
const fetchK = options.fetchK ?? 20;
|
|
1605
|
+
const k = options.k ?? 4;
|
|
1606
|
+
const lambdaMult = options.lambda ?? 0.5;
|
|
1607
|
+
const rows = await this.queryCollection(embedding, fetchK, options.filter);
|
|
1608
|
+
const embeddingList = rows.map(
|
|
1609
|
+
(row) => JSON.parse(row.embedding)
|
|
1610
|
+
);
|
|
1611
|
+
const selected = new Set(
|
|
1612
|
+
maximalMarginalRelevance2(embedding, embeddingList, lambdaMult, k)
|
|
1613
|
+
);
|
|
1614
|
+
return rows.map((row) => [
|
|
1615
|
+
this.rowToDocument(row),
|
|
1616
|
+
Number(row.distance)
|
|
1617
|
+
]).filter((_, i) => selected.has(i));
|
|
1618
|
+
}
|
|
1619
|
+
async getByIds(ids) {
|
|
1620
|
+
const collectionId = this.requireCollectionId();
|
|
1621
|
+
const params = new ParamBuilder();
|
|
1622
|
+
const collectionPlaceholder = params.add(collectionId);
|
|
1623
|
+
const placeholders = ids.map((id) => params.add(id));
|
|
1624
|
+
const query = `SELECT id, document, cmetadata FROM langchain_pg_embedding
|
|
1625
|
+
WHERE collection_id = ${collectionPlaceholder} AND id IN (${placeholders.join(", ")});`;
|
|
1626
|
+
const result = await this.engine.pool.query(query, params.values);
|
|
1627
|
+
return result.rows.map((row) => this.rowToDocument(row));
|
|
1628
|
+
}
|
|
1629
|
+
};
|
|
1630
|
+
|
|
1631
|
+
// src/pgvector_migrator.ts
|
|
1632
|
+
import { Document as Document3 } from "@langchain/core/documents";
|
|
1633
|
+
var COLLECTIONS_TABLE = "langchain_pg_collection";
|
|
1634
|
+
var EMBEDDINGS_TABLE = "langchain_pg_embedding";
|
|
1635
|
+
async function getCollectionUuid(engine, collectionName) {
|
|
1636
|
+
const result = await engine.pool.query(
|
|
1637
|
+
`SELECT uuid FROM ${COLLECTIONS_TABLE} WHERE name = $1`,
|
|
1638
|
+
[collectionName]
|
|
1639
|
+
);
|
|
1640
|
+
if (result.rows.length === 0) {
|
|
1641
|
+
throw new Error(`Collection, ${collectionName} not found.`);
|
|
1642
|
+
}
|
|
1643
|
+
return result.rows[0].uuid;
|
|
1644
|
+
}
|
|
1645
|
+
async function* extractPgvectorCollection(engine, collectionName, batchSize = 1e3) {
|
|
1646
|
+
const uuid = await getCollectionUuid(engine, collectionName);
|
|
1647
|
+
let offset = 0;
|
|
1648
|
+
for (; ; ) {
|
|
1649
|
+
const result = await engine.pool.query(
|
|
1650
|
+
`SELECT * FROM ${EMBEDDINGS_TABLE} WHERE collection_id = $1 ORDER BY id LIMIT $2 OFFSET $3`,
|
|
1651
|
+
[uuid, batchSize, offset]
|
|
1652
|
+
);
|
|
1653
|
+
if (result.rows.length === 0) break;
|
|
1654
|
+
yield result.rows;
|
|
1655
|
+
offset += result.rows.length;
|
|
1656
|
+
if (result.rows.length < batchSize) break;
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
async function listPgvectorCollectionNames(engine) {
|
|
1660
|
+
const result = await engine.pool.query(
|
|
1661
|
+
`SELECT name FROM ${COLLECTIONS_TABLE}`
|
|
1662
|
+
);
|
|
1663
|
+
return result.rows.map((row) => row.name);
|
|
1664
|
+
}
|
|
1665
|
+
async function migratePgvectorCollection(engine, collectionName, vectorStore, options = {}) {
|
|
1666
|
+
const insertBatchSize = options.insertBatchSize ?? 1e3;
|
|
1667
|
+
const uuid = await getCollectionUuid(engine, collectionName);
|
|
1668
|
+
const countResult = await engine.pool.query(
|
|
1669
|
+
`SELECT COUNT(*) FROM ${EMBEDDINGS_TABLE} WHERE collection_id = $1`,
|
|
1670
|
+
[uuid]
|
|
1671
|
+
);
|
|
1672
|
+
const originalCount = Number(countResult.rows[0].count);
|
|
1673
|
+
if (originalCount === 0) {
|
|
1674
|
+
console.warn(`Collection, ${collectionName} contains no elements.`);
|
|
1675
|
+
return;
|
|
1676
|
+
}
|
|
1677
|
+
for await (const batch of extractPgvectorCollection(
|
|
1678
|
+
engine,
|
|
1679
|
+
collectionName,
|
|
1680
|
+
insertBatchSize
|
|
1681
|
+
)) {
|
|
1682
|
+
const embeddings = batch.map(
|
|
1683
|
+
(row) => JSON.parse(row.embedding)
|
|
1684
|
+
);
|
|
1685
|
+
const documents = batch.map(
|
|
1686
|
+
(row) => new Document3({
|
|
1687
|
+
pageContent: row.document,
|
|
1688
|
+
metadata: row.cmetadata ?? {}
|
|
1689
|
+
})
|
|
1690
|
+
);
|
|
1691
|
+
const ids = batch.map((row) => row.id);
|
|
1692
|
+
await vectorStore.addVectors(embeddings, documents, { ids });
|
|
1693
|
+
}
|
|
1694
|
+
const destResult = await engine.pool.query(
|
|
1695
|
+
`SELECT COUNT(*) FROM "${vectorStore.schemaName}"."${vectorStore.tableName}"`
|
|
1696
|
+
);
|
|
1697
|
+
const destCount = Number(destResult.rows[0].count);
|
|
1698
|
+
if (destCount !== originalCount) {
|
|
1699
|
+
throw new Error(
|
|
1700
|
+
`All data not yet migrated.
|
|
1701
|
+
Original row count: ${originalCount}
|
|
1702
|
+
Collection table, ${vectorStore.tableName} row count: ${destCount}`
|
|
1703
|
+
);
|
|
1704
|
+
}
|
|
1705
|
+
if (options.deletePgCollection) {
|
|
1706
|
+
await engine.pool.query(
|
|
1707
|
+
`DELETE FROM ${EMBEDDINGS_TABLE} WHERE collection_id = $1`,
|
|
1708
|
+
[uuid]
|
|
1709
|
+
);
|
|
1710
|
+
await engine.pool.query(
|
|
1711
|
+
`DELETE FROM ${COLLECTIONS_TABLE} WHERE name = $1`,
|
|
1712
|
+
[collectionName]
|
|
1713
|
+
);
|
|
1714
|
+
console.log(`Successfully deleted PGVector collection, ${collectionName}`);
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
export {
|
|
1718
|
+
BaseIndex,
|
|
1719
|
+
COLLECTIONS_TABLE,
|
|
1720
|
+
Column,
|
|
1721
|
+
DEFAULT_DISTANCE_STRATEGY,
|
|
1722
|
+
DEFAULT_INDEX_NAME_SUFFIX,
|
|
1723
|
+
DistanceStrategy,
|
|
1724
|
+
EMBEDDINGS_TABLE,
|
|
1725
|
+
ExactNearestNeighbor,
|
|
1726
|
+
HNSWIndex,
|
|
1727
|
+
HNSWQueryOptions,
|
|
1728
|
+
HybridSearchConfig,
|
|
1729
|
+
IVFFlatIndex,
|
|
1730
|
+
IVFFlatQueryOptions,
|
|
1731
|
+
LegacyDistanceStrategy,
|
|
1732
|
+
PGEngine,
|
|
1733
|
+
PGVector,
|
|
1734
|
+
PGVectorStore,
|
|
1735
|
+
PGVectorTranslator,
|
|
1736
|
+
ParamBuilder,
|
|
1737
|
+
PostgresChatMessageHistory,
|
|
1738
|
+
QueryOptions,
|
|
1739
|
+
combineFilterClause,
|
|
1740
|
+
createFilterClause,
|
|
1741
|
+
createLegacyFilterClause,
|
|
1742
|
+
extractPgvectorCollection,
|
|
1743
|
+
listPgvectorCollectionNames,
|
|
1744
|
+
migratePgvectorCollection,
|
|
1745
|
+
reciprocalRankFusion,
|
|
1746
|
+
validateIdentifier,
|
|
1747
|
+
weightedSumRanking
|
|
1748
|
+
};
|
|
1749
|
+
//# sourceMappingURL=index.js.map
|