langchain 0.0.170 → 0.0.172

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 (102) hide show
  1. package/agents/format_scratchpad/log.cjs +1 -0
  2. package/agents/format_scratchpad/log.d.ts +1 -0
  3. package/agents/format_scratchpad/log.js +1 -0
  4. package/agents/format_scratchpad/log_to_message.cjs +1 -0
  5. package/agents/format_scratchpad/log_to_message.d.ts +1 -0
  6. package/agents/format_scratchpad/log_to_message.js +1 -0
  7. package/agents/format_scratchpad/xml.cjs +1 -0
  8. package/agents/format_scratchpad/xml.d.ts +1 -0
  9. package/agents/format_scratchpad/xml.js +1 -0
  10. package/agents/format_scratchpad.cjs +1 -1
  11. package/agents/format_scratchpad.d.ts +1 -1
  12. package/agents/format_scratchpad.js +1 -1
  13. package/agents/react/output_parser.cjs +1 -0
  14. package/agents/react/output_parser.d.ts +1 -0
  15. package/agents/react/output_parser.js +1 -0
  16. package/chat_models/llama_cpp.cjs +1 -0
  17. package/chat_models/llama_cpp.d.ts +1 -0
  18. package/chat_models/llama_cpp.js +1 -0
  19. package/dist/agents/format_scratchpad/log.cjs +16 -0
  20. package/dist/agents/format_scratchpad/log.d.ts +9 -0
  21. package/dist/agents/format_scratchpad/log.js +12 -0
  22. package/dist/agents/format_scratchpad/log_to_message.cjs +22 -0
  23. package/dist/agents/format_scratchpad/log_to_message.d.ts +2 -0
  24. package/dist/agents/format_scratchpad/log_to_message.js +18 -0
  25. package/dist/agents/{format_scratchpad.cjs → format_scratchpad/openai_functions.cjs} +3 -3
  26. package/dist/agents/{format_scratchpad.d.ts → format_scratchpad/openai_functions.d.ts} +1 -1
  27. package/dist/agents/{format_scratchpad.js → format_scratchpad/openai_functions.js} +3 -3
  28. package/dist/agents/format_scratchpad/xml.cjs +12 -0
  29. package/dist/agents/format_scratchpad/xml.d.ts +2 -0
  30. package/dist/agents/format_scratchpad/xml.js +8 -0
  31. package/dist/agents/react/output_parser.cjs +96 -0
  32. package/dist/agents/react/output_parser.d.ts +47 -0
  33. package/dist/agents/react/output_parser.js +92 -0
  34. package/dist/agents/react/prompt.cjs +13 -0
  35. package/dist/agents/react/prompt.d.ts +1 -0
  36. package/dist/agents/react/prompt.js +10 -0
  37. package/dist/agents/toolkits/openapi/openapi.cjs +1 -1
  38. package/dist/agents/toolkits/openapi/openapi.d.ts +1 -1
  39. package/dist/agents/toolkits/openapi/openapi.js +1 -1
  40. package/dist/chains/sql_db/sql_db_chain.cjs +2 -0
  41. package/dist/chains/sql_db/sql_db_chain.d.ts +2 -0
  42. package/dist/chains/sql_db/sql_db_chain.js +2 -0
  43. package/dist/chat_models/llama_cpp.cjs +243 -0
  44. package/dist/chat_models/llama_cpp.d.ts +94 -0
  45. package/dist/chat_models/llama_cpp.js +239 -0
  46. package/dist/document_loaders/web/pdf.cjs +23 -5
  47. package/dist/document_loaders/web/pdf.d.ts +9 -1
  48. package/dist/document_loaders/web/pdf.js +20 -2
  49. package/dist/embeddings/openai.cjs +11 -0
  50. package/dist/embeddings/openai.d.ts +2 -0
  51. package/dist/embeddings/openai.js +11 -0
  52. package/dist/graphs/neo4j_graph.cjs +14 -0
  53. package/dist/graphs/neo4j_graph.d.ts +14 -0
  54. package/dist/graphs/neo4j_graph.js +14 -0
  55. package/dist/llms/googlepalm.cjs +3 -0
  56. package/dist/llms/googlepalm.js +3 -0
  57. package/dist/load/import_constants.cjs +2 -0
  58. package/dist/load/import_constants.js +2 -0
  59. package/dist/load/import_map.cjs +8 -3
  60. package/dist/load/import_map.d.ts +6 -1
  61. package/dist/load/import_map.js +6 -1
  62. package/dist/retrievers/parent_document.cjs +22 -2
  63. package/dist/retrievers/parent_document.d.ts +8 -1
  64. package/dist/retrievers/parent_document.js +22 -2
  65. package/dist/schema/runnable/passthrough.cjs +3 -1
  66. package/dist/schema/runnable/passthrough.js +3 -1
  67. package/dist/sql_db.cjs +2 -0
  68. package/dist/sql_db.d.ts +2 -0
  69. package/dist/sql_db.js +2 -0
  70. package/dist/storage/file_system.cjs +147 -0
  71. package/dist/storage/file_system.d.ts +60 -0
  72. package/dist/storage/file_system.js +140 -0
  73. package/dist/tools/render.cjs +18 -0
  74. package/dist/tools/render.d.ts +13 -0
  75. package/dist/tools/render.js +14 -0
  76. package/dist/util/stream.cjs +3 -0
  77. package/dist/util/stream.js +3 -0
  78. package/dist/vectorstores/analyticdb.cjs +7 -3
  79. package/dist/vectorstores/analyticdb.d.ts +1 -1
  80. package/dist/vectorstores/analyticdb.js +7 -3
  81. package/dist/vectorstores/cassandra.cjs +25 -4
  82. package/dist/vectorstores/cassandra.d.ts +11 -1
  83. package/dist/vectorstores/cassandra.js +25 -4
  84. package/dist/vectorstores/momento_vector_index.cjs +3 -15
  85. package/dist/vectorstores/momento_vector_index.d.ts +0 -8
  86. package/dist/vectorstores/momento_vector_index.js +3 -15
  87. package/dist/vectorstores/neo4j_vector.cjs +14 -0
  88. package/dist/vectorstores/neo4j_vector.d.ts +14 -0
  89. package/dist/vectorstores/neo4j_vector.js +14 -0
  90. package/dist/vectorstores/qdrant.cjs +19 -11
  91. package/dist/vectorstores/qdrant.d.ts +1 -1
  92. package/dist/vectorstores/qdrant.js +19 -11
  93. package/dist/vectorstores/redis.cjs +4 -1
  94. package/dist/vectorstores/redis.d.ts +1 -1
  95. package/dist/vectorstores/redis.js +4 -1
  96. package/package.json +63 -7
  97. package/storage/file_system.cjs +1 -0
  98. package/storage/file_system.d.ts +1 -0
  99. package/storage/file_system.js +1 -0
  100. package/tools/render.cjs +1 -0
  101. package/tools/render.d.ts +1 -0
  102. package/tools/render.js +1 -0
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.LocalFileStore = void 0;
7
+ const fs_1 = require("fs");
8
+ const path_1 = __importDefault(require("path"));
9
+ const storage_js_1 = require("../schema/storage.cjs");
10
+ /**
11
+ * File system implementation of the BaseStore using a dictionary. Used for
12
+ * storing key-value pairs in the file system.
13
+ */
14
+ class LocalFileStore extends storage_js_1.BaseStore {
15
+ constructor(fields) {
16
+ super(fields);
17
+ Object.defineProperty(this, "lc_namespace", {
18
+ enumerable: true,
19
+ configurable: true,
20
+ writable: true,
21
+ value: ["langchain", "storage"]
22
+ });
23
+ Object.defineProperty(this, "rootPath", {
24
+ enumerable: true,
25
+ configurable: true,
26
+ writable: true,
27
+ value: void 0
28
+ });
29
+ this.rootPath = fields.rootPath;
30
+ }
31
+ /**
32
+ * Read and parse the file at the given path.
33
+ * @param key The key to read the file for.
34
+ * @returns Promise that resolves to the parsed file content.
35
+ */
36
+ async getParsedFile(key) {
37
+ try {
38
+ const fileContent = await fs_1.promises.readFile(this.getFullPath(key));
39
+ if (!fileContent) {
40
+ return undefined;
41
+ }
42
+ return fileContent;
43
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
44
+ }
45
+ catch (e) {
46
+ // File does not exist yet.
47
+ // eslint-disable-next-line no-instanceof/no-instanceof
48
+ if ("code" in e && e.code === "ENOENT") {
49
+ return undefined;
50
+ }
51
+ throw new Error(`Error reading and parsing file at path: ${this.rootPath}.\nError: ${JSON.stringify(e)}`);
52
+ }
53
+ }
54
+ /**
55
+ * Writes the given key-value pairs to the file at the given path.
56
+ * @param fileContent An object with the key-value pairs to be written to the file.
57
+ */
58
+ async setFileContent(content, key) {
59
+ try {
60
+ await fs_1.promises.writeFile(this.getFullPath(key), content);
61
+ }
62
+ catch (error) {
63
+ throw new Error(`Error writing file at path: ${this.getFullPath(key)}.\nError: ${JSON.stringify(error)}`);
64
+ }
65
+ }
66
+ /**
67
+ * Returns the full path of the file where the value of the given key is stored.
68
+ * @param key the key to get the full path for
69
+ */
70
+ getFullPath(key) {
71
+ try {
72
+ const keyAsTxtFile = `${key}.txt`;
73
+ const fullPath = path_1.default.join(this.rootPath, keyAsTxtFile);
74
+ return fullPath;
75
+ }
76
+ catch (e) {
77
+ throw new Error(`Error getting full path for key: ${key}.\nError: ${JSON.stringify(e)}`);
78
+ }
79
+ }
80
+ /**
81
+ * Retrieves the values associated with the given keys from the store.
82
+ * @param keys Keys to retrieve values for.
83
+ * @returns Array of values associated with the given keys.
84
+ */
85
+ async mget(keys) {
86
+ const values = [];
87
+ for (const key of keys) {
88
+ const fileContent = await this.getParsedFile(key);
89
+ values.push(fileContent);
90
+ }
91
+ return values;
92
+ }
93
+ /**
94
+ * Sets the values for the given keys in the store.
95
+ * @param keyValuePairs Array of key-value pairs to set in the store.
96
+ * @returns Promise that resolves when all key-value pairs have been set.
97
+ */
98
+ async mset(keyValuePairs) {
99
+ await Promise.all(keyValuePairs.map(([key, value]) => this.setFileContent(value, key)));
100
+ }
101
+ /**
102
+ * Deletes the given keys and their associated values from the store.
103
+ * @param keys Keys to delete from the store.
104
+ * @returns Promise that resolves when all keys have been deleted.
105
+ */
106
+ async mdelete(keys) {
107
+ await Promise.all(keys.map((key) => fs_1.promises.unlink(this.getFullPath(key))));
108
+ }
109
+ /**
110
+ * Asynchronous generator that yields keys from the store. If a prefix is
111
+ * provided, it only yields keys that start with the prefix.
112
+ * @param prefix Optional prefix to filter keys.
113
+ * @returns AsyncGenerator that yields keys from the store.
114
+ */
115
+ async *yieldKeys(prefix) {
116
+ const allFiles = await fs_1.promises.readdir(this.rootPath);
117
+ const allKeys = allFiles.map((file) => file.replace(".txt", ""));
118
+ for (const key of allKeys) {
119
+ if (prefix === undefined || key.startsWith(prefix)) {
120
+ yield key;
121
+ }
122
+ }
123
+ }
124
+ /**
125
+ * Static method for initializing the class.
126
+ * Preforms a check to see if the directory exists, and if not, creates it.
127
+ * @param path Path to the directory.
128
+ * @returns Promise that resolves to an instance of the class.
129
+ */
130
+ static async fromPath(rootPath) {
131
+ try {
132
+ // Verifies the directory exists at the provided path, and that it is readable and writable.
133
+ await fs_1.promises.access(rootPath, fs_1.promises.constants.R_OK | fs_1.promises.constants.W_OK);
134
+ }
135
+ catch (_) {
136
+ try {
137
+ // Directory does not exist, create it.
138
+ await fs_1.promises.mkdir(rootPath, { recursive: true });
139
+ }
140
+ catch (error) {
141
+ throw new Error(`An error occurred creating directory at: ${rootPath}.\nError: ${JSON.stringify(error)}`);
142
+ }
143
+ }
144
+ return new this({ rootPath });
145
+ }
146
+ }
147
+ exports.LocalFileStore = LocalFileStore;
@@ -0,0 +1,60 @@
1
+ import { BaseStore } from "../schema/storage.js";
2
+ /**
3
+ * File system implementation of the BaseStore using a dictionary. Used for
4
+ * storing key-value pairs in the file system.
5
+ */
6
+ export declare class LocalFileStore extends BaseStore<string, Uint8Array> {
7
+ lc_namespace: string[];
8
+ rootPath: string;
9
+ constructor(fields: {
10
+ rootPath: string;
11
+ });
12
+ /**
13
+ * Read and parse the file at the given path.
14
+ * @param key The key to read the file for.
15
+ * @returns Promise that resolves to the parsed file content.
16
+ */
17
+ private getParsedFile;
18
+ /**
19
+ * Writes the given key-value pairs to the file at the given path.
20
+ * @param fileContent An object with the key-value pairs to be written to the file.
21
+ */
22
+ private setFileContent;
23
+ /**
24
+ * Returns the full path of the file where the value of the given key is stored.
25
+ * @param key the key to get the full path for
26
+ */
27
+ private getFullPath;
28
+ /**
29
+ * Retrieves the values associated with the given keys from the store.
30
+ * @param keys Keys to retrieve values for.
31
+ * @returns Array of values associated with the given keys.
32
+ */
33
+ mget(keys: string[]): Promise<(Uint8Array | undefined)[]>;
34
+ /**
35
+ * Sets the values for the given keys in the store.
36
+ * @param keyValuePairs Array of key-value pairs to set in the store.
37
+ * @returns Promise that resolves when all key-value pairs have been set.
38
+ */
39
+ mset(keyValuePairs: [string, Uint8Array][]): Promise<void>;
40
+ /**
41
+ * Deletes the given keys and their associated values from the store.
42
+ * @param keys Keys to delete from the store.
43
+ * @returns Promise that resolves when all keys have been deleted.
44
+ */
45
+ mdelete(keys: string[]): Promise<void>;
46
+ /**
47
+ * Asynchronous generator that yields keys from the store. If a prefix is
48
+ * provided, it only yields keys that start with the prefix.
49
+ * @param prefix Optional prefix to filter keys.
50
+ * @returns AsyncGenerator that yields keys from the store.
51
+ */
52
+ yieldKeys(prefix?: string): AsyncGenerator<string>;
53
+ /**
54
+ * Static method for initializing the class.
55
+ * Preforms a check to see if the directory exists, and if not, creates it.
56
+ * @param path Path to the directory.
57
+ * @returns Promise that resolves to an instance of the class.
58
+ */
59
+ static fromPath(rootPath: string): Promise<LocalFileStore>;
60
+ }
@@ -0,0 +1,140 @@
1
+ import { promises as fsPromises } from "fs";
2
+ import nodePath from "path";
3
+ import { BaseStore } from "../schema/storage.js";
4
+ /**
5
+ * File system implementation of the BaseStore using a dictionary. Used for
6
+ * storing key-value pairs in the file system.
7
+ */
8
+ export class LocalFileStore extends BaseStore {
9
+ constructor(fields) {
10
+ super(fields);
11
+ Object.defineProperty(this, "lc_namespace", {
12
+ enumerable: true,
13
+ configurable: true,
14
+ writable: true,
15
+ value: ["langchain", "storage"]
16
+ });
17
+ Object.defineProperty(this, "rootPath", {
18
+ enumerable: true,
19
+ configurable: true,
20
+ writable: true,
21
+ value: void 0
22
+ });
23
+ this.rootPath = fields.rootPath;
24
+ }
25
+ /**
26
+ * Read and parse the file at the given path.
27
+ * @param key The key to read the file for.
28
+ * @returns Promise that resolves to the parsed file content.
29
+ */
30
+ async getParsedFile(key) {
31
+ try {
32
+ const fileContent = await fsPromises.readFile(this.getFullPath(key));
33
+ if (!fileContent) {
34
+ return undefined;
35
+ }
36
+ return fileContent;
37
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
38
+ }
39
+ catch (e) {
40
+ // File does not exist yet.
41
+ // eslint-disable-next-line no-instanceof/no-instanceof
42
+ if ("code" in e && e.code === "ENOENT") {
43
+ return undefined;
44
+ }
45
+ throw new Error(`Error reading and parsing file at path: ${this.rootPath}.\nError: ${JSON.stringify(e)}`);
46
+ }
47
+ }
48
+ /**
49
+ * Writes the given key-value pairs to the file at the given path.
50
+ * @param fileContent An object with the key-value pairs to be written to the file.
51
+ */
52
+ async setFileContent(content, key) {
53
+ try {
54
+ await fsPromises.writeFile(this.getFullPath(key), content);
55
+ }
56
+ catch (error) {
57
+ throw new Error(`Error writing file at path: ${this.getFullPath(key)}.\nError: ${JSON.stringify(error)}`);
58
+ }
59
+ }
60
+ /**
61
+ * Returns the full path of the file where the value of the given key is stored.
62
+ * @param key the key to get the full path for
63
+ */
64
+ getFullPath(key) {
65
+ try {
66
+ const keyAsTxtFile = `${key}.txt`;
67
+ const fullPath = nodePath.join(this.rootPath, keyAsTxtFile);
68
+ return fullPath;
69
+ }
70
+ catch (e) {
71
+ throw new Error(`Error getting full path for key: ${key}.\nError: ${JSON.stringify(e)}`);
72
+ }
73
+ }
74
+ /**
75
+ * Retrieves the values associated with the given keys from the store.
76
+ * @param keys Keys to retrieve values for.
77
+ * @returns Array of values associated with the given keys.
78
+ */
79
+ async mget(keys) {
80
+ const values = [];
81
+ for (const key of keys) {
82
+ const fileContent = await this.getParsedFile(key);
83
+ values.push(fileContent);
84
+ }
85
+ return values;
86
+ }
87
+ /**
88
+ * Sets the values for the given keys in the store.
89
+ * @param keyValuePairs Array of key-value pairs to set in the store.
90
+ * @returns Promise that resolves when all key-value pairs have been set.
91
+ */
92
+ async mset(keyValuePairs) {
93
+ await Promise.all(keyValuePairs.map(([key, value]) => this.setFileContent(value, key)));
94
+ }
95
+ /**
96
+ * Deletes the given keys and their associated values from the store.
97
+ * @param keys Keys to delete from the store.
98
+ * @returns Promise that resolves when all keys have been deleted.
99
+ */
100
+ async mdelete(keys) {
101
+ await Promise.all(keys.map((key) => fsPromises.unlink(this.getFullPath(key))));
102
+ }
103
+ /**
104
+ * Asynchronous generator that yields keys from the store. If a prefix is
105
+ * provided, it only yields keys that start with the prefix.
106
+ * @param prefix Optional prefix to filter keys.
107
+ * @returns AsyncGenerator that yields keys from the store.
108
+ */
109
+ async *yieldKeys(prefix) {
110
+ const allFiles = await fsPromises.readdir(this.rootPath);
111
+ const allKeys = allFiles.map((file) => file.replace(".txt", ""));
112
+ for (const key of allKeys) {
113
+ if (prefix === undefined || key.startsWith(prefix)) {
114
+ yield key;
115
+ }
116
+ }
117
+ }
118
+ /**
119
+ * Static method for initializing the class.
120
+ * Preforms a check to see if the directory exists, and if not, creates it.
121
+ * @param path Path to the directory.
122
+ * @returns Promise that resolves to an instance of the class.
123
+ */
124
+ static async fromPath(rootPath) {
125
+ try {
126
+ // Verifies the directory exists at the provided path, and that it is readable and writable.
127
+ await fsPromises.access(rootPath, fsPromises.constants.R_OK | fsPromises.constants.W_OK);
128
+ }
129
+ catch (_) {
130
+ try {
131
+ // Directory does not exist, create it.
132
+ await fsPromises.mkdir(rootPath, { recursive: true });
133
+ }
134
+ catch (error) {
135
+ throw new Error(`An error occurred creating directory at: ${rootPath}.\nError: ${JSON.stringify(error)}`);
136
+ }
137
+ }
138
+ return new this({ rootPath });
139
+ }
140
+ }
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.renderTextDescription = void 0;
4
+ /**
5
+ * Render the tool name and description in plain text.
6
+ *
7
+ * Output will be in the format of:
8
+ * ```
9
+ * search: This tool is used for search
10
+ * calculator: This tool is used for math
11
+ * ```
12
+ * @param tools
13
+ * @returns a string of all tools and their descriptions
14
+ */
15
+ function renderTextDescription(tools) {
16
+ return tools.map((tool) => `${tool.name}: ${tool.description}`).join("\n");
17
+ }
18
+ exports.renderTextDescription = renderTextDescription;
@@ -0,0 +1,13 @@
1
+ import { StructuredTool } from "./base.js";
2
+ /**
3
+ * Render the tool name and description in plain text.
4
+ *
5
+ * Output will be in the format of:
6
+ * ```
7
+ * search: This tool is used for search
8
+ * calculator: This tool is used for math
9
+ * ```
10
+ * @param tools
11
+ * @returns a string of all tools and their descriptions
12
+ */
13
+ export declare function renderTextDescription(tools: StructuredTool[]): string;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Render the tool name and description in plain text.
3
+ *
4
+ * Output will be in the format of:
5
+ * ```
6
+ * search: This tool is used for search
7
+ * calculator: This tool is used for math
8
+ * ```
9
+ * @param tools
10
+ * @returns a string of all tools and their descriptions
11
+ */
12
+ export function renderTextDescription(tools) {
13
+ return tools.map((tool) => `${tool.name}: ${tool.description}`).join("\n");
14
+ }
@@ -62,6 +62,9 @@ class IterableReadableStream extends ReadableStream {
62
62
  });
63
63
  }
64
64
  },
65
+ cancel() {
66
+ reader.releaseLock();
67
+ },
65
68
  });
66
69
  }
67
70
  static fromAsyncGenerator(generator) {
@@ -59,6 +59,9 @@ export class IterableReadableStream extends ReadableStream {
59
59
  });
60
60
  }
61
61
  },
62
+ cancel() {
63
+ reader.releaseLock();
64
+ },
62
65
  });
63
66
  }
64
67
  static fromAsyncGenerator(generator) {
@@ -34,7 +34,6 @@ const promises_1 = require("node:stream/promises");
34
34
  const node_stream_1 = require("node:stream");
35
35
  const base_js_1 = require("./base.cjs");
36
36
  const document_js_1 = require("../document.cjs");
37
- const _LANGCHAIN_DEFAULT_EMBEDDING_DIM = 1536;
38
37
  const _LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain_document";
39
38
  /**
40
39
  * Class that provides methods for creating and managing a collection of
@@ -85,8 +84,7 @@ class AnalyticDBVectorStore extends base_js_1.VectorStore {
85
84
  user: args.connectionOptions.user,
86
85
  password: args.connectionOptions.password,
87
86
  });
88
- this.embeddingDimension =
89
- args.embeddingDimension || _LANGCHAIN_DEFAULT_EMBEDDING_DIM;
87
+ this.embeddingDimension = args.embeddingDimension;
90
88
  this.collectionName =
91
89
  args.collectionName || _LANGCHAIN_DEFAULT_COLLECTION_NAME;
92
90
  this.preDeleteCollection = args.preDeleteCollection || false;
@@ -106,6 +104,9 @@ class AnalyticDBVectorStore extends base_js_1.VectorStore {
106
104
  * @returns Promise that resolves when the table and index are created.
107
105
  */
108
106
  async createTableIfNotExists() {
107
+ if (!this.embeddingDimension) {
108
+ this.embeddingDimension = (await this.embeddings.embedQuery("test")).length;
109
+ }
109
110
  const client = await this.pool.connect();
110
111
  try {
111
112
  await client.query("BEGIN");
@@ -194,6 +195,9 @@ class AnalyticDBVectorStore extends base_js_1.VectorStore {
194
195
  if (vectors.length !== documents.length) {
195
196
  throw new Error(`Vectors and documents must have the same length`);
196
197
  }
198
+ if (!this.embeddingDimension) {
199
+ this.embeddingDimension = (await this.embeddings.embedQuery("test")).length;
200
+ }
197
201
  if (vectors[0].length !== this.embeddingDimension) {
198
202
  throw new Error(`Vectors must have the same length as the number of dimensions (${this.embeddingDimension})`);
199
203
  }
@@ -21,7 +21,7 @@ export interface AnalyticDBArgs {
21
21
  export declare class AnalyticDBVectorStore extends VectorStore {
22
22
  FilterType: Record<string, any>;
23
23
  private pool;
24
- private embeddingDimension;
24
+ private embeddingDimension?;
25
25
  private collectionName;
26
26
  private preDeleteCollection;
27
27
  private isCreateCollection;
@@ -5,7 +5,6 @@ import { pipeline } from "node:stream/promises";
5
5
  import { Readable } from "node:stream";
6
6
  import { VectorStore } from "./base.js";
7
7
  import { Document } from "../document.js";
8
- const _LANGCHAIN_DEFAULT_EMBEDDING_DIM = 1536;
9
8
  const _LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain_document";
10
9
  /**
11
10
  * Class that provides methods for creating and managing a collection of
@@ -56,8 +55,7 @@ export class AnalyticDBVectorStore extends VectorStore {
56
55
  user: args.connectionOptions.user,
57
56
  password: args.connectionOptions.password,
58
57
  });
59
- this.embeddingDimension =
60
- args.embeddingDimension || _LANGCHAIN_DEFAULT_EMBEDDING_DIM;
58
+ this.embeddingDimension = args.embeddingDimension;
61
59
  this.collectionName =
62
60
  args.collectionName || _LANGCHAIN_DEFAULT_COLLECTION_NAME;
63
61
  this.preDeleteCollection = args.preDeleteCollection || false;
@@ -77,6 +75,9 @@ export class AnalyticDBVectorStore extends VectorStore {
77
75
  * @returns Promise that resolves when the table and index are created.
78
76
  */
79
77
  async createTableIfNotExists() {
78
+ if (!this.embeddingDimension) {
79
+ this.embeddingDimension = (await this.embeddings.embedQuery("test")).length;
80
+ }
80
81
  const client = await this.pool.connect();
81
82
  try {
82
83
  await client.query("BEGIN");
@@ -165,6 +166,9 @@ export class AnalyticDBVectorStore extends VectorStore {
165
166
  if (vectors.length !== documents.length) {
166
167
  throw new Error(`Vectors and documents must have the same length`);
167
168
  }
169
+ if (!this.embeddingDimension) {
170
+ this.embeddingDimension = (await this.embeddings.embedQuery("test")).length;
171
+ }
168
172
  if (vectors[0].length !== this.embeddingDimension) {
169
173
  throw new Error(`Vectors must have the same length as the number of dimensions (${this.embeddingDimension})`);
170
174
  }
@@ -53,6 +53,12 @@ class CassandraStore extends base_js_1.VectorStore {
53
53
  writable: true,
54
54
  value: void 0
55
55
  });
56
+ Object.defineProperty(this, "indices", {
57
+ enumerable: true,
58
+ configurable: true,
59
+ writable: true,
60
+ value: void 0
61
+ });
56
62
  Object.defineProperty(this, "isInitialized", {
57
63
  enumerable: true,
58
64
  configurable: true,
@@ -65,6 +71,7 @@ class CassandraStore extends base_js_1.VectorStore {
65
71
  this.table = args.table;
66
72
  this.primaryKey = args.primaryKey;
67
73
  this.metadataColumns = args.metadataColumns;
74
+ this.indices = args.indices;
68
75
  }
69
76
  /**
70
77
  * Method to save vectors to the Cassandra database.
@@ -94,13 +101,14 @@ class CassandraStore extends base_js_1.VectorStore {
94
101
  * Method to search for vectors that are similar to a given query vector.
95
102
  * @param query The query vector.
96
103
  * @param k The number of similar vectors to return.
104
+ * @param filter
97
105
  * @returns Promise that resolves with an array of tuples, each containing a Document and a score.
98
106
  */
99
- async similaritySearchVectorWithScore(query, k) {
107
+ async similaritySearchVectorWithScore(query, k, filter) {
100
108
  if (!this.isInitialized) {
101
109
  await this.initialize();
102
110
  }
103
- const queryStr = this.buildSearchQuery(query, k);
111
+ const queryStr = this.buildSearchQuery(query, k, filter);
104
112
  const queryResultSet = await this.client.execute(queryStr);
105
113
  return queryResultSet?.rows.map((row, index) => {
106
114
  const textContent = row.text;
@@ -173,6 +181,11 @@ class CassandraStore extends base_js_1.VectorStore {
173
181
  await this.client
174
182
  .execute(`CREATE CUSTOM INDEX IF NOT EXISTS idx_vector_${this.table}
175
183
  ON ${this.keyspace}.${this.table}(vector) USING 'StorageAttachedIndex';`);
184
+ for await (const { name, value } of this.indices) {
185
+ await this.client
186
+ .execute(`CREATE CUSTOM INDEX IF NOT EXISTS idx_${this.table}_${name}
187
+ ON ${this.keyspace}.${this.table} ${value} USING 'StorageAttachedIndex';`);
188
+ }
176
189
  this.isInitialized = true;
177
190
  }
178
191
  /**
@@ -200,15 +213,23 @@ class CassandraStore extends base_js_1.VectorStore {
200
213
  }
201
214
  return queries;
202
215
  }
216
+ buildWhereClause(filter) {
217
+ const whereClause = Object.entries(filter)
218
+ .map(([key, value]) => `${key} = '${value}'`)
219
+ .join(" AND ");
220
+ return `WHERE ${whereClause}`;
221
+ }
203
222
  /**
204
223
  * Method to build an CQL query for searching for similar vectors in the
205
224
  * Cassandra database.
206
225
  * @param query The query vector.
207
226
  * @param k The number of similar vectors to return.
227
+ * @param filter
208
228
  * @returns The CQL query string.
209
229
  */
210
- buildSearchQuery(query, k) {
211
- return `SELECT * FROM ${this.keyspace}.${this.table} ORDER BY vector ANN OF [${query}] LIMIT ${k || 1};`;
230
+ buildSearchQuery(query, k = 1, filter = undefined) {
231
+ const whereClause = filter ? this.buildWhereClause(filter) : "";
232
+ return `SELECT * FROM ${this.keyspace}.${this.table} ${whereClause} ORDER BY vector ANN OF [${query}] LIMIT ${k}`;
212
233
  }
213
234
  }
214
235
  exports.CassandraStore = CassandraStore;
@@ -6,12 +6,17 @@ export interface Column {
6
6
  type: string;
7
7
  name: string;
8
8
  }
9
+ export interface Index {
10
+ name: string;
11
+ value: string;
12
+ }
9
13
  export interface CassandraLibArgs extends DseClientOptions {
10
14
  table: string;
11
15
  keyspace: string;
12
16
  dimensions: number;
13
17
  primaryKey: Column;
14
18
  metadataColumns: Column[];
19
+ indices: Index[];
15
20
  }
16
21
  /**
17
22
  * Class for interacting with the Cassandra database. It extends the
@@ -20,12 +25,14 @@ export interface CassandraLibArgs extends DseClientOptions {
20
25
  * texts or documents.
21
26
  */
22
27
  export declare class CassandraStore extends VectorStore {
28
+ FilterType: Record<string, any>;
23
29
  private client;
24
30
  private readonly dimensions;
25
31
  private readonly keyspace;
26
32
  private primaryKey;
27
33
  private metadataColumns;
28
34
  private readonly table;
35
+ private indices;
29
36
  private isInitialized;
30
37
  _vectorstoreType(): string;
31
38
  constructor(embeddings: Embeddings, args: CassandraLibArgs);
@@ -46,9 +53,10 @@ export declare class CassandraStore extends VectorStore {
46
53
  * Method to search for vectors that are similar to a given query vector.
47
54
  * @param query The query vector.
48
55
  * @param k The number of similar vectors to return.
56
+ * @param filter
49
57
  * @returns Promise that resolves with an array of tuples, each containing a Document and a score.
50
58
  */
51
- similaritySearchVectorWithScore(query: number[], k: number): Promise<[Document, number][]>;
59
+ similaritySearchVectorWithScore(query: number[], k: number, filter?: this["FilterType"]): Promise<[Document, number][]>;
52
60
  /**
53
61
  * Static method to create an instance of CassandraStore from texts.
54
62
  * @param texts The texts to use.
@@ -87,11 +95,13 @@ export declare class CassandraStore extends VectorStore {
87
95
  * @returns The CQL query string.
88
96
  */
89
97
  private buildInsertQuery;
98
+ private buildWhereClause;
90
99
  /**
91
100
  * Method to build an CQL query for searching for similar vectors in the
92
101
  * Cassandra database.
93
102
  * @param query The query vector.
94
103
  * @param k The number of similar vectors to return.
104
+ * @param filter
95
105
  * @returns The CQL query string.
96
106
  */
97
107
  private buildSearchQuery;