langchain 0.0.154 → 0.0.155

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 (53) hide show
  1. package/dist/callbacks/base.d.ts +42 -28
  2. package/dist/callbacks/handlers/log_stream.cjs +283 -0
  3. package/dist/callbacks/handlers/log_stream.d.ts +99 -0
  4. package/dist/callbacks/handlers/log_stream.js +277 -0
  5. package/dist/callbacks/handlers/tracer.cjs +34 -18
  6. package/dist/callbacks/handlers/tracer.d.ts +18 -16
  7. package/dist/callbacks/handlers/tracer.js +34 -18
  8. package/dist/document_loaders/web/notionapi.cjs +8 -4
  9. package/dist/document_loaders/web/notionapi.js +8 -4
  10. package/dist/document_loaders/web/searchapi.cjs +134 -0
  11. package/dist/document_loaders/web/searchapi.d.ts +65 -0
  12. package/dist/document_loaders/web/searchapi.js +130 -0
  13. package/dist/load/import_constants.cjs +1 -0
  14. package/dist/load/import_constants.js +1 -0
  15. package/dist/load/import_map.cjs +3 -2
  16. package/dist/load/import_map.d.ts +1 -0
  17. package/dist/load/import_map.js +1 -0
  18. package/dist/schema/runnable/base.cjs +64 -5
  19. package/dist/schema/runnable/base.d.ts +13 -0
  20. package/dist/schema/runnable/base.js +64 -5
  21. package/dist/tools/index.cjs +3 -1
  22. package/dist/tools/index.d.ts +1 -0
  23. package/dist/tools/index.js +1 -0
  24. package/dist/tools/searchapi.cjs +139 -0
  25. package/dist/tools/searchapi.d.ts +64 -0
  26. package/dist/tools/searchapi.js +135 -0
  27. package/dist/util/fast-json-patch/index.cjs +48 -0
  28. package/dist/util/fast-json-patch/index.d.ts +21 -0
  29. package/dist/util/fast-json-patch/index.js +15 -0
  30. package/dist/util/fast-json-patch/src/core.cjs +469 -0
  31. package/dist/util/fast-json-patch/src/core.d.ts +111 -0
  32. package/dist/util/fast-json-patch/src/core.js +459 -0
  33. package/dist/util/fast-json-patch/src/helpers.cjs +194 -0
  34. package/dist/util/fast-json-patch/src/helpers.d.ts +36 -0
  35. package/dist/util/fast-json-patch/src/helpers.js +181 -0
  36. package/dist/util/googlevertexai-webauth.cjs +6 -2
  37. package/dist/util/googlevertexai-webauth.d.ts +1 -0
  38. package/dist/util/googlevertexai-webauth.js +6 -2
  39. package/dist/util/stream.cjs +2 -40
  40. package/dist/util/stream.d.ts +1 -2
  41. package/dist/util/stream.js +1 -38
  42. package/dist/vectorstores/pgvector.cjs +1 -1
  43. package/dist/vectorstores/pgvector.js +1 -1
  44. package/dist/vectorstores/vercel_postgres.cjs +300 -0
  45. package/dist/vectorstores/vercel_postgres.d.ts +145 -0
  46. package/dist/vectorstores/vercel_postgres.js +296 -0
  47. package/document_loaders/web/searchapi.cjs +1 -0
  48. package/document_loaders/web/searchapi.d.ts +1 -0
  49. package/document_loaders/web/searchapi.js +1 -0
  50. package/package.json +22 -1
  51. package/vectorstores/vercel_postgres.cjs +1 -0
  52. package/vectorstores/vercel_postgres.d.ts +1 -0
  53. package/vectorstores/vercel_postgres.js +1 -0
@@ -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 {};