langchain 0.0.154 → 0.0.156

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.
Files changed (78) hide show
  1. package/chat_models/bedrock.cjs +1 -0
  2. package/chat_models/bedrock.d.ts +1 -0
  3. package/chat_models/bedrock.js +1 -0
  4. package/dist/callbacks/base.d.ts +42 -28
  5. package/dist/callbacks/handlers/log_stream.cjs +283 -0
  6. package/dist/callbacks/handlers/log_stream.d.ts +99 -0
  7. package/dist/callbacks/handlers/log_stream.js +277 -0
  8. package/dist/callbacks/handlers/tracer.cjs +34 -18
  9. package/dist/callbacks/handlers/tracer.d.ts +18 -16
  10. package/dist/callbacks/handlers/tracer.js +34 -18
  11. package/dist/chat_models/bedrock.cjs +260 -0
  12. package/dist/chat_models/bedrock.d.ts +58 -0
  13. package/dist/chat_models/bedrock.js +254 -0
  14. package/dist/document_loaders/web/notionapi.cjs +8 -4
  15. package/dist/document_loaders/web/notionapi.js +8 -4
  16. package/dist/document_loaders/web/searchapi.cjs +134 -0
  17. package/dist/document_loaders/web/searchapi.d.ts +65 -0
  18. package/dist/document_loaders/web/searchapi.js +130 -0
  19. package/dist/embeddings/cloudflare_workersai.cjs +69 -0
  20. package/dist/embeddings/cloudflare_workersai.d.ts +28 -0
  21. package/dist/embeddings/cloudflare_workersai.js +65 -0
  22. package/dist/llms/bedrock.cjs +57 -67
  23. package/dist/llms/bedrock.d.ts +8 -35
  24. package/dist/llms/bedrock.js +57 -67
  25. package/dist/load/import_constants.cjs +4 -0
  26. package/dist/load/import_constants.js +4 -0
  27. package/dist/load/import_map.cjs +3 -2
  28. package/dist/load/import_map.d.ts +1 -0
  29. package/dist/load/import_map.js +1 -0
  30. package/dist/schema/runnable/base.cjs +64 -5
  31. package/dist/schema/runnable/base.d.ts +13 -0
  32. package/dist/schema/runnable/base.js +64 -5
  33. package/dist/tools/index.cjs +3 -1
  34. package/dist/tools/index.d.ts +1 -0
  35. package/dist/tools/index.js +1 -0
  36. package/dist/tools/searchapi.cjs +139 -0
  37. package/dist/tools/searchapi.d.ts +64 -0
  38. package/dist/tools/searchapi.js +135 -0
  39. package/dist/util/bedrock.cjs +54 -0
  40. package/dist/util/bedrock.d.ts +59 -0
  41. package/dist/util/bedrock.js +50 -0
  42. package/dist/util/fast-json-patch/index.cjs +48 -0
  43. package/dist/util/fast-json-patch/index.d.ts +21 -0
  44. package/dist/util/fast-json-patch/index.js +15 -0
  45. package/dist/util/fast-json-patch/src/core.cjs +469 -0
  46. package/dist/util/fast-json-patch/src/core.d.ts +111 -0
  47. package/dist/util/fast-json-patch/src/core.js +459 -0
  48. package/dist/util/fast-json-patch/src/helpers.cjs +194 -0
  49. package/dist/util/fast-json-patch/src/helpers.d.ts +36 -0
  50. package/dist/util/fast-json-patch/src/helpers.js +181 -0
  51. package/dist/util/googlevertexai-webauth.cjs +6 -2
  52. package/dist/util/googlevertexai-webauth.d.ts +1 -0
  53. package/dist/util/googlevertexai-webauth.js +6 -2
  54. package/dist/util/stream.cjs +2 -40
  55. package/dist/util/stream.d.ts +1 -2
  56. package/dist/util/stream.js +1 -38
  57. package/dist/vectorstores/cloudflare_vectorize.cjs +200 -0
  58. package/dist/vectorstores/cloudflare_vectorize.d.ts +90 -0
  59. package/dist/vectorstores/cloudflare_vectorize.js +173 -0
  60. package/dist/vectorstores/pgvector.cjs +1 -1
  61. package/dist/vectorstores/pgvector.js +1 -1
  62. package/dist/vectorstores/supabase.d.ts +1 -1
  63. package/dist/vectorstores/vercel_postgres.cjs +300 -0
  64. package/dist/vectorstores/vercel_postgres.d.ts +145 -0
  65. package/dist/vectorstores/vercel_postgres.js +296 -0
  66. package/document_loaders/web/searchapi.cjs +1 -0
  67. package/document_loaders/web/searchapi.d.ts +1 -0
  68. package/document_loaders/web/searchapi.js +1 -0
  69. package/embeddings/cloudflare_workersai.cjs +1 -0
  70. package/embeddings/cloudflare_workersai.d.ts +1 -0
  71. package/embeddings/cloudflare_workersai.js +1 -0
  72. package/package.json +60 -14
  73. package/vectorstores/cloudflare_vectorize.cjs +1 -0
  74. package/vectorstores/cloudflare_vectorize.d.ts +1 -0
  75. package/vectorstores/cloudflare_vectorize.js +1 -0
  76. package/vectorstores/vercel_postgres.cjs +1 -0
  77. package/vectorstores/vercel_postgres.d.ts +1 -0
  78. package/vectorstores/vercel_postgres.js +1 -0
@@ -0,0 +1,173 @@
1
+ import * as uuid from "uuid";
2
+ import { VectorStore } from "./base.js";
3
+ import { Document } from "../document.js";
4
+ import { chunkArray } from "../util/chunk.js";
5
+ import { AsyncCaller } from "../util/async_caller.js";
6
+ /**
7
+ * Class that extends the VectorStore class and provides methods to
8
+ * interact with the Cloudflare Vectorize vector database.
9
+ */
10
+ export class CloudflareVectorizeStore extends VectorStore {
11
+ _vectorstoreType() {
12
+ return "cloudflare_vectorize";
13
+ }
14
+ constructor(embeddings, args) {
15
+ super(embeddings, args);
16
+ Object.defineProperty(this, "textKey", {
17
+ enumerable: true,
18
+ configurable: true,
19
+ writable: true,
20
+ value: void 0
21
+ });
22
+ Object.defineProperty(this, "namespace", {
23
+ enumerable: true,
24
+ configurable: true,
25
+ writable: true,
26
+ value: void 0
27
+ });
28
+ Object.defineProperty(this, "index", {
29
+ enumerable: true,
30
+ configurable: true,
31
+ writable: true,
32
+ value: void 0
33
+ });
34
+ Object.defineProperty(this, "caller", {
35
+ enumerable: true,
36
+ configurable: true,
37
+ writable: true,
38
+ value: void 0
39
+ });
40
+ this.embeddings = embeddings;
41
+ const { index, textKey, ...asyncCallerArgs } = args;
42
+ if (!index) {
43
+ throw new Error("Must supply a Vectorize index binding, eg { index: env.VECTORIZE }");
44
+ }
45
+ this.index = index;
46
+ this.textKey = textKey ?? "text";
47
+ this.caller = new AsyncCaller({
48
+ maxConcurrency: 6,
49
+ maxRetries: 0,
50
+ ...asyncCallerArgs,
51
+ });
52
+ }
53
+ /**
54
+ * Method that adds documents to the Vectorize database.
55
+ * @param documents Array of documents to add.
56
+ * @param options Optional ids for the documents.
57
+ * @returns Promise that resolves with the ids of the added documents.
58
+ */
59
+ async addDocuments(documents, options) {
60
+ const texts = documents.map(({ pageContent }) => pageContent);
61
+ return this.addVectors(await this.embeddings.embedDocuments(texts), documents, options);
62
+ }
63
+ /**
64
+ * Method that adds vectors to the Vectorize database.
65
+ * @param vectors Array of vectors to add.
66
+ * @param documents Array of documents associated with the vectors.
67
+ * @param options Optional ids for the vectors.
68
+ * @returns Promise that resolves with the ids of the added vectors.
69
+ */
70
+ async addVectors(vectors, documents, options) {
71
+ const ids = Array.isArray(options) ? options : options?.ids;
72
+ const documentIds = ids == null ? documents.map(() => uuid.v4()) : ids;
73
+ const vectorizeVectors = vectors.map((values, idx) => {
74
+ const metadata = {
75
+ ...documents[idx].metadata,
76
+ [this.textKey]: documents[idx].pageContent,
77
+ };
78
+ return {
79
+ id: documentIds[idx],
80
+ metadata,
81
+ values,
82
+ };
83
+ });
84
+ // Stick to a limit of 500 vectors per upsert request
85
+ const chunkSize = 500;
86
+ const chunkedVectors = chunkArray(vectorizeVectors, chunkSize);
87
+ const batchRequests = chunkedVectors.map((chunk) => this.caller.call(async () => this.index.upsert(chunk)));
88
+ await Promise.all(batchRequests);
89
+ return documentIds;
90
+ }
91
+ /**
92
+ * Method that deletes vectors from the Vectorize database.
93
+ * @param params Parameters for the delete operation.
94
+ * @returns Promise that resolves when the delete operation is complete.
95
+ */
96
+ async delete(params) {
97
+ const batchSize = 1000;
98
+ const batchedIds = chunkArray(params.ids, batchSize);
99
+ const batchRequests = batchedIds.map((batchIds) => this.caller.call(async () => this.index.deleteByIds(batchIds)));
100
+ await Promise.all(batchRequests);
101
+ }
102
+ /**
103
+ * Method that performs a similarity search in the Vectorize database and
104
+ * returns the results along with their scores.
105
+ * @param query Query vector for the similarity search.
106
+ * @param k Number of top results to return.
107
+ * @returns Promise that resolves with an array of documents and their scores.
108
+ */
109
+ async similaritySearchVectorWithScore(query, k) {
110
+ const results = await this.index.query(query, {
111
+ returnVectors: true,
112
+ topK: k,
113
+ });
114
+ const result = [];
115
+ if (results.matches) {
116
+ for (const res of results.matches) {
117
+ const { [this.textKey]: pageContent, ...metadata } = res.vector?.metadata ?? {};
118
+ result.push([
119
+ new Document({ metadata, pageContent: pageContent }),
120
+ res.score,
121
+ ]);
122
+ }
123
+ }
124
+ return result;
125
+ }
126
+ /**
127
+ * Static method that creates a new instance of the CloudflareVectorizeStore class
128
+ * from texts.
129
+ * @param texts Array of texts to add to the Vectorize database.
130
+ * @param metadatas Metadata associated with the texts.
131
+ * @param embeddings Embeddings to use for the texts.
132
+ * @param dbConfig Configuration for the Vectorize database.
133
+ * @param options Optional ids for the vectors.
134
+ * @returns Promise that resolves with a new instance of the CloudflareVectorizeStore class.
135
+ */
136
+ static async fromTexts(texts, metadatas, embeddings, dbConfig) {
137
+ const docs = [];
138
+ for (let i = 0; i < texts.length; i += 1) {
139
+ const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;
140
+ const newDoc = new Document({
141
+ pageContent: texts[i],
142
+ metadata,
143
+ });
144
+ docs.push(newDoc);
145
+ }
146
+ return CloudflareVectorizeStore.fromDocuments(docs, embeddings, dbConfig);
147
+ }
148
+ /**
149
+ * Static method that creates a new instance of the CloudflareVectorizeStore class
150
+ * from documents.
151
+ * @param docs Array of documents to add to the Vectorize database.
152
+ * @param embeddings Embeddings to use for the documents.
153
+ * @param dbConfig Configuration for the Vectorize database.
154
+ * @param options Optional ids for the vectors.
155
+ * @returns Promise that resolves with a new instance of the CloudflareVectorizeStore class.
156
+ */
157
+ static async fromDocuments(docs, embeddings, dbConfig) {
158
+ const instance = new this(embeddings, dbConfig);
159
+ await instance.addDocuments(docs);
160
+ return instance;
161
+ }
162
+ /**
163
+ * Static method that creates a new instance of the CloudflareVectorizeStore class
164
+ * from an existing index.
165
+ * @param embeddings Embeddings to use for the documents.
166
+ * @param dbConfig Configuration for the Vectorize database.
167
+ * @returns Promise that resolves with a new instance of the CloudflareVectorizeStore class.
168
+ */
169
+ static async fromExistingIndex(embeddings, dbConfig) {
170
+ const instance = new this(embeddings, dbConfig);
171
+ return instance;
172
+ }
173
+ }
@@ -173,7 +173,7 @@ class PGVectorStore extends base_js_1.VectorStore {
173
173
  }
174
174
  catch (e) {
175
175
  console.error(e);
176
- throw new Error(`Error inserting: ${chunk[1]}`);
176
+ throw new Error(`Error inserting: ${e.message}`);
177
177
  }
178
178
  }
179
179
  }
@@ -167,7 +167,7 @@ export class PGVectorStore extends VectorStore {
167
167
  }
168
168
  catch (e) {
169
169
  console.error(e);
170
- throw new Error(`Error inserting: ${chunk[1]}`);
170
+ throw new Error(`Error inserting: ${e.message}`);
171
171
  }
172
172
  }
173
173
  }
@@ -54,7 +54,7 @@ export declare class SupabaseVectorStore extends VectorStore {
54
54
  * @returns A promise that resolves when the vectors have been deleted.
55
55
  */
56
56
  delete(params: {
57
- ids: string[];
57
+ ids: string[] | number[];
58
58
  }): Promise<void>;
59
59
  /**
60
60
  * Performs a similarity search on the vector store.
@@ -0,0 +1,300 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VercelPostgres = void 0;
4
+ const postgres_1 = require("@vercel/postgres");
5
+ const base_js_1 = require("./base.cjs");
6
+ const document_js_1 = require("../document.cjs");
7
+ const env_js_1 = require("../util/env.cjs");
8
+ /**
9
+ * Class that provides an interface to a Vercel Postgres vector database. It
10
+ * extends the `VectorStore` base class and implements methods for adding
11
+ * documents and vectors and performing similarity searches.
12
+ */
13
+ class VercelPostgres extends base_js_1.VectorStore {
14
+ _vectorstoreType() {
15
+ return "vercel";
16
+ }
17
+ constructor(embeddings, config) {
18
+ super(embeddings, config);
19
+ Object.defineProperty(this, "tableName", {
20
+ enumerable: true,
21
+ configurable: true,
22
+ writable: true,
23
+ value: void 0
24
+ });
25
+ Object.defineProperty(this, "idColumnName", {
26
+ enumerable: true,
27
+ configurable: true,
28
+ writable: true,
29
+ value: void 0
30
+ });
31
+ Object.defineProperty(this, "vectorColumnName", {
32
+ enumerable: true,
33
+ configurable: true,
34
+ writable: true,
35
+ value: void 0
36
+ });
37
+ Object.defineProperty(this, "contentColumnName", {
38
+ enumerable: true,
39
+ configurable: true,
40
+ writable: true,
41
+ value: void 0
42
+ });
43
+ Object.defineProperty(this, "metadataColumnName", {
44
+ enumerable: true,
45
+ configurable: true,
46
+ writable: true,
47
+ value: void 0
48
+ });
49
+ Object.defineProperty(this, "filter", {
50
+ enumerable: true,
51
+ configurable: true,
52
+ writable: true,
53
+ value: void 0
54
+ });
55
+ Object.defineProperty(this, "_verbose", {
56
+ enumerable: true,
57
+ configurable: true,
58
+ writable: true,
59
+ value: void 0
60
+ });
61
+ Object.defineProperty(this, "pool", {
62
+ enumerable: true,
63
+ configurable: true,
64
+ writable: true,
65
+ value: void 0
66
+ });
67
+ Object.defineProperty(this, "client", {
68
+ enumerable: true,
69
+ configurable: true,
70
+ writable: true,
71
+ value: void 0
72
+ });
73
+ this.tableName = config.tableName ?? "langchain_vectors";
74
+ this.filter = config.filter;
75
+ this.vectorColumnName = config.columns?.vectorColumnName ?? "embedding";
76
+ this.contentColumnName = config.columns?.contentColumnName ?? "text";
77
+ this.idColumnName = config.columns?.idColumnName ?? "id";
78
+ this.metadataColumnName = config.columns?.metadataColumnName ?? "metadata";
79
+ this.pool = config.pool;
80
+ this.client = config.client;
81
+ this._verbose =
82
+ (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_VERBOSE") === "true" ??
83
+ !!config.verbose;
84
+ }
85
+ /**
86
+ * Static method to create a new `VercelPostgres` instance from a
87
+ * connection. It creates a table if one does not exist, and calls
88
+ * `connect` to return a new instance of `VercelPostgres`.
89
+ *
90
+ * @param embeddings - Embeddings instance.
91
+ * @param fields - `VercelPostgres` configuration options.
92
+ * @returns A new instance of `VercelPostgres`.
93
+ */
94
+ static async initialize(embeddings, config) {
95
+ // Default maxUses to 1 for edge environments:
96
+ // https://github.com/vercel/storage/tree/main/packages/postgres#a-note-on-edge-environments
97
+ const pool = config?.pool ??
98
+ (0, postgres_1.createPool)({ maxUses: 1, ...config?.postgresConnectionOptions });
99
+ const client = config?.client ?? (await pool.connect());
100
+ const postgresqlVectorStore = new VercelPostgres(embeddings, {
101
+ ...config,
102
+ pool,
103
+ client,
104
+ });
105
+ await postgresqlVectorStore.ensureTableInDatabase();
106
+ return postgresqlVectorStore;
107
+ }
108
+ /**
109
+ * Method to add documents to the vector store. It converts the documents into
110
+ * vectors, and adds them to the store.
111
+ *
112
+ * @param documents - Array of `Document` instances.
113
+ * @returns Promise that resolves when the documents have been added.
114
+ */
115
+ async addDocuments(documents, options) {
116
+ const texts = documents.map(({ pageContent }) => pageContent);
117
+ return this.addVectors(await this.embeddings.embedDocuments(texts), documents, options);
118
+ }
119
+ /**
120
+ * Generates the SQL placeholders for a specific row at the provided index.
121
+ *
122
+ * @param index - The index of the row for which placeholders need to be generated.
123
+ * @returns The SQL placeholders for the row values.
124
+ */
125
+ generatePlaceholderForRowAt(
126
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
127
+ row, index) {
128
+ const base = index * row.length;
129
+ return `(${row.map((_, j) => `$${base + 1 + j}`)})`;
130
+ }
131
+ /**
132
+ * Constructs the SQL query for inserting rows into the specified table.
133
+ *
134
+ * @param rows - The rows of data to be inserted, consisting of values and records.
135
+ * @param chunkIndex - The starting index for generating query placeholders based on chunk positioning.
136
+ * @returns The complete SQL INSERT INTO query string.
137
+ */
138
+ async runInsertQuery(
139
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
140
+ rows, useIdColumn) {
141
+ const values = rows.map((row, j) => this.generatePlaceholderForRowAt(row, j));
142
+ const flatValues = rows.flat();
143
+ return this.client.query(`
144
+ INSERT INTO ${this.tableName} (
145
+ ${useIdColumn ? `${this.idColumnName},` : ""}
146
+ ${this.contentColumnName},
147
+ ${this.vectorColumnName},
148
+ ${this.metadataColumnName}
149
+ ) VALUES ${values.join(", ")}
150
+ ON CONFLICT (${this.idColumnName})
151
+ DO UPDATE
152
+ SET
153
+ ${this.contentColumnName} = EXCLUDED.${this.contentColumnName},
154
+ ${this.vectorColumnName} = EXCLUDED.${this.vectorColumnName},
155
+ ${this.metadataColumnName} = EXCLUDED.${this.metadataColumnName}
156
+ RETURNING ${this.idColumnName}`, flatValues);
157
+ }
158
+ /**
159
+ * Method to add vectors to the vector store. It converts the vectors into
160
+ * rows and inserts them into the database.
161
+ *
162
+ * @param vectors - Array of vectors.
163
+ * @param documents - Array of `Document` instances.
164
+ * @returns Promise that resolves when the vectors have been added.
165
+ */
166
+ async addVectors(vectors, documents, options) {
167
+ if (options?.ids !== undefined && options?.ids.length !== vectors.length) {
168
+ throw new Error(`If provided, the length of "ids" must be the same as the number of vectors.`);
169
+ }
170
+ const rows = vectors.map((embedding, idx) => {
171
+ const embeddingString = `[${embedding.join(",")}]`;
172
+ const row = [
173
+ documents[idx].pageContent,
174
+ embeddingString,
175
+ documents[idx].metadata,
176
+ ];
177
+ if (options?.ids) {
178
+ return [options.ids[idx], ...row];
179
+ }
180
+ return row;
181
+ });
182
+ const chunkSize = 500;
183
+ const ids = [];
184
+ for (let i = 0; i < rows.length; i += chunkSize) {
185
+ const chunk = rows.slice(i, i + chunkSize);
186
+ try {
187
+ const result = await this.runInsertQuery(chunk, options?.ids !== undefined);
188
+ ids.push(...result.rows.map((row) => row[this.idColumnName]));
189
+ }
190
+ catch (e) {
191
+ console.error(e);
192
+ throw new Error(`Error inserting: ${e.message}`);
193
+ }
194
+ }
195
+ return ids;
196
+ }
197
+ /**
198
+ * Method to perform a similarity search in the vector store. It returns
199
+ * the `k` most similar documents to the query vector, along with their
200
+ * similarity scores.
201
+ *
202
+ * @param query - Query vector.
203
+ * @param k - Number of most similar documents to return.
204
+ * @param filter - Optional filter to apply to the search.
205
+ * @returns Promise that resolves with an array of tuples, each containing a `Document` and its similarity score.
206
+ */
207
+ async similaritySearchVectorWithScore(query, k, filter) {
208
+ const embeddingString = `[${query.join(",")}]`;
209
+ const _filter = filter ?? "{}";
210
+ const queryString = `
211
+ SELECT *, ${this.vectorColumnName} <=> $1 as "_distance"
212
+ FROM ${this.tableName}
213
+ WHERE ${this.metadataColumnName} @> $2
214
+ ORDER BY "_distance" ASC
215
+ LIMIT $3;`;
216
+ const documents = (await this.client.query(queryString, [embeddingString, _filter, k])).rows;
217
+ const results = [];
218
+ for (const doc of documents) {
219
+ if (doc._distance != null && doc[this.contentColumnName] != null) {
220
+ const document = new document_js_1.Document({
221
+ pageContent: doc[this.contentColumnName],
222
+ metadata: doc[this.metadataColumnName],
223
+ });
224
+ results.push([document, doc._distance]);
225
+ }
226
+ }
227
+ return results;
228
+ }
229
+ async delete(params) {
230
+ if (params.ids !== undefined) {
231
+ await this.client.query(`DELETE FROM ${this.tableName} WHERE ${this.idColumnName} IN (${params.ids.map((_, idx) => `$${idx + 1}`)})`, params.ids);
232
+ }
233
+ else if (params.deleteAll) {
234
+ await this.client.query(`TRUNCATE TABLE ${this.tableName}`);
235
+ }
236
+ }
237
+ /**
238
+ * Method to ensure the existence of the table in the database. It creates
239
+ * the table if it does not already exist.
240
+ *
241
+ * @returns Promise that resolves when the table has been ensured.
242
+ */
243
+ async ensureTableInDatabase() {
244
+ await this.client.query(`CREATE EXTENSION IF NOT EXISTS vector;`);
245
+ await this.client.query(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp";`);
246
+ await this.client.query(`CREATE TABLE IF NOT EXISTS "${this.tableName}" (
247
+ "${this.idColumnName}" uuid NOT NULL DEFAULT uuid_generate_v4() PRIMARY KEY,
248
+ "${this.contentColumnName}" text,
249
+ "${this.metadataColumnName}" jsonb,
250
+ "${this.vectorColumnName}" vector
251
+ );`);
252
+ }
253
+ /**
254
+ * Static method to create a new `VercelPostgres` instance from an
255
+ * array of texts and their metadata. It converts the texts into
256
+ * `Document` instances and adds them to the store.
257
+ *
258
+ * @param texts - Array of texts.
259
+ * @param metadatas - Array of metadata objects or a single metadata object.
260
+ * @param embeddings - Embeddings instance.
261
+ * @param fields - `VercelPostgres` configuration options.
262
+ * @returns Promise that resolves with a new instance of `VercelPostgres`.
263
+ */
264
+ static async fromTexts(texts, metadatas, embeddings, dbConfig) {
265
+ const docs = [];
266
+ for (let i = 0; i < texts.length; i += 1) {
267
+ const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;
268
+ const newDoc = new document_js_1.Document({
269
+ pageContent: texts[i],
270
+ metadata,
271
+ });
272
+ docs.push(newDoc);
273
+ }
274
+ return this.fromDocuments(docs, embeddings, dbConfig);
275
+ }
276
+ /**
277
+ * Static method to create a new `VercelPostgres` instance from an
278
+ * array of `Document` instances. It adds the documents to the store.
279
+ *
280
+ * @param docs - Array of `Document` instances.
281
+ * @param embeddings - Embeddings instance.
282
+ * @param fields - `VercelPostgres` configuration options.
283
+ * @returns Promise that resolves with a new instance of `VercelPostgres`.
284
+ */
285
+ static async fromDocuments(docs, embeddings, dbConfig) {
286
+ const instance = await this.initialize(embeddings, dbConfig);
287
+ await instance.addDocuments(docs);
288
+ return instance;
289
+ }
290
+ /**
291
+ * Closes all the clients in the pool and terminates the pool.
292
+ *
293
+ * @returns Promise that resolves when all clients are closed and the pool is terminated.
294
+ */
295
+ async end() {
296
+ await this.client?.release();
297
+ return this.pool.end();
298
+ }
299
+ }
300
+ exports.VercelPostgres = VercelPostgres;
@@ -0,0 +1,145 @@
1
+ import { type VercelPool, type VercelPoolClient, type VercelPostgresPoolConfig } from "@vercel/postgres";
2
+ import { VectorStore } from "./base.js";
3
+ import { Embeddings } from "../embeddings/base.js";
4
+ import { Document } from "../document.js";
5
+ type Metadata = Record<string, unknown>;
6
+ /**
7
+ * Interface that defines the arguments required to create a
8
+ * `VercelPostgres` instance. It includes Postgres connection options,
9
+ * table name, filter, and verbosity level.
10
+ */
11
+ export interface VercelPostgresFields {
12
+ pool: VercelPool;
13
+ client: VercelPoolClient;
14
+ tableName?: string;
15
+ columns?: {
16
+ idColumnName?: string;
17
+ vectorColumnName?: string;
18
+ contentColumnName?: string;
19
+ metadataColumnName?: string;
20
+ };
21
+ filter?: Metadata;
22
+ verbose?: boolean;
23
+ }
24
+ /**
25
+ * Class that provides an interface to a Vercel Postgres vector database. It
26
+ * extends the `VectorStore` base class and implements methods for adding
27
+ * documents and vectors and performing similarity searches.
28
+ */
29
+ export declare class VercelPostgres extends VectorStore {
30
+ FilterType: Metadata;
31
+ tableName: string;
32
+ idColumnName: string;
33
+ vectorColumnName: string;
34
+ contentColumnName: string;
35
+ metadataColumnName: string;
36
+ filter?: Metadata;
37
+ _verbose?: boolean;
38
+ pool: VercelPool;
39
+ client: VercelPoolClient;
40
+ _vectorstoreType(): string;
41
+ private constructor();
42
+ /**
43
+ * Static method to create a new `VercelPostgres` instance from a
44
+ * connection. It creates a table if one does not exist, and calls
45
+ * `connect` to return a new instance of `VercelPostgres`.
46
+ *
47
+ * @param embeddings - Embeddings instance.
48
+ * @param fields - `VercelPostgres` configuration options.
49
+ * @returns A new instance of `VercelPostgres`.
50
+ */
51
+ static initialize(embeddings: Embeddings, config?: Partial<VercelPostgresFields> & {
52
+ postgresConnectionOptions?: VercelPostgresPoolConfig;
53
+ }): Promise<VercelPostgres>;
54
+ /**
55
+ * Method to add documents to the vector store. It converts the documents into
56
+ * vectors, and adds them to the store.
57
+ *
58
+ * @param documents - Array of `Document` instances.
59
+ * @returns Promise that resolves when the documents have been added.
60
+ */
61
+ addDocuments(documents: Document[], options?: {
62
+ ids?: string[];
63
+ }): Promise<string[]>;
64
+ /**
65
+ * Generates the SQL placeholders for a specific row at the provided index.
66
+ *
67
+ * @param index - The index of the row for which placeholders need to be generated.
68
+ * @returns The SQL placeholders for the row values.
69
+ */
70
+ protected generatePlaceholderForRowAt(row: (string | Record<string, any>)[], index: number): string;
71
+ /**
72
+ * Constructs the SQL query for inserting rows into the specified table.
73
+ *
74
+ * @param rows - The rows of data to be inserted, consisting of values and records.
75
+ * @param chunkIndex - The starting index for generating query placeholders based on chunk positioning.
76
+ * @returns The complete SQL INSERT INTO query string.
77
+ */
78
+ protected runInsertQuery(rows: (string | Record<string, any>)[][], useIdColumn: boolean): Promise<import("@vercel/postgres").QueryResult<any>>;
79
+ /**
80
+ * Method to add vectors to the vector store. It converts the vectors into
81
+ * rows and inserts them into the database.
82
+ *
83
+ * @param vectors - Array of vectors.
84
+ * @param documents - Array of `Document` instances.
85
+ * @returns Promise that resolves when the vectors have been added.
86
+ */
87
+ addVectors(vectors: number[][], documents: Document[], options?: {
88
+ ids?: string[];
89
+ }): Promise<string[]>;
90
+ /**
91
+ * Method to perform a similarity search in the vector store. It returns
92
+ * the `k` most similar documents to the query vector, along with their
93
+ * similarity scores.
94
+ *
95
+ * @param query - Query vector.
96
+ * @param k - Number of most similar documents to return.
97
+ * @param filter - Optional filter to apply to the search.
98
+ * @returns Promise that resolves with an array of tuples, each containing a `Document` and its similarity score.
99
+ */
100
+ similaritySearchVectorWithScore(query: number[], k: number, filter?: this["FilterType"]): Promise<[Document, number][]>;
101
+ delete(params: {
102
+ ids?: string[];
103
+ deleteAll?: boolean;
104
+ }): Promise<void>;
105
+ /**
106
+ * Method to ensure the existence of the table in the database. It creates
107
+ * the table if it does not already exist.
108
+ *
109
+ * @returns Promise that resolves when the table has been ensured.
110
+ */
111
+ ensureTableInDatabase(): Promise<void>;
112
+ /**
113
+ * Static method to create a new `VercelPostgres` instance from an
114
+ * array of texts and their metadata. It converts the texts into
115
+ * `Document` instances and adds them to the store.
116
+ *
117
+ * @param texts - Array of texts.
118
+ * @param metadatas - Array of metadata objects or a single metadata object.
119
+ * @param embeddings - Embeddings instance.
120
+ * @param fields - `VercelPostgres` configuration options.
121
+ * @returns Promise that resolves with a new instance of `VercelPostgres`.
122
+ */
123
+ static fromTexts(texts: string[], metadatas: object[] | object, embeddings: Embeddings, dbConfig?: Partial<VercelPostgresFields> & {
124
+ postgresConnectionOptions?: VercelPostgresPoolConfig;
125
+ }): Promise<VercelPostgres>;
126
+ /**
127
+ * Static method to create a new `VercelPostgres` instance from an
128
+ * array of `Document` instances. It adds the documents to the store.
129
+ *
130
+ * @param docs - Array of `Document` instances.
131
+ * @param embeddings - Embeddings instance.
132
+ * @param fields - `VercelPostgres` configuration options.
133
+ * @returns Promise that resolves with a new instance of `VercelPostgres`.
134
+ */
135
+ static fromDocuments(docs: Document[], embeddings: Embeddings, dbConfig?: Partial<VercelPostgresFields> & {
136
+ postgresConnectionOptions?: VercelPostgresPoolConfig;
137
+ }): Promise<VercelPostgres>;
138
+ /**
139
+ * Closes all the clients in the pool and terminates the pool.
140
+ *
141
+ * @returns Promise that resolves when all clients are closed and the pool is terminated.
142
+ */
143
+ end(): Promise<void>;
144
+ }
145
+ export {};