langchain 0.0.76 → 0.0.78

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 (162) hide show
  1. package/chains/query_constructor/ir.cjs +1 -0
  2. package/chains/query_constructor/ir.d.ts +1 -0
  3. package/chains/query_constructor/ir.js +1 -0
  4. package/chains/query_constructor.cjs +1 -0
  5. package/chains/query_constructor.d.ts +1 -0
  6. package/chains/query_constructor.js +1 -0
  7. package/dist/agents/agent.d.ts +5 -4
  8. package/dist/agents/agent_toolkits/sql/sql.cjs +2 -2
  9. package/dist/agents/agent_toolkits/sql/sql.d.ts +1 -1
  10. package/dist/agents/agent_toolkits/sql/sql.js +2 -2
  11. package/dist/agents/chat/index.cjs +3 -3
  12. package/dist/agents/chat/index.d.ts +1 -0
  13. package/dist/agents/chat/index.js +3 -3
  14. package/dist/agents/chat_convo/index.cjs +30 -14
  15. package/dist/agents/chat_convo/index.d.ts +5 -1
  16. package/dist/agents/chat_convo/index.js +31 -15
  17. package/dist/agents/chat_convo/outputParser.cjs +79 -7
  18. package/dist/agents/chat_convo/outputParser.d.ts +25 -13
  19. package/dist/agents/chat_convo/outputParser.js +77 -6
  20. package/dist/agents/chat_convo/prompt.cjs +11 -8
  21. package/dist/agents/chat_convo/prompt.d.ts +2 -2
  22. package/dist/agents/chat_convo/prompt.js +11 -8
  23. package/dist/agents/executor.d.ts +2 -3
  24. package/dist/agents/index.cjs +6 -1
  25. package/dist/agents/index.d.ts +2 -0
  26. package/dist/agents/index.js +2 -0
  27. package/dist/agents/initialize.cjs +19 -13
  28. package/dist/agents/initialize.d.ts +12 -2
  29. package/dist/agents/initialize.js +16 -10
  30. package/dist/agents/mrkl/index.cjs +3 -3
  31. package/dist/agents/mrkl/index.d.ts +1 -0
  32. package/dist/agents/mrkl/index.js +3 -3
  33. package/dist/agents/mrkl/outputParser.cjs +2 -2
  34. package/dist/agents/mrkl/outputParser.js +2 -2
  35. package/dist/agents/structured_chat/index.cjs +106 -0
  36. package/dist/agents/structured_chat/index.d.ts +44 -0
  37. package/dist/agents/structured_chat/index.js +102 -0
  38. package/dist/agents/structured_chat/outputParser.cjs +92 -0
  39. package/dist/agents/structured_chat/outputParser.d.ts +24 -0
  40. package/dist/agents/structured_chat/outputParser.js +87 -0
  41. package/dist/agents/structured_chat/prompt.cjs +62 -0
  42. package/dist/agents/structured_chat/prompt.d.ts +4 -0
  43. package/dist/agents/structured_chat/prompt.js +59 -0
  44. package/dist/callbacks/handlers/tracer_langchain.cjs +12 -4
  45. package/dist/callbacks/handlers/tracer_langchain.d.ts +4 -1
  46. package/dist/callbacks/handlers/tracer_langchain.js +12 -4
  47. package/dist/callbacks/manager.cjs +6 -2
  48. package/dist/callbacks/manager.js +6 -2
  49. package/dist/chains/query_constructor/index.cjs +105 -0
  50. package/dist/chains/query_constructor/index.d.ts +37 -0
  51. package/dist/chains/query_constructor/index.js +95 -0
  52. package/dist/chains/query_constructor/ir.cjs +116 -0
  53. package/dist/chains/query_constructor/ir.d.ts +60 -0
  54. package/dist/chains/query_constructor/ir.js +107 -0
  55. package/dist/chains/query_constructor/parser.cjs +103 -0
  56. package/dist/chains/query_constructor/parser.d.ts +12 -0
  57. package/dist/chains/query_constructor/parser.js +99 -0
  58. package/dist/chains/query_constructor/prompt.cjs +127 -0
  59. package/dist/chains/query_constructor/prompt.d.ts +15 -0
  60. package/dist/chains/query_constructor/prompt.js +124 -0
  61. package/dist/chains/sql_db/sql_db_chain.cjs +13 -0
  62. package/dist/chains/sql_db/sql_db_chain.d.ts +2 -0
  63. package/dist/chains/sql_db/sql_db_chain.js +13 -0
  64. package/dist/client/langchainplus.cjs +21 -15
  65. package/dist/client/langchainplus.d.ts +4 -2
  66. package/dist/client/langchainplus.js +21 -15
  67. package/dist/llms/sagemaker_endpoint.cjs +123 -0
  68. package/dist/llms/sagemaker_endpoint.d.ts +82 -0
  69. package/dist/llms/sagemaker_endpoint.js +118 -0
  70. package/dist/memory/buffer_memory.cjs +1 -1
  71. package/dist/memory/buffer_memory.js +1 -1
  72. package/dist/memory/buffer_window_memory.cjs +1 -1
  73. package/dist/memory/buffer_window_memory.js +1 -1
  74. package/dist/output_parsers/expression.cjs +68 -0
  75. package/dist/output_parsers/expression.d.ts +25 -0
  76. package/dist/output_parsers/expression.js +49 -0
  77. package/dist/output_parsers/expression_type_handlers/array_literal_expression_handler.cjs +26 -0
  78. package/dist/output_parsers/expression_type_handlers/array_literal_expression_handler.d.ts +7 -0
  79. package/dist/output_parsers/expression_type_handlers/array_literal_expression_handler.js +22 -0
  80. package/dist/output_parsers/expression_type_handlers/base.cjs +67 -0
  81. package/dist/output_parsers/expression_type_handlers/base.d.ts +23 -0
  82. package/dist/output_parsers/expression_type_handlers/base.js +62 -0
  83. package/dist/output_parsers/expression_type_handlers/boolean_literal_handler.cjs +24 -0
  84. package/dist/output_parsers/expression_type_handlers/boolean_literal_handler.d.ts +7 -0
  85. package/dist/output_parsers/expression_type_handlers/boolean_literal_handler.js +20 -0
  86. package/dist/output_parsers/expression_type_handlers/call_expression_handler.cjs +52 -0
  87. package/dist/output_parsers/expression_type_handlers/call_expression_handler.d.ts +7 -0
  88. package/dist/output_parsers/expression_type_handlers/call_expression_handler.js +48 -0
  89. package/dist/output_parsers/expression_type_handlers/factory.cjs +56 -0
  90. package/dist/output_parsers/expression_type_handlers/factory.d.ts +9 -0
  91. package/dist/output_parsers/expression_type_handlers/factory.js +52 -0
  92. package/dist/output_parsers/expression_type_handlers/identifier_handler.cjs +22 -0
  93. package/dist/output_parsers/expression_type_handlers/identifier_handler.d.ts +7 -0
  94. package/dist/output_parsers/expression_type_handlers/identifier_handler.js +18 -0
  95. package/dist/output_parsers/expression_type_handlers/member_expression_handler.cjs +45 -0
  96. package/dist/output_parsers/expression_type_handlers/member_expression_handler.d.ts +7 -0
  97. package/dist/output_parsers/expression_type_handlers/member_expression_handler.js +41 -0
  98. package/dist/output_parsers/expression_type_handlers/numeric_literal_handler.cjs +24 -0
  99. package/dist/output_parsers/expression_type_handlers/numeric_literal_handler.d.ts +7 -0
  100. package/dist/output_parsers/expression_type_handlers/numeric_literal_handler.js +20 -0
  101. package/dist/output_parsers/expression_type_handlers/object_literal_expression_handler.cjs +29 -0
  102. package/dist/output_parsers/expression_type_handlers/object_literal_expression_handler.d.ts +7 -0
  103. package/dist/output_parsers/expression_type_handlers/object_literal_expression_handler.js +25 -0
  104. package/dist/output_parsers/expression_type_handlers/property_assignment_handler.cjs +36 -0
  105. package/dist/output_parsers/expression_type_handlers/property_assignment_handler.d.ts +7 -0
  106. package/dist/output_parsers/expression_type_handlers/property_assignment_handler.js +32 -0
  107. package/dist/output_parsers/expression_type_handlers/string_literal_handler.cjs +22 -0
  108. package/dist/output_parsers/expression_type_handlers/string_literal_handler.d.ts +7 -0
  109. package/dist/output_parsers/expression_type_handlers/string_literal_handler.js +18 -0
  110. package/dist/output_parsers/expression_type_handlers/types.cjs +2 -0
  111. package/dist/output_parsers/expression_type_handlers/types.d.ts +41 -0
  112. package/dist/output_parsers/expression_type_handlers/types.js +1 -0
  113. package/dist/output_parsers/index.cjs +2 -1
  114. package/dist/output_parsers/index.d.ts +1 -1
  115. package/dist/output_parsers/index.js +1 -1
  116. package/dist/output_parsers/structured.cjs +81 -23
  117. package/dist/output_parsers/structured.d.ts +18 -0
  118. package/dist/output_parsers/structured.js +79 -22
  119. package/dist/retrievers/self_query/index.cjs +79 -0
  120. package/dist/retrievers/self_query/index.d.ts +33 -0
  121. package/dist/retrievers/self_query/index.js +74 -0
  122. package/dist/retrievers/self_query/translator.cjs +72 -0
  123. package/dist/retrievers/self_query/translator.d.ts +14 -0
  124. package/dist/retrievers/self_query/translator.js +67 -0
  125. package/dist/schema/query_constructor.cjs +26 -0
  126. package/dist/schema/query_constructor.d.ts +6 -0
  127. package/dist/schema/query_constructor.js +22 -0
  128. package/dist/text_splitter.cjs +2 -1
  129. package/dist/text_splitter.js +2 -1
  130. package/dist/tools/dynamic.cjs +39 -1
  131. package/dist/tools/dynamic.d.ts +18 -3
  132. package/dist/tools/dynamic.js +38 -1
  133. package/dist/tools/index.cjs +2 -1
  134. package/dist/tools/index.d.ts +1 -1
  135. package/dist/tools/index.js +1 -1
  136. package/dist/tools/json.cjs +3 -1
  137. package/dist/tools/json.js +3 -1
  138. package/dist/tools/sql.cjs +17 -11
  139. package/dist/tools/sql.d.ts +7 -1
  140. package/dist/tools/sql.js +17 -11
  141. package/dist/util/event-source-parse.cjs +31 -5
  142. package/dist/util/event-source-parse.d.ts +3 -3
  143. package/dist/util/event-source-parse.js +31 -5
  144. package/dist/vectorstores/faiss.cjs +245 -0
  145. package/dist/vectorstores/faiss.d.ts +39 -0
  146. package/dist/vectorstores/faiss.js +218 -0
  147. package/llms/sagemaker_endpoint.cjs +1 -0
  148. package/llms/sagemaker_endpoint.d.ts +1 -0
  149. package/llms/sagemaker_endpoint.js +1 -0
  150. package/output_parsers/expression.cjs +1 -0
  151. package/output_parsers/expression.d.ts +1 -0
  152. package/output_parsers/expression.js +1 -0
  153. package/package.json +79 -3
  154. package/retrievers/self_query.cjs +1 -0
  155. package/retrievers/self_query.d.ts +1 -0
  156. package/retrievers/self_query.js +1 -0
  157. package/schema/query_constructor.cjs +1 -0
  158. package/schema/query_constructor.d.ts +1 -0
  159. package/schema/query_constructor.js +1 -0
  160. package/vectorstores/faiss.cjs +1 -0
  161. package/vectorstores/faiss.d.ts +1 -0
  162. package/vectorstores/faiss.js +1 -0
@@ -13,9 +13,18 @@ export const EventStreamContentType = "text/event-stream";
13
13
  */
14
14
  export async function getBytes(stream, onChunk) {
15
15
  const reader = stream.getReader();
16
- let result;
17
- // eslint-disable-next-line no-cond-assign
18
- while (!(result = await reader.read()).done) {
16
+ // CHANGED: Introduced a "flush" mechanism to process potential pending messages when the stream ends.
17
+ // This change is essential to ensure that we capture every last piece of information from streams,
18
+ // such as those from Azure OpenAI, which may not terminate with a blank line. Without this
19
+ // mechanism, we risk ignoring a possibly significant last message.
20
+ // See https://github.com/hwchase17/langchainjs/issues/1299 for details.
21
+ // eslint-disable-next-line no-constant-condition
22
+ while (true) {
23
+ const result = await reader.read();
24
+ if (result.done) {
25
+ onChunk(new Uint8Array(), true);
26
+ break;
27
+ }
19
28
  onChunk(result.value);
20
29
  }
21
30
  }
@@ -31,7 +40,11 @@ export function getLines(onLine) {
31
40
  let fieldLength; // length of the `field` portion of the line
32
41
  let discardTrailingNewline = false;
33
42
  // return a function that can process each incoming byte chunk:
34
- return function onChunk(arr) {
43
+ return function onChunk(arr, flush) {
44
+ if (flush) {
45
+ onLine(arr, 0, true);
46
+ return;
47
+ }
35
48
  if (buffer === undefined) {
36
49
  buffer = arr;
37
50
  position = 0;
@@ -102,7 +115,14 @@ export function getMessages(onMessage, onId, onRetry) {
102
115
  let message = newMessage();
103
116
  const decoder = new TextDecoder();
104
117
  // return a function that can process each incoming line buffer:
105
- return function onLine(line, fieldLength) {
118
+ return function onLine(line, fieldLength, flush) {
119
+ if (flush) {
120
+ if (!isEmpty(message)) {
121
+ onMessage?.(message);
122
+ message = newMessage();
123
+ }
124
+ return;
125
+ }
106
126
  if (line.length === 0) {
107
127
  // empty line denotes end of message. Trigger the callback and start a new message:
108
128
  onMessage?.(message);
@@ -157,3 +177,9 @@ function newMessage() {
157
177
  retry: undefined,
158
178
  };
159
179
  }
180
+ function isEmpty(message) {
181
+ return (message.data === "" &&
182
+ message.event === "" &&
183
+ message.id === "" &&
184
+ message.retry === undefined);
185
+ }
@@ -0,0 +1,245 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.FaissStore = void 0;
27
+ const uuid = __importStar(require("uuid"));
28
+ const base_js_1 = require("./base.cjs");
29
+ const document_js_1 = require("../document.cjs");
30
+ const index_js_1 = require("../docstore/index.cjs");
31
+ class FaissStore extends base_js_1.SaveableVectorStore {
32
+ constructor(embeddings, args) {
33
+ super(embeddings, args);
34
+ Object.defineProperty(this, "_index", {
35
+ enumerable: true,
36
+ configurable: true,
37
+ writable: true,
38
+ value: void 0
39
+ });
40
+ Object.defineProperty(this, "_mapping", {
41
+ enumerable: true,
42
+ configurable: true,
43
+ writable: true,
44
+ value: void 0
45
+ });
46
+ Object.defineProperty(this, "docstore", {
47
+ enumerable: true,
48
+ configurable: true,
49
+ writable: true,
50
+ value: void 0
51
+ });
52
+ Object.defineProperty(this, "args", {
53
+ enumerable: true,
54
+ configurable: true,
55
+ writable: true,
56
+ value: void 0
57
+ });
58
+ this.args = args;
59
+ this._index = args.index;
60
+ this._mapping = args.mapping ?? {};
61
+ this.embeddings = embeddings;
62
+ this.docstore = args?.docstore ?? new index_js_1.InMemoryDocstore();
63
+ }
64
+ async addDocuments(documents) {
65
+ const texts = documents.map(({ pageContent }) => pageContent);
66
+ return this.addVectors(await this.embeddings.embedDocuments(texts), documents);
67
+ }
68
+ get index() {
69
+ if (!this._index) {
70
+ throw new Error("Vector store not initialised yet. Try calling `fromTexts` or `fromDocuments` first.");
71
+ }
72
+ return this._index;
73
+ }
74
+ set index(index) {
75
+ this._index = index;
76
+ }
77
+ async addVectors(vectors, documents) {
78
+ if (vectors.length === 0) {
79
+ return;
80
+ }
81
+ if (vectors.length !== documents.length) {
82
+ throw new Error(`Vectors and documents must have the same length`);
83
+ }
84
+ const dv = vectors[0].length;
85
+ if (!this._index) {
86
+ const { IndexFlatL2 } = await FaissStore.importFaiss();
87
+ this._index = new IndexFlatL2(dv);
88
+ }
89
+ const d = this.index.getDimension();
90
+ if (dv !== d) {
91
+ throw new Error(`Vectors must have the same length as the number of dimensions (${d})`);
92
+ }
93
+ const docstoreSize = this.docstore.count;
94
+ for (let i = 0; i < vectors.length; i += 1) {
95
+ const documentId = uuid.v4();
96
+ const id = docstoreSize + i;
97
+ this.index.add(vectors[i]);
98
+ this._mapping[id] = documentId;
99
+ this.docstore.add({ [documentId]: documents[i] });
100
+ }
101
+ }
102
+ async similaritySearchVectorWithScore(query, k) {
103
+ const d = this.index.getDimension();
104
+ if (query.length !== d) {
105
+ throw new Error(`Query vector must have the same length as the number of dimensions (${d})`);
106
+ }
107
+ if (k > this.index.ntotal()) {
108
+ const total = this.index.ntotal();
109
+ console.warn(`k (${k}) is greater than the number of elements in the index (${total}), setting k to ${total}`);
110
+ // eslint-disable-next-line no-param-reassign
111
+ k = total;
112
+ }
113
+ const result = this.index.search(query, k);
114
+ return result.labels.map((id, index) => {
115
+ const uuid = this._mapping[id];
116
+ return [this.docstore.search(uuid), result.distances[index]];
117
+ });
118
+ }
119
+ async save(directory) {
120
+ const fs = await import("node:fs/promises");
121
+ const path = await import("node:path");
122
+ await fs.mkdir(directory, { recursive: true });
123
+ await Promise.all([
124
+ this.index.write(path.join(directory, "faiss.index")),
125
+ await fs.writeFile(path.join(directory, "docstore.json"), JSON.stringify([
126
+ Array.from(this.docstore._docs.entries()),
127
+ this._mapping,
128
+ ])),
129
+ ]);
130
+ }
131
+ static async load(directory, embeddings) {
132
+ const fs = await import("node:fs/promises");
133
+ const path = await import("node:path");
134
+ const readStore = (directory) => fs
135
+ .readFile(path.join(directory, "docstore.json"), "utf8")
136
+ .then(JSON.parse);
137
+ const readIndex = async (directory) => {
138
+ const { IndexFlatL2 } = await this.importFaiss();
139
+ return IndexFlatL2.read(path.join(directory, "faiss.index"));
140
+ };
141
+ const [[docstoreFiles, mapping], index] = await Promise.all([
142
+ readStore(directory),
143
+ readIndex(directory),
144
+ ]);
145
+ const docstore = new index_js_1.InMemoryDocstore(new Map(docstoreFiles));
146
+ return new this(embeddings, { docstore, index, mapping });
147
+ }
148
+ static async loadFromPython(directory, embeddings) {
149
+ const fs = await import("node:fs/promises");
150
+ const path = await import("node:path");
151
+ const { Parser, NameRegistry } = await this.importPickleparser();
152
+ class PyDocument extends Map {
153
+ toDocument() {
154
+ return new document_js_1.Document({
155
+ pageContent: this.get("page_content"),
156
+ metadata: this.get("metadata"),
157
+ });
158
+ }
159
+ }
160
+ class PyInMemoryDocstore {
161
+ constructor() {
162
+ Object.defineProperty(this, "_dict", {
163
+ enumerable: true,
164
+ configurable: true,
165
+ writable: true,
166
+ value: void 0
167
+ });
168
+ }
169
+ toInMemoryDocstore() {
170
+ const s = new index_js_1.InMemoryDocstore();
171
+ for (const [key, value] of Object.entries(this._dict)) {
172
+ s._docs.set(key, value.toDocument());
173
+ }
174
+ return s;
175
+ }
176
+ }
177
+ const readStore = async (directory) => {
178
+ const pkl = await fs.readFile(path.join(directory, "index.pkl"), "binary");
179
+ const buffer = Buffer.from(pkl, "binary");
180
+ const registry = new NameRegistry()
181
+ .register("langchain.docstore.in_memory", "InMemoryDocstore", PyInMemoryDocstore)
182
+ .register("langchain.schema", "Document", PyDocument)
183
+ .register("pathlib", "WindowsPath", (...args) => args.join("\\"))
184
+ .register("pathlib", "PosixPath", (...args) => args.join("/"));
185
+ const pickleparser = new Parser({
186
+ nameResolver: registry,
187
+ });
188
+ const [rawStore, mapping] = pickleparser.parse(buffer);
189
+ const store = rawStore.toInMemoryDocstore();
190
+ return { store, mapping };
191
+ };
192
+ const readIndex = async (directory) => {
193
+ const { IndexFlatL2 } = await this.importFaiss();
194
+ return IndexFlatL2.read(path.join(directory, "index.faiss"));
195
+ };
196
+ const [store, index] = await Promise.all([
197
+ readStore(directory),
198
+ readIndex(directory),
199
+ ]);
200
+ return new this(embeddings, {
201
+ docstore: store.store,
202
+ index,
203
+ mapping: store.mapping,
204
+ });
205
+ }
206
+ static async fromTexts(texts, metadatas, embeddings, dbConfig) {
207
+ const docs = [];
208
+ for (let i = 0; i < texts.length; i += 1) {
209
+ const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;
210
+ const newDoc = new document_js_1.Document({
211
+ pageContent: texts[i],
212
+ metadata,
213
+ });
214
+ docs.push(newDoc);
215
+ }
216
+ return this.fromDocuments(docs, embeddings, dbConfig);
217
+ }
218
+ static async fromDocuments(docs, embeddings, dbConfig) {
219
+ const args = {
220
+ docstore: dbConfig?.docstore,
221
+ };
222
+ const instance = new this(embeddings, args);
223
+ await instance.addDocuments(docs);
224
+ return instance;
225
+ }
226
+ static async importFaiss() {
227
+ try {
228
+ const { default: { IndexFlatL2 }, } = await import("faiss-node");
229
+ return { IndexFlatL2 };
230
+ }
231
+ catch (err) {
232
+ throw new Error("Please install faiss-node as a dependency with, e.g. `npm install -S faiss-node`");
233
+ }
234
+ }
235
+ static async importPickleparser() {
236
+ try {
237
+ const { default: { Parser, NameRegistry }, } = await import("pickleparser");
238
+ return { Parser, NameRegistry };
239
+ }
240
+ catch (err) {
241
+ throw new Error("Please install pickleparser as a dependency with, e.g. `npm install -S pickleparser`");
242
+ }
243
+ }
244
+ }
245
+ exports.FaissStore = FaissStore;
@@ -0,0 +1,39 @@
1
+ import type { IndexFlatL2 } from "faiss-node";
2
+ import type { NameRegistry, Parser } from "pickleparser";
3
+ import { Embeddings } from "../embeddings/base.js";
4
+ import { SaveableVectorStore } from "./base.js";
5
+ import { Document } from "../document.js";
6
+ import { InMemoryDocstore } from "../docstore/index.js";
7
+ export interface FaissLibArgs {
8
+ docstore?: InMemoryDocstore;
9
+ index?: IndexFlatL2;
10
+ mapping?: Record<number, string>;
11
+ }
12
+ export declare class FaissStore extends SaveableVectorStore {
13
+ _index?: IndexFlatL2;
14
+ _mapping: Record<number, string>;
15
+ docstore: InMemoryDocstore;
16
+ args: FaissLibArgs;
17
+ constructor(embeddings: Embeddings, args: FaissLibArgs);
18
+ addDocuments(documents: Document[]): Promise<void>;
19
+ get index(): IndexFlatL2;
20
+ private set index(value);
21
+ addVectors(vectors: number[][], documents: Document[]): Promise<void>;
22
+ similaritySearchVectorWithScore(query: number[], k: number): Promise<[Document<Record<string, any>>, number][]>;
23
+ save(directory: string): Promise<void>;
24
+ static load(directory: string, embeddings: Embeddings): Promise<FaissStore>;
25
+ static loadFromPython(directory: string, embeddings: Embeddings): Promise<FaissStore>;
26
+ static fromTexts(texts: string[], metadatas: object[] | object, embeddings: Embeddings, dbConfig?: {
27
+ docstore?: InMemoryDocstore;
28
+ }): Promise<FaissStore>;
29
+ static fromDocuments(docs: Document[], embeddings: Embeddings, dbConfig?: {
30
+ docstore?: InMemoryDocstore;
31
+ }): Promise<FaissStore>;
32
+ static importFaiss(): Promise<{
33
+ IndexFlatL2: typeof IndexFlatL2;
34
+ }>;
35
+ static importPickleparser(): Promise<{
36
+ Parser: typeof Parser;
37
+ NameRegistry: typeof NameRegistry;
38
+ }>;
39
+ }
@@ -0,0 +1,218 @@
1
+ import * as uuid from "uuid";
2
+ import { SaveableVectorStore } from "./base.js";
3
+ import { Document } from "../document.js";
4
+ import { InMemoryDocstore } from "../docstore/index.js";
5
+ export class FaissStore extends SaveableVectorStore {
6
+ constructor(embeddings, args) {
7
+ super(embeddings, args);
8
+ Object.defineProperty(this, "_index", {
9
+ enumerable: true,
10
+ configurable: true,
11
+ writable: true,
12
+ value: void 0
13
+ });
14
+ Object.defineProperty(this, "_mapping", {
15
+ enumerable: true,
16
+ configurable: true,
17
+ writable: true,
18
+ value: void 0
19
+ });
20
+ Object.defineProperty(this, "docstore", {
21
+ enumerable: true,
22
+ configurable: true,
23
+ writable: true,
24
+ value: void 0
25
+ });
26
+ Object.defineProperty(this, "args", {
27
+ enumerable: true,
28
+ configurable: true,
29
+ writable: true,
30
+ value: void 0
31
+ });
32
+ this.args = args;
33
+ this._index = args.index;
34
+ this._mapping = args.mapping ?? {};
35
+ this.embeddings = embeddings;
36
+ this.docstore = args?.docstore ?? new InMemoryDocstore();
37
+ }
38
+ async addDocuments(documents) {
39
+ const texts = documents.map(({ pageContent }) => pageContent);
40
+ return this.addVectors(await this.embeddings.embedDocuments(texts), documents);
41
+ }
42
+ get index() {
43
+ if (!this._index) {
44
+ throw new Error("Vector store not initialised yet. Try calling `fromTexts` or `fromDocuments` first.");
45
+ }
46
+ return this._index;
47
+ }
48
+ set index(index) {
49
+ this._index = index;
50
+ }
51
+ async addVectors(vectors, documents) {
52
+ if (vectors.length === 0) {
53
+ return;
54
+ }
55
+ if (vectors.length !== documents.length) {
56
+ throw new Error(`Vectors and documents must have the same length`);
57
+ }
58
+ const dv = vectors[0].length;
59
+ if (!this._index) {
60
+ const { IndexFlatL2 } = await FaissStore.importFaiss();
61
+ this._index = new IndexFlatL2(dv);
62
+ }
63
+ const d = this.index.getDimension();
64
+ if (dv !== d) {
65
+ throw new Error(`Vectors must have the same length as the number of dimensions (${d})`);
66
+ }
67
+ const docstoreSize = this.docstore.count;
68
+ for (let i = 0; i < vectors.length; i += 1) {
69
+ const documentId = uuid.v4();
70
+ const id = docstoreSize + i;
71
+ this.index.add(vectors[i]);
72
+ this._mapping[id] = documentId;
73
+ this.docstore.add({ [documentId]: documents[i] });
74
+ }
75
+ }
76
+ async similaritySearchVectorWithScore(query, k) {
77
+ const d = this.index.getDimension();
78
+ if (query.length !== d) {
79
+ throw new Error(`Query vector must have the same length as the number of dimensions (${d})`);
80
+ }
81
+ if (k > this.index.ntotal()) {
82
+ const total = this.index.ntotal();
83
+ console.warn(`k (${k}) is greater than the number of elements in the index (${total}), setting k to ${total}`);
84
+ // eslint-disable-next-line no-param-reassign
85
+ k = total;
86
+ }
87
+ const result = this.index.search(query, k);
88
+ return result.labels.map((id, index) => {
89
+ const uuid = this._mapping[id];
90
+ return [this.docstore.search(uuid), result.distances[index]];
91
+ });
92
+ }
93
+ async save(directory) {
94
+ const fs = await import("node:fs/promises");
95
+ const path = await import("node:path");
96
+ await fs.mkdir(directory, { recursive: true });
97
+ await Promise.all([
98
+ this.index.write(path.join(directory, "faiss.index")),
99
+ await fs.writeFile(path.join(directory, "docstore.json"), JSON.stringify([
100
+ Array.from(this.docstore._docs.entries()),
101
+ this._mapping,
102
+ ])),
103
+ ]);
104
+ }
105
+ static async load(directory, embeddings) {
106
+ const fs = await import("node:fs/promises");
107
+ const path = await import("node:path");
108
+ const readStore = (directory) => fs
109
+ .readFile(path.join(directory, "docstore.json"), "utf8")
110
+ .then(JSON.parse);
111
+ const readIndex = async (directory) => {
112
+ const { IndexFlatL2 } = await this.importFaiss();
113
+ return IndexFlatL2.read(path.join(directory, "faiss.index"));
114
+ };
115
+ const [[docstoreFiles, mapping], index] = await Promise.all([
116
+ readStore(directory),
117
+ readIndex(directory),
118
+ ]);
119
+ const docstore = new InMemoryDocstore(new Map(docstoreFiles));
120
+ return new this(embeddings, { docstore, index, mapping });
121
+ }
122
+ static async loadFromPython(directory, embeddings) {
123
+ const fs = await import("node:fs/promises");
124
+ const path = await import("node:path");
125
+ const { Parser, NameRegistry } = await this.importPickleparser();
126
+ class PyDocument extends Map {
127
+ toDocument() {
128
+ return new Document({
129
+ pageContent: this.get("page_content"),
130
+ metadata: this.get("metadata"),
131
+ });
132
+ }
133
+ }
134
+ class PyInMemoryDocstore {
135
+ constructor() {
136
+ Object.defineProperty(this, "_dict", {
137
+ enumerable: true,
138
+ configurable: true,
139
+ writable: true,
140
+ value: void 0
141
+ });
142
+ }
143
+ toInMemoryDocstore() {
144
+ const s = new InMemoryDocstore();
145
+ for (const [key, value] of Object.entries(this._dict)) {
146
+ s._docs.set(key, value.toDocument());
147
+ }
148
+ return s;
149
+ }
150
+ }
151
+ const readStore = async (directory) => {
152
+ const pkl = await fs.readFile(path.join(directory, "index.pkl"), "binary");
153
+ const buffer = Buffer.from(pkl, "binary");
154
+ const registry = new NameRegistry()
155
+ .register("langchain.docstore.in_memory", "InMemoryDocstore", PyInMemoryDocstore)
156
+ .register("langchain.schema", "Document", PyDocument)
157
+ .register("pathlib", "WindowsPath", (...args) => args.join("\\"))
158
+ .register("pathlib", "PosixPath", (...args) => args.join("/"));
159
+ const pickleparser = new Parser({
160
+ nameResolver: registry,
161
+ });
162
+ const [rawStore, mapping] = pickleparser.parse(buffer);
163
+ const store = rawStore.toInMemoryDocstore();
164
+ return { store, mapping };
165
+ };
166
+ const readIndex = async (directory) => {
167
+ const { IndexFlatL2 } = await this.importFaiss();
168
+ return IndexFlatL2.read(path.join(directory, "index.faiss"));
169
+ };
170
+ const [store, index] = await Promise.all([
171
+ readStore(directory),
172
+ readIndex(directory),
173
+ ]);
174
+ return new this(embeddings, {
175
+ docstore: store.store,
176
+ index,
177
+ mapping: store.mapping,
178
+ });
179
+ }
180
+ static async fromTexts(texts, metadatas, embeddings, dbConfig) {
181
+ const docs = [];
182
+ for (let i = 0; i < texts.length; i += 1) {
183
+ const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;
184
+ const newDoc = new Document({
185
+ pageContent: texts[i],
186
+ metadata,
187
+ });
188
+ docs.push(newDoc);
189
+ }
190
+ return this.fromDocuments(docs, embeddings, dbConfig);
191
+ }
192
+ static async fromDocuments(docs, embeddings, dbConfig) {
193
+ const args = {
194
+ docstore: dbConfig?.docstore,
195
+ };
196
+ const instance = new this(embeddings, args);
197
+ await instance.addDocuments(docs);
198
+ return instance;
199
+ }
200
+ static async importFaiss() {
201
+ try {
202
+ const { default: { IndexFlatL2 }, } = await import("faiss-node");
203
+ return { IndexFlatL2 };
204
+ }
205
+ catch (err) {
206
+ throw new Error("Please install faiss-node as a dependency with, e.g. `npm install -S faiss-node`");
207
+ }
208
+ }
209
+ static async importPickleparser() {
210
+ try {
211
+ const { default: { Parser, NameRegistry }, } = await import("pickleparser");
212
+ return { Parser, NameRegistry };
213
+ }
214
+ catch (err) {
215
+ throw new Error("Please install pickleparser as a dependency with, e.g. `npm install -S pickleparser`");
216
+ }
217
+ }
218
+ }
@@ -0,0 +1 @@
1
+ module.exports = require('../dist/llms/sagemaker_endpoint.cjs');
@@ -0,0 +1 @@
1
+ export * from '../dist/llms/sagemaker_endpoint.js'
@@ -0,0 +1 @@
1
+ export * from '../dist/llms/sagemaker_endpoint.js'
@@ -0,0 +1 @@
1
+ module.exports = require('../dist/output_parsers/expression.cjs');
@@ -0,0 +1 @@
1
+ export * from '../dist/output_parsers/expression.js'
@@ -0,0 +1 @@
1
+ export * from '../dist/output_parsers/expression.js'