@videoq-jp/langchainjs-postgres 0.0.0-stage → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,568 @@
1
+ import { Pool, PoolConfig } from 'pg';
2
+ import { DocumentInterface, Document } from '@langchain/core/documents';
3
+ import { EmbeddingsInterface } from '@langchain/core/embeddings';
4
+ import { VectorStore, MaxMarginalRelevanceSearchOptions } from '@langchain/core/vectorstores';
5
+ import { Visitor, VisitorOperationResult, VisitorComparisonResult, VisitorStructuredQueryResult, Operator, Comparator, Operation, Comparison, StructuredQuery } from '@langchain/core/structured_query';
6
+ import { BaseListChatMessageHistory } from '@langchain/core/chat_history';
7
+ import { BaseMessage } from '@langchain/core/messages';
8
+
9
+ /**
10
+ * Vector index definitions for {@link PGVectorStore}.
11
+ *
12
+ * Ported from `langchain_postgres.v2.indexes` (Python).
13
+ * Learn more about pgvector indexes at https://github.com/pgvector/pgvector#indexing
14
+ */
15
+ interface DistanceStrategyValue {
16
+ /** Operator used in `ORDER BY` clauses, e.g. `<=>`. */
17
+ operator: string;
18
+ /** SQL function name used to compute distance/similarity, e.g. `cosine_distance`. */
19
+ searchFunction: string;
20
+ /** pgvector index operator class, e.g. `vector_cosine_ops`. */
21
+ indexFunction: string;
22
+ }
23
+ /** Enumerator of the supported pgvector distance strategies. */
24
+ declare const DistanceStrategy: {
25
+ readonly EUCLIDEAN: {
26
+ readonly operator: "<->";
27
+ readonly searchFunction: "l2_distance";
28
+ readonly indexFunction: "vector_l2_ops";
29
+ };
30
+ readonly COSINE_DISTANCE: {
31
+ readonly operator: "<=>";
32
+ readonly searchFunction: "cosine_distance";
33
+ readonly indexFunction: "vector_cosine_ops";
34
+ };
35
+ readonly INNER_PRODUCT: {
36
+ readonly operator: "<#>";
37
+ readonly searchFunction: "inner_product";
38
+ readonly indexFunction: "vector_ip_ops";
39
+ };
40
+ };
41
+ type DistanceStrategy = (typeof DistanceStrategy)[keyof typeof DistanceStrategy];
42
+ declare const DEFAULT_DISTANCE_STRATEGY: DistanceStrategy;
43
+ declare const DEFAULT_INDEX_NAME_SUFFIX = "langchainvectorindex";
44
+ declare function validateIdentifier(identifier: string): void;
45
+ interface BaseIndexArgs {
46
+ name?: string;
47
+ distanceStrategy?: DistanceStrategy;
48
+ partialIndexes?: string[];
49
+ extensionName?: string;
50
+ }
51
+ /** Abstract base class for defining vector indexes. */
52
+ declare abstract class BaseIndex {
53
+ name?: string;
54
+ indexType: string;
55
+ distanceStrategy: DistanceStrategy;
56
+ partialIndexes?: string[];
57
+ extensionName?: string;
58
+ constructor(args?: BaseIndexArgs);
59
+ /** Set index query options for vector store initialization. */
60
+ abstract indexOptions(): string;
61
+ getIndexFunction(): string;
62
+ }
63
+ /** Sentinel index used to request removal of a vector index. */
64
+ declare class ExactNearestNeighbor extends BaseIndex {
65
+ indexType: string;
66
+ indexOptions(): string;
67
+ }
68
+ declare abstract class QueryOptions {
69
+ /** Convert index attributes to a list of `SET LOCAL` configurations. */
70
+ abstract toParameter(): string[];
71
+ }
72
+ interface HNSWIndexArgs extends BaseIndexArgs {
73
+ m?: number;
74
+ efConstruction?: number;
75
+ }
76
+ declare class HNSWIndex extends BaseIndex {
77
+ indexType: string;
78
+ m: number;
79
+ efConstruction: number;
80
+ constructor(args?: HNSWIndexArgs);
81
+ indexOptions(): string;
82
+ }
83
+ interface HNSWQueryOptionsArgs {
84
+ efSearch?: number;
85
+ }
86
+ declare class HNSWQueryOptions extends QueryOptions {
87
+ efSearch: number;
88
+ constructor(args?: HNSWQueryOptionsArgs);
89
+ toParameter(): string[];
90
+ }
91
+ interface IVFFlatIndexArgs extends BaseIndexArgs {
92
+ lists?: number;
93
+ }
94
+ declare class IVFFlatIndex extends BaseIndex {
95
+ indexType: string;
96
+ lists: number;
97
+ constructor(args?: IVFFlatIndexArgs);
98
+ indexOptions(): string;
99
+ }
100
+ interface IVFFlatQueryOptionsArgs {
101
+ probes?: number;
102
+ }
103
+ declare class IVFFlatQueryOptions extends QueryOptions {
104
+ probes: number;
105
+ constructor(args?: IVFFlatQueryOptionsArgs);
106
+ toParameter(): string[];
107
+ }
108
+
109
+ /**
110
+ * Hybrid (dense + sparse) search configuration and fusion functions.
111
+ *
112
+ * Ported from `langchain_postgres.v2.hybrid_search_config` (Python).
113
+ *
114
+ * Queries might be slow if the hybrid search column does not exist. For best
115
+ * hybrid search performance, consider creating a TSV column and adding a GIN
116
+ * index via {@link PGVectorStore.applyHybridSearchIndex}.
117
+ */
118
+
119
+ /** A single row returned from a SQL query, keyed by column name. */
120
+ type Row = Record<string, any>;
121
+ interface FusionFunctionParams {
122
+ fetchTopK?: number;
123
+ distanceStrategy?: DistanceStrategy;
124
+ [key: string]: unknown;
125
+ }
126
+ type FusionFunction = (primarySearchResults: Row[], secondarySearchResults: Row[], params?: FusionFunctionParams) => Row[];
127
+ /** Ranks documents using a weighted sum of scores from two sources. */
128
+ declare const weightedSumRanking: FusionFunction;
129
+ /** Ranks documents using Reciprocal Rank Fusion (RRF) of scores from two sources. */
130
+ declare const reciprocalRankFusion: FusionFunction;
131
+ interface HybridSearchConfigArgs {
132
+ tsvColumn?: string;
133
+ tsvLang?: string;
134
+ ftsQuery?: string;
135
+ fusionFunction?: FusionFunction;
136
+ fusionFunctionParameters?: FusionFunctionParams;
137
+ primaryTopK?: number;
138
+ secondaryTopK?: number;
139
+ indexName?: string;
140
+ indexType?: string;
141
+ }
142
+ /** Hybrid search configuration for {@link PGVectorStore}. */
143
+ declare class HybridSearchConfig {
144
+ tsvColumn?: string;
145
+ tsvLang?: string;
146
+ ftsQuery?: string;
147
+ fusionFunction: FusionFunction;
148
+ fusionFunctionParameters: FusionFunctionParams;
149
+ primaryTopK: number;
150
+ secondaryTopK: number;
151
+ indexName: string;
152
+ indexType: string;
153
+ constructor(args?: HybridSearchConfigArgs);
154
+ }
155
+
156
+ /**
157
+ * Connection pool manager for Postgres.
158
+ *
159
+ * Ported from `langchain_postgres.v2.engine` (Python). The Python
160
+ * implementation juggles a background event loop so that async SQLAlchemy
161
+ * calls can be exposed synchronously; that machinery is unnecessary in
162
+ * JavaScript since everything here is already Promise-based.
163
+ */
164
+
165
+ interface ColumnDict {
166
+ name: string;
167
+ dataType: string;
168
+ nullable?: boolean;
169
+ }
170
+ /** Describes a metadata column on a vectorstore table. */
171
+ declare class Column {
172
+ name: string;
173
+ dataType: string;
174
+ nullable: boolean;
175
+ constructor(name: string, dataType: string, nullable?: boolean);
176
+ }
177
+ type ColumnLike = Column | ColumnDict;
178
+ interface InitVectorstoreTableOptions {
179
+ schemaName?: string;
180
+ contentColumn?: string;
181
+ embeddingColumn?: string;
182
+ metadataColumns?: ColumnLike[];
183
+ metadataJsonColumn?: string;
184
+ idColumn?: string | ColumnLike;
185
+ overwriteExisting?: boolean;
186
+ storeMetadata?: boolean;
187
+ hybridSearchConfig?: HybridSearchConfig;
188
+ }
189
+ /** A class for managing connections to a Postgres database. */
190
+ declare class PGEngine {
191
+ /** The underlying `pg` connection pool. Exposed for advanced use cases. */
192
+ readonly pool: Pool;
193
+ private constructor();
194
+ /** Create a PGEngine instance from an existing `pg.Pool`. */
195
+ static fromPool(pool: Pool): PGEngine;
196
+ /** Create a PGEngine instance from a Postgres connection string. */
197
+ static fromConnectionString(url: string, poolConfig?: Omit<PoolConfig, "connectionString">): PGEngine;
198
+ /** Dispose of the connection pool. */
199
+ close(): Promise<void>;
200
+ /**
201
+ * Create a table for saving vectors to be used with {@link PGVectorStore}.
202
+ *
203
+ * @throws if the table already exists, or if the data type of the id
204
+ * column is not a valid PostgreSQL data type.
205
+ */
206
+ initVectorstoreTable(tableName: string, vectorSize: number, options?: InitVectorstoreTableOptions): Promise<void>;
207
+ /** Drop the vector store table. */
208
+ dropTable(tableName: string, options?: {
209
+ schemaName?: string;
210
+ }): Promise<void>;
211
+ }
212
+
213
+ /**
214
+ * Postgres-backed vector store built on top of {@link PGEngine}.
215
+ *
216
+ * Ported from `langchain_postgres.v2.async_vectorstore.AsyncPGVectorStore`
217
+ * (Python). The upstream package ships separate sync/async classes
218
+ * (`PGVectorStore` / `AsyncPGVectorStore`) because Python needs to bridge a
219
+ * background event loop for synchronous callers. JavaScript has no such
220
+ * split: every method here is simply async, matching how every other
221
+ * LangChain.js vector store is implemented.
222
+ */
223
+
224
+ /** Embeddings with optional database-side SQL expression hooks. */
225
+ interface PGVectorStoreEmbeddings extends EmbeddingsInterface {
226
+ /**
227
+ * Return a trusted SQL expression using the supplied `$n` placeholder.
228
+ * The store binds the document or query text separately.
229
+ */
230
+ embedQueryInlineTemplate?(placeholder: string): string;
231
+ /**
232
+ * @deprecated This raw-text SQL hook is never called. Providers exposing it
233
+ * must also implement embedQueryInlineTemplate or initialization fails
234
+ * because the legacy implementation is susceptible to SQL injection.
235
+ */
236
+ embedQueryInline?(text: string): string;
237
+ }
238
+ interface PGVectorStoreInitializeOptions {
239
+ schemaName?: string;
240
+ contentColumn?: string;
241
+ embeddingColumn?: string;
242
+ metadataColumns?: string[];
243
+ ignoreMetadataColumns?: string[];
244
+ idColumn?: string;
245
+ /** Pass `null` to disable the metadata JSON column entirely. */
246
+ metadataJsonColumn?: string | null;
247
+ distanceStrategy?: DistanceStrategy;
248
+ k?: number;
249
+ fetchK?: number;
250
+ lambdaMult?: number;
251
+ indexQueryOptions?: QueryOptions;
252
+ hybridSearchConfig?: HybridSearchConfig;
253
+ }
254
+ interface PGVectorStoreFromTextsOptions extends PGVectorStoreInitializeOptions {
255
+ engine: PGEngine;
256
+ tableName: string;
257
+ ids?: string[];
258
+ }
259
+ interface PGVectorStoreGetOptions {
260
+ ids?: string[];
261
+ where?: Record<string, any>;
262
+ limit?: number;
263
+ offset?: number;
264
+ whereDocument?: Record<string, any>;
265
+ include?: Array<"embeddings" | "metadatas" | "documents">;
266
+ }
267
+ interface PGVectorStoreGetResult {
268
+ ids: string[];
269
+ embeddings?: number[][];
270
+ metadatas?: Record<string, any>[];
271
+ documents?: string[];
272
+ }
273
+ interface MMRByVectorOptions {
274
+ k?: number;
275
+ fetchK?: number;
276
+ lambda?: number;
277
+ filter?: Record<string, any>;
278
+ }
279
+ /** Postgres vector store backed by the `pgvector` extension. */
280
+ declare class PGVectorStore extends VectorStore {
281
+ FilterType: Record<string, any>;
282
+ embeddings: PGVectorStoreEmbeddings;
283
+ engine: PGEngine;
284
+ tableName: string;
285
+ schemaName: string;
286
+ contentColumn: string;
287
+ embeddingColumn: string;
288
+ metadataColumns: string[];
289
+ idColumn: string;
290
+ metadataJsonColumn?: string;
291
+ distanceStrategy: DistanceStrategy;
292
+ k: number;
293
+ fetchK: number;
294
+ lambdaMult: number;
295
+ indexQueryOptions?: QueryOptions;
296
+ hybridSearchConfig?: HybridSearchConfig;
297
+ private constructor();
298
+ _vectorstoreType(): string;
299
+ /**
300
+ * Create a {@link PGVectorStore} bound to an existing table.
301
+ * Use {@link PGEngine.initVectorstoreTable} first to create the table.
302
+ */
303
+ static initialize(engine: PGEngine, embeddings: PGVectorStoreEmbeddings, tableName: string, options?: PGVectorStoreInitializeOptions): Promise<PGVectorStore>;
304
+ static fromTexts(texts: string[], metadatas: Record<string, any>[] | Record<string, any>, embeddings: PGVectorStoreEmbeddings, dbConfig: PGVectorStoreFromTextsOptions): Promise<PGVectorStore>;
305
+ static fromDocuments(docs: DocumentInterface[], embeddings: PGVectorStoreEmbeddings, dbConfig: PGVectorStoreFromTextsOptions): Promise<PGVectorStore>;
306
+ private filterContext;
307
+ private rowToDocument;
308
+ private addEmbeddings;
309
+ addVectors(vectors: number[][], documents: DocumentInterface[], options?: Record<string, any>): Promise<string[]>;
310
+ addDocuments(documents: DocumentInterface[], options?: Record<string, any>): Promise<string[]>;
311
+ /** Embed raw texts and add them to the table. */
312
+ addTexts(texts: string[], metadatas?: Record<string, any>[], ids?: Array<string | null | undefined>): Promise<string[]>;
313
+ private hasInlineEmbeddings;
314
+ delete(params?: {
315
+ ids?: string[];
316
+ filter?: Record<string, any>;
317
+ }): Promise<void>;
318
+ private queryCollection;
319
+ similaritySearch(query: string, k?: number, filter?: Record<string, any>): Promise<Document[]>;
320
+ similaritySearchWithScore(query: string, k?: number, filter?: Record<string, any>): Promise<[Document, number][]>;
321
+ similaritySearchByVector(embedding: number[], k?: number, filter?: Record<string, any>): Promise<Document[]>;
322
+ similaritySearchVectorWithScore(embedding: number[], k: number, filter?: Record<string, any>): Promise<[Document, number][]>;
323
+ private similaritySearchVectorWithScoreInternal;
324
+ maxMarginalRelevanceSearch(query: string, options: MaxMarginalRelevanceSearchOptions<this["FilterType"]>): Promise<Document[]>;
325
+ maxMarginalRelevanceSearchByVector(embedding: number[], options?: MMRByVectorOptions): Promise<Document[]>;
326
+ maxMarginalRelevanceSearchWithScoreByVector(embedding: number[], options?: MMRByVectorOptions): Promise<[Document, number][]>;
327
+ /** Create a full-text-search (TSV) index for hybrid search. */
328
+ applyHybridSearchIndex(concurrently?: boolean): Promise<void>;
329
+ /** Create a vector index on the embedding column. Pass an {@link ExactNearestNeighbor} to drop the index instead. */
330
+ applyVectorIndex(index: BaseIndex, name?: string, options?: {
331
+ concurrently?: boolean;
332
+ }): Promise<void>;
333
+ reindex(indexName?: string): Promise<void>;
334
+ dropVectorIndex(indexName?: string): Promise<void>;
335
+ isValidIndex(indexName?: string): Promise<boolean>;
336
+ private queryCollectionWithFilter;
337
+ /** Retrieve documents using filters, similar to a Chroma-style `get()`. */
338
+ get(options?: PGVectorStoreGetOptions): Promise<PGVectorStoreGetResult>;
339
+ getByIds(ids: string[]): Promise<Document[]>;
340
+ }
341
+
342
+ /**
343
+ * Metadata filter compiler shared by {@link PGVectorStore}.
344
+ *
345
+ * Ported from `AsyncPGVectorStore._create_filter_clause` /
346
+ * `_handle_field_filter` (Python). Builds parameterized SQL `WHERE` clause
347
+ * fragments from LangChain's Mongo-style filter dictionaries.
348
+ */
349
+ /** Accumulates query parameters and hands out `$n` positional placeholders. */
350
+ declare class ParamBuilder {
351
+ values: unknown[];
352
+ add(value: unknown): string;
353
+ }
354
+ interface FilterContext {
355
+ metadataJsonColumn?: string;
356
+ metadataColumns: string[];
357
+ idColumn: string;
358
+ contentColumn: string;
359
+ embeddingColumn: string;
360
+ params: ParamBuilder;
361
+ }
362
+ /**
363
+ * Combine a LangChain-style metadata filter dictionary into a SQL `WHERE`
364
+ * fragment, delegating leaf `field: value` pairs to `handleField`.
365
+ *
366
+ * Shared by {@link createFilterClause} (v2, typed-column filters) and the
367
+ * legacy `PGVector` store's JSONB-based filter compiler.
368
+ */
369
+ declare function combineFilterClause(filters: unknown, handleField: (field: string, value: unknown) => string): string;
370
+ /** Compile a LangChain metadata filter dictionary into a SQL `WHERE` fragment. */
371
+ declare function createFilterClause(filters: unknown, ctx: FilterContext): string;
372
+
373
+ /**
374
+ * Self-query retriever translator for {@link PGVectorStore}.
375
+ *
376
+ * Ported from `langchain_postgres.translator.PGVectorTranslator` (Python).
377
+ * Translates the LangChain self-query IR into the Mongo-style filter
378
+ * dictionaries understood by {@link createFilterClause} in `filter.ts`.
379
+ *
380
+ * Note: `@langchain/core`'s structured-query IR only defines the
381
+ * `eq/ne/lt/gt/lte/gte` comparators (the Python IR additionally has
382
+ * `in/nin/contain/like`), so this translator's allowed comparator list is
383
+ * necessarily a subset of the Python original.
384
+ */
385
+
386
+ /** Translate LangChain self-query filters into `PGVectorStore` filter dictionaries. */
387
+ declare class PGVectorTranslator extends Visitor<PGVectorStore> {
388
+ VisitOperationOutput: VisitorOperationResult;
389
+ VisitComparisonOutput: VisitorComparisonResult;
390
+ VisitStructuredQueryOutput: VisitorStructuredQueryResult;
391
+ allowedOperators: Operator[];
392
+ allowedComparators: Comparator[];
393
+ private validateFunction;
394
+ private formatFunction;
395
+ visitOperation(operation: Operation): VisitorOperationResult;
396
+ visitComparison(comparison: Comparison): VisitorComparisonResult;
397
+ visitStructuredQuery(structuredQuery: StructuredQuery): VisitorStructuredQueryResult;
398
+ }
399
+
400
+ /**
401
+ * Chat message history backed by a Postgres table.
402
+ *
403
+ * Ported from `langchain_postgres.chat_message_histories.PostgresChatMessageHistory`
404
+ * (Python). The Python client accepts either a sync or async `psycopg`
405
+ * connection and exposes matching `a`-prefixed async methods; since
406
+ * JavaScript only has async I/O, this port exposes a single async API that
407
+ * accepts anything with a `pg`-compatible `query()` method (a `Pool`, a
408
+ * checked-out `PoolClient`, or a plain `Client`).
409
+ */
410
+
411
+ /** Minimal `pg`-compatible connection surface (satisfied by `Pool`, `PoolClient`, and `Client`). */
412
+ interface PostgresConnection {
413
+ query(text: string, params?: unknown[]): Promise<{
414
+ rows: any[];
415
+ }>;
416
+ }
417
+ interface PostgresChatMessageHistoryInput {
418
+ /** Name of the database table to use. */
419
+ tableName: string;
420
+ /** Session ID to scope messages to. Must be a valid UUID. */
421
+ sessionId: string;
422
+ /** An existing `pg` `Pool`, `PoolClient`, or `Client`. */
423
+ pool: PostgresConnection;
424
+ }
425
+ /**
426
+ * Client for persisting chat message history in a Postgres database.
427
+ *
428
+ * The schema has the following columns:
429
+ * - `id`: A serial primary key.
430
+ * - `session_id`: The session ID for the chat message history.
431
+ * - `message`: The JSONB message content.
432
+ * - `created_at`: The timestamp of when the message was created (not
433
+ * returned by this interface, but available in the database).
434
+ *
435
+ * Use {@link PostgresChatMessageHistory.createTables} to set up the table
436
+ * schema before first use.
437
+ */
438
+ declare class PostgresChatMessageHistory extends BaseListChatMessageHistory {
439
+ lc_namespace: string[];
440
+ private pool;
441
+ private tableName;
442
+ private sessionId;
443
+ constructor(fields: PostgresChatMessageHistoryInput);
444
+ /** Create the table schema in the database and create relevant indexes. */
445
+ static createTables(connection: PostgresConnection, tableName: string): Promise<void>;
446
+ /**
447
+ * Delete the table schema in the database.
448
+ *
449
+ * WARNING: This will delete the given table from the database including
450
+ * all the data in the table and the schema of the table.
451
+ */
452
+ static dropTable(connection: PostgresConnection, tableName: string): Promise<void>;
453
+ getMessages(): Promise<BaseMessage[]>;
454
+ addMessage(message: BaseMessage): Promise<void>;
455
+ addMessages(messages: BaseMessage[]): Promise<void>;
456
+ clear(): Promise<void>;
457
+ }
458
+
459
+ /**
460
+ * Legacy Postgres vector store using a collection/embedding table pair.
461
+ *
462
+ * Ported from `langchain_postgres.vectorstores.PGVector` (Python). The
463
+ * upstream class builds its own SQLAlchemy engine directly from a connection
464
+ * string; this port instead takes a {@link PGEngine} (the same connection
465
+ * pool abstraction used by {@link PGVectorStore}) so both stores in this
466
+ * package share one connection-management story. The on-disk schema
467
+ * (`langchain_pg_collection` / `langchain_pg_embedding`) and filter
468
+ * semantics are preserved.
469
+ */
470
+
471
+ /** Enumerator of the distance strategies supported by the legacy store. */
472
+ declare const LegacyDistanceStrategy: {
473
+ readonly EUCLIDEAN: "l2";
474
+ readonly COSINE: "cosine";
475
+ readonly MAX_INNER_PRODUCT: "inner";
476
+ };
477
+ type LegacyDistanceStrategy = (typeof LegacyDistanceStrategy)[keyof typeof LegacyDistanceStrategy];
478
+ interface PGVectorInitializeOptions {
479
+ collectionName?: string;
480
+ collectionMetadata?: Record<string, any>;
481
+ distanceStrategy?: LegacyDistanceStrategy;
482
+ /** Delete the collection (if it already exists) before (re)creating it. */
483
+ preDeleteCollection?: boolean;
484
+ }
485
+ interface PGVectorFromTextsOptions extends PGVectorInitializeOptions {
486
+ engine: PGEngine;
487
+ ids?: string[];
488
+ }
489
+ /** Legacy Postgres vector store backed by the `pgvector` extension. */
490
+ declare class PGVector extends VectorStore {
491
+ FilterType: Record<string, any>;
492
+ engine: PGEngine;
493
+ collectionName: string;
494
+ collectionMetadata?: Record<string, any>;
495
+ distanceStrategy: LegacyDistanceStrategy;
496
+ preDeleteCollection: boolean;
497
+ private collectionId?;
498
+ private constructor();
499
+ _vectorstoreType(): string;
500
+ static initialize(engine: PGEngine, embeddings: EmbeddingsInterface, options?: PGVectorInitializeOptions): Promise<PGVector>;
501
+ static fromTexts(texts: string[], metadatas: Record<string, any>[] | Record<string, any>, embeddings: EmbeddingsInterface, dbConfig: PGVectorFromTextsOptions): Promise<PGVector>;
502
+ static fromDocuments(docs: DocumentInterface[], embeddings: EmbeddingsInterface, dbConfig: PGVectorFromTextsOptions): Promise<PGVector>;
503
+ private createTablesIfNotExists;
504
+ /** Delete the collection (its row and all embeddings, via `ON DELETE CASCADE`). */
505
+ deleteCollection(): Promise<void>;
506
+ private createCollection;
507
+ private requireCollectionId;
508
+ private rowToDocument;
509
+ private addEmbeddings;
510
+ addVectors(vectors: number[][], documents: DocumentInterface[], options?: Record<string, any>): Promise<string[]>;
511
+ addDocuments(documents: DocumentInterface[], options?: Record<string, any>): Promise<string[]>;
512
+ addTexts(texts: string[], metadatas?: Record<string, any>[], ids?: Array<string | null | undefined>): Promise<string[]>;
513
+ delete(params?: {
514
+ ids?: string[];
515
+ filter?: Record<string, any>;
516
+ }): Promise<void>;
517
+ private queryCollection;
518
+ similaritySearchVectorWithScore(embedding: number[], k: number, filter?: Record<string, any>): Promise<[Document, number][]>;
519
+ maxMarginalRelevanceSearch(query: string, options: MaxMarginalRelevanceSearchOptions<this["FilterType"]>): Promise<Document[]>;
520
+ maxMarginalRelevanceSearchWithScoreByVector(embedding: number[], options?: {
521
+ k?: number;
522
+ fetchK?: number;
523
+ lambda?: number;
524
+ filter?: Record<string, any>;
525
+ }): Promise<[Document, number][]>;
526
+ getByIds(ids: string[]): Promise<Document[]>;
527
+ }
528
+
529
+ /**
530
+ * Metadata filter compiler for the legacy {@link PGVector} store.
531
+ *
532
+ * Ported from `PGVector._handle_field_filter` (Python, `vectorstores.py`).
533
+ * Unlike the v2 store, legacy metadata always lives in a single `cmetadata`
534
+ * JSONB column, so equality-style comparators use Postgres's `jsonb_path_match`
535
+ * (mirroring the SQLAlchemy `func.jsonb_path_match(...)` calls upstream) while
536
+ * `$in`/`$nin`/`$like`/`$ilike` operate on the extracted text value.
537
+ */
538
+
539
+ /** Compile a LangChain metadata filter dictionary against the legacy `cmetadata` column. */
540
+ declare function createLegacyFilterClause(filters: unknown, params: ParamBuilder): string;
541
+
542
+ declare const COLLECTIONS_TABLE = "langchain_pg_collection";
543
+ declare const EMBEDDINGS_TABLE = "langchain_pg_embedding";
544
+ interface PgVectorRow {
545
+ id: string;
546
+ collection_id: string;
547
+ embedding: string;
548
+ document: string;
549
+ cmetadata: Record<string, any> | null;
550
+ }
551
+ /** Extract all data belonging to a legacy `PGVector` collection, in batches. */
552
+ declare function extractPgvectorCollection(engine: PGEngine, collectionName: string, batchSize?: number): AsyncGenerator<PgVectorRow[]>;
553
+ /** List all collection names present in the legacy `PGVector` collection table. */
554
+ declare function listPgvectorCollectionNames(engine: PGEngine): Promise<string[]>;
555
+ interface MigratePgvectorCollectionOptions {
556
+ /** Delete the original legacy collection data upon successful migration. Default: `false`. */
557
+ deletePgCollection?: boolean;
558
+ /** Number of rows to read/insert per batch. Default: `1000`. */
559
+ insertBatchSize?: number;
560
+ }
561
+ /**
562
+ * Migrate all data present in a legacy `PGVector` collection into a
563
+ * {@link PGVectorStore} table.
564
+ */
565
+ declare function migratePgvectorCollection(engine: PGEngine, collectionName: string, vectorStore: PGVectorStore, options?: MigratePgvectorCollectionOptions): Promise<void>;
566
+
567
+ export { BaseIndex, COLLECTIONS_TABLE, Column, DEFAULT_DISTANCE_STRATEGY, DEFAULT_INDEX_NAME_SUFFIX, DistanceStrategy, EMBEDDINGS_TABLE, ExactNearestNeighbor, HNSWIndex, HNSWQueryOptions, HybridSearchConfig, IVFFlatIndex, IVFFlatQueryOptions, LegacyDistanceStrategy, PGEngine, PGVector, PGVectorStore, PGVectorTranslator, ParamBuilder, PostgresChatMessageHistory, QueryOptions, combineFilterClause, createFilterClause, createLegacyFilterClause, extractPgvectorCollection, listPgvectorCollectionNames, migratePgvectorCollection, reciprocalRankFusion, validateIdentifier, weightedSumRanking };
568
+ export type { BaseIndexArgs, ColumnDict, ColumnLike, DistanceStrategyValue, FilterContext, FusionFunction, FusionFunctionParams, HNSWIndexArgs, HNSWQueryOptionsArgs, HybridSearchConfigArgs, IVFFlatIndexArgs, IVFFlatQueryOptionsArgs, MMRByVectorOptions, MigratePgvectorCollectionOptions, PGVectorFromTextsOptions, PGVectorInitializeOptions, PGVectorStoreEmbeddings, PGVectorStoreFromTextsOptions, PGVectorStoreGetOptions, PGVectorStoreGetResult, PGVectorStoreInitializeOptions, PgVectorRow, PostgresChatMessageHistoryInput, PostgresConnection, Row };