langchain 0.0.195 → 0.0.197-rc.0

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 (236) hide show
  1. package/LICENSE +21 -0
  2. package/dist/agents/openai/index.cjs +6 -2
  3. package/dist/agents/openai/index.js +6 -2
  4. package/dist/agents/toolkits/conversational_retrieval/token_buffer_memory.d.ts +1 -1
  5. package/dist/base_language/count_tokens.cjs +5 -70
  6. package/dist/base_language/count_tokens.d.ts +1 -10
  7. package/dist/base_language/count_tokens.js +1 -65
  8. package/dist/base_language/index.cjs +6 -196
  9. package/dist/base_language/index.d.ts +1 -111
  10. package/dist/base_language/index.js +1 -191
  11. package/dist/cache/base.cjs +15 -37
  12. package/dist/cache/base.d.ts +1 -20
  13. package/dist/cache/base.js +1 -33
  14. package/dist/cache/index.cjs +2 -46
  15. package/dist/cache/index.d.ts +1 -29
  16. package/dist/cache/index.js +1 -45
  17. package/dist/callbacks/base.cjs +3 -139
  18. package/dist/callbacks/base.d.ts +1 -266
  19. package/dist/callbacks/base.js +1 -126
  20. package/dist/callbacks/handlers/console.cjs +14 -221
  21. package/dist/callbacks/handlers/console.d.ts +1 -117
  22. package/dist/callbacks/handlers/console.js +1 -217
  23. package/dist/callbacks/handlers/initialize.cjs +15 -30
  24. package/dist/callbacks/handlers/initialize.d.ts +1 -16
  25. package/dist/callbacks/handlers/initialize.js +1 -27
  26. package/dist/callbacks/handlers/log_stream.cjs +15 -293
  27. package/dist/callbacks/handlers/log_stream.d.ts +1 -100
  28. package/dist/callbacks/handlers/log_stream.js +1 -289
  29. package/dist/callbacks/handlers/run_collector.cjs +15 -48
  30. package/dist/callbacks/handlers/run_collector.d.ts +1 -26
  31. package/dist/callbacks/handlers/run_collector.js +1 -46
  32. package/dist/callbacks/handlers/tracer.cjs +15 -375
  33. package/dist/callbacks/handlers/tracer.d.ts +1 -70
  34. package/dist/callbacks/handlers/tracer.js +1 -373
  35. package/dist/callbacks/handlers/tracer_langchain.cjs +15 -104
  36. package/dist/callbacks/handlers/tracer_langchain.d.ts +1 -41
  37. package/dist/callbacks/handlers/tracer_langchain.js +1 -102
  38. package/dist/callbacks/handlers/tracer_langchain_v1.cjs +15 -197
  39. package/dist/callbacks/handlers/tracer_langchain_v1.d.ts +1 -57
  40. package/dist/callbacks/handlers/tracer_langchain_v1.js +1 -195
  41. package/dist/callbacks/manager.cjs +15 -676
  42. package/dist/callbacks/manager.d.ts +1 -180
  43. package/dist/callbacks/manager.js +1 -666
  44. package/dist/callbacks/promises.cjs +14 -42
  45. package/dist/callbacks/promises.d.ts +1 -11
  46. package/dist/callbacks/promises.js +1 -37
  47. package/dist/chains/graph_qa/prompts.d.ts +1 -1
  48. package/dist/chains/openai_functions/structured_output.cjs +2 -2
  49. package/dist/chains/openai_functions/structured_output.d.ts +1 -1
  50. package/dist/chains/openai_functions/structured_output.js +1 -1
  51. package/dist/chat_models/anthropic.cjs +15 -348
  52. package/dist/chat_models/anthropic.d.ts +1 -156
  53. package/dist/chat_models/anthropic.js +1 -346
  54. package/dist/chat_models/baiduwenxin.d.ts +1 -1
  55. package/dist/chat_models/base.cjs +15 -296
  56. package/dist/chat_models/base.d.ts +1 -122
  57. package/dist/chat_models/base.js +1 -292
  58. package/dist/chat_models/bedrock/web.cjs +21 -1
  59. package/dist/chat_models/bedrock/web.d.ts +2 -2
  60. package/dist/chat_models/bedrock/web.js +21 -1
  61. package/dist/chat_models/fireworks.d.ts +1 -1
  62. package/dist/document.cjs +2 -24
  63. package/dist/document.d.ts +1 -12
  64. package/dist/document.js +1 -23
  65. package/dist/document_loaders/web/azure_blob_storage_file.d.ts +1 -1
  66. package/dist/document_loaders/web/github.cjs +105 -0
  67. package/dist/document_loaders/web/github.d.ts +26 -0
  68. package/dist/document_loaders/web/github.js +105 -0
  69. package/dist/document_loaders/web/s3.d.ts +1 -1
  70. package/dist/embeddings/base.cjs +15 -22
  71. package/dist/embeddings/base.d.ts +1 -33
  72. package/dist/embeddings/base.js +1 -20
  73. package/dist/embeddings/cache_backed.cjs +2 -2
  74. package/dist/embeddings/cache_backed.js +1 -1
  75. package/dist/evaluation/agents/trajectory.d.ts +1 -1
  76. package/dist/evaluation/criteria/prompt.d.ts +2 -2
  77. package/dist/evaluation/qa/prompt.d.ts +2 -2
  78. package/dist/experimental/hubs/makersuite/googlemakersuitehub.d.ts +1 -1
  79. package/dist/experimental/plan_and_execute/prompt.d.ts +1 -1
  80. package/dist/llms/base.cjs +15 -278
  81. package/dist/llms/base.d.ts +1 -115
  82. package/dist/llms/base.js +1 -275
  83. package/dist/llms/bedrock/web.cjs +21 -1
  84. package/dist/llms/bedrock/web.d.ts +2 -2
  85. package/dist/llms/bedrock/web.js +21 -1
  86. package/dist/llms/fireworks.d.ts +1 -1
  87. package/dist/load/import_map.cjs +2 -1
  88. package/dist/load/import_map.d.ts +1 -0
  89. package/dist/load/import_map.js +1 -0
  90. package/dist/load/index.cjs +7 -148
  91. package/dist/load/index.js +7 -148
  92. package/dist/load/map_keys.cjs +0 -24
  93. package/dist/load/map_keys.d.ts +0 -6
  94. package/dist/load/map_keys.js +1 -17
  95. package/dist/load/serializable.cjs +15 -178
  96. package/dist/load/serializable.d.ts +1 -66
  97. package/dist/load/serializable.js +1 -175
  98. package/dist/memory/base.cjs +17 -92
  99. package/dist/memory/base.d.ts +2 -68
  100. package/dist/memory/base.js +2 -87
  101. package/dist/output_parsers/list.cjs +4 -122
  102. package/dist/output_parsers/list.d.ts +1 -57
  103. package/dist/output_parsers/list.js +1 -119
  104. package/dist/output_parsers/openai_functions.cjs +2 -2
  105. package/dist/output_parsers/openai_functions.d.ts +1 -1
  106. package/dist/output_parsers/openai_functions.js +1 -1
  107. package/dist/output_parsers/regex.d.ts +1 -1
  108. package/dist/output_parsers/structured.d.ts +1 -1
  109. package/dist/prompts/base.cjs +8 -183
  110. package/dist/prompts/base.d.ts +3 -132
  111. package/dist/prompts/base.js +3 -178
  112. package/dist/prompts/chat.cjs +13 -477
  113. package/dist/prompts/chat.d.ts +2 -219
  114. package/dist/prompts/chat.js +2 -466
  115. package/dist/prompts/few_shot.cjs +3 -352
  116. package/dist/prompts/few_shot.d.ts +1 -192
  117. package/dist/prompts/few_shot.js +1 -350
  118. package/dist/prompts/index.cjs +3 -2
  119. package/dist/prompts/index.d.ts +2 -1
  120. package/dist/prompts/index.js +2 -1
  121. package/dist/prompts/pipeline.cjs +2 -141
  122. package/dist/prompts/pipeline.d.ts +1 -98
  123. package/dist/prompts/pipeline.js +1 -140
  124. package/dist/prompts/prompt.cjs +2 -145
  125. package/dist/prompts/prompt.d.ts +1 -92
  126. package/dist/prompts/prompt.js +1 -144
  127. package/dist/prompts/selectors/LengthBasedExampleSelector.cjs +2 -147
  128. package/dist/prompts/selectors/LengthBasedExampleSelector.d.ts +1 -89
  129. package/dist/prompts/selectors/LengthBasedExampleSelector.js +1 -146
  130. package/dist/prompts/selectors/SemanticSimilarityExampleSelector.cjs +15 -137
  131. package/dist/prompts/selectors/SemanticSimilarityExampleSelector.d.ts +1 -91
  132. package/dist/prompts/selectors/SemanticSimilarityExampleSelector.js +1 -135
  133. package/dist/prompts/selectors/conditional.cjs +5 -73
  134. package/dist/prompts/selectors/conditional.d.ts +1 -63
  135. package/dist/prompts/selectors/conditional.js +1 -69
  136. package/dist/prompts/serde.d.ts +1 -43
  137. package/dist/prompts/template.cjs +8 -88
  138. package/dist/prompts/template.d.ts +1 -36
  139. package/dist/prompts/template.js +1 -83
  140. package/dist/{util/@cfworker/json-schema → runnables}/index.cjs +1 -1
  141. package/dist/runnables/index.d.ts +1 -0
  142. package/dist/runnables/index.js +1 -0
  143. package/dist/schema/document.cjs +3 -34
  144. package/dist/schema/document.d.ts +2 -29
  145. package/dist/schema/document.js +2 -32
  146. package/dist/schema/index.cjs +37 -612
  147. package/dist/schema/index.d.ts +11 -311
  148. package/dist/schema/index.js +8 -583
  149. package/dist/schema/output_parser.cjs +15 -309
  150. package/dist/schema/output_parser.d.ts +1 -173
  151. package/dist/schema/output_parser.js +1 -301
  152. package/dist/schema/retriever.cjs +15 -77
  153. package/dist/schema/retriever.d.ts +1 -43
  154. package/dist/schema/retriever.js +1 -75
  155. package/dist/schema/runnable/base.cjs +10 -1072
  156. package/dist/schema/runnable/base.d.ts +1 -356
  157. package/dist/schema/runnable/base.js +1 -1060
  158. package/dist/schema/runnable/branch.cjs +2 -131
  159. package/dist/schema/runnable/branch.d.ts +1 -94
  160. package/dist/schema/runnable/branch.js +1 -130
  161. package/dist/schema/runnable/config.cjs +0 -6
  162. package/dist/schema/runnable/config.d.ts +1 -3
  163. package/dist/schema/runnable/config.js +1 -4
  164. package/dist/schema/runnable/index.cjs +15 -16
  165. package/dist/schema/runnable/index.d.ts +1 -5
  166. package/dist/schema/runnable/index.js +1 -4
  167. package/dist/schema/runnable/passthrough.cjs +3 -113
  168. package/dist/schema/runnable/passthrough.d.ts +1 -72
  169. package/dist/schema/runnable/passthrough.js +1 -111
  170. package/dist/schema/runnable/router.cjs +2 -71
  171. package/dist/schema/runnable/router.d.ts +1 -29
  172. package/dist/schema/runnable/router.js +1 -70
  173. package/dist/schema/storage.cjs +15 -8
  174. package/dist/schema/storage.d.ts +1 -57
  175. package/dist/schema/storage.js +1 -6
  176. package/dist/tools/bingserpapi.d.ts +1 -1
  177. package/dist/tools/searchapi.d.ts +1 -1
  178. package/dist/tools/serpapi.d.ts +1 -1
  179. package/dist/tools/serper.d.ts +1 -1
  180. package/dist/util/async_caller.cjs +14 -128
  181. package/dist/util/async_caller.d.ts +1 -45
  182. package/dist/util/async_caller.js +1 -124
  183. package/dist/vectorstores/momento_vector_index.cjs +39 -0
  184. package/dist/vectorstores/momento_vector_index.d.ts +17 -1
  185. package/dist/vectorstores/momento_vector_index.js +40 -1
  186. package/dist/vectorstores/mongodb_atlas.cjs +22 -2
  187. package/dist/vectorstores/mongodb_atlas.d.ts +13 -0
  188. package/dist/vectorstores/mongodb_atlas.js +22 -2
  189. package/package.json +18 -11
  190. package/runnables.cjs +1 -0
  191. package/runnables.d.ts +1 -0
  192. package/runnables.js +1 -0
  193. package/dist/util/@cfworker/json-schema/index.d.ts +0 -1
  194. package/dist/util/@cfworker/json-schema/index.js +0 -1
  195. package/dist/util/@cfworker/json-schema/src/deep-compare-strict.cjs +0 -43
  196. package/dist/util/@cfworker/json-schema/src/deep-compare-strict.d.ts +0 -1
  197. package/dist/util/@cfworker/json-schema/src/deep-compare-strict.js +0 -39
  198. package/dist/util/@cfworker/json-schema/src/dereference.cjs +0 -169
  199. package/dist/util/@cfworker/json-schema/src/dereference.d.ts +0 -12
  200. package/dist/util/@cfworker/json-schema/src/dereference.js +0 -165
  201. package/dist/util/@cfworker/json-schema/src/format.cjs +0 -139
  202. package/dist/util/@cfworker/json-schema/src/format.d.ts +0 -2
  203. package/dist/util/@cfworker/json-schema/src/format.js +0 -136
  204. package/dist/util/@cfworker/json-schema/src/index.cjs +0 -24
  205. package/dist/util/@cfworker/json-schema/src/index.d.ts +0 -8
  206. package/dist/util/@cfworker/json-schema/src/index.js +0 -8
  207. package/dist/util/@cfworker/json-schema/src/pointer.cjs +0 -11
  208. package/dist/util/@cfworker/json-schema/src/pointer.d.ts +0 -2
  209. package/dist/util/@cfworker/json-schema/src/pointer.js +0 -6
  210. package/dist/util/@cfworker/json-schema/src/types.cjs +0 -2
  211. package/dist/util/@cfworker/json-schema/src/types.d.ts +0 -72
  212. package/dist/util/@cfworker/json-schema/src/types.js +0 -1
  213. package/dist/util/@cfworker/json-schema/src/ucs2-length.cjs +0 -28
  214. package/dist/util/@cfworker/json-schema/src/ucs2-length.d.ts +0 -6
  215. package/dist/util/@cfworker/json-schema/src/ucs2-length.js +0 -24
  216. package/dist/util/@cfworker/json-schema/src/validate.cjs +0 -808
  217. package/dist/util/@cfworker/json-schema/src/validate.d.ts +0 -3
  218. package/dist/util/@cfworker/json-schema/src/validate.js +0 -804
  219. package/dist/util/@cfworker/json-schema/src/validator.cjs +0 -44
  220. package/dist/util/@cfworker/json-schema/src/validator.d.ts +0 -10
  221. package/dist/util/@cfworker/json-schema/src/validator.js +0 -40
  222. package/dist/util/fast-json-patch/index.cjs +0 -49
  223. package/dist/util/fast-json-patch/index.d.ts +0 -22
  224. package/dist/util/fast-json-patch/index.js +0 -16
  225. package/dist/util/fast-json-patch/src/core.cjs +0 -469
  226. package/dist/util/fast-json-patch/src/core.d.ts +0 -111
  227. package/dist/util/fast-json-patch/src/core.js +0 -459
  228. package/dist/util/fast-json-patch/src/duplex.cjs +0 -237
  229. package/dist/util/fast-json-patch/src/duplex.d.ts +0 -23
  230. package/dist/util/fast-json-patch/src/duplex.js +0 -230
  231. package/dist/util/fast-json-patch/src/helpers.cjs +0 -194
  232. package/dist/util/fast-json-patch/src/helpers.d.ts +0 -36
  233. package/dist/util/fast-json-patch/src/helpers.js +0 -181
  234. package/dist/util/js-sha1/hash.cjs +0 -358
  235. package/dist/util/js-sha1/hash.d.ts +0 -1
  236. package/dist/util/js-sha1/hash.js +0 -355
@@ -1,124 +1 @@
1
- import pRetry from "p-retry";
2
- import PQueueMod from "p-queue";
3
- const STATUS_NO_RETRY = [
4
- 400,
5
- 401,
6
- 402,
7
- 403,
8
- 404,
9
- 405,
10
- 406,
11
- 407,
12
- 408,
13
- 409, // Conflict
14
- ];
15
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
16
- const defaultFailedAttemptHandler = (error) => {
17
- if (error.message.startsWith("Cancel") ||
18
- error.message.startsWith("TimeoutError") ||
19
- error.name === "TimeoutError" ||
20
- error.message.startsWith("AbortError") ||
21
- error.name === "AbortError") {
22
- throw error;
23
- }
24
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
25
- if (error?.code === "ECONNABORTED") {
26
- throw error;
27
- }
28
- const status =
29
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
- error?.response?.status ?? error?.status;
31
- if (status && STATUS_NO_RETRY.includes(+status)) {
32
- throw error;
33
- }
34
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
35
- if (error?.error?.code === "insufficient_quota") {
36
- const err = new Error(error?.message);
37
- err.name = "InsufficientQuotaError";
38
- throw err;
39
- }
40
- };
41
- /**
42
- * A class that can be used to make async calls with concurrency and retry logic.
43
- *
44
- * This is useful for making calls to any kind of "expensive" external resource,
45
- * be it because it's rate-limited, subject to network issues, etc.
46
- *
47
- * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults
48
- * to `Infinity`. This means that by default, all calls will be made in parallel.
49
- *
50
- * Retries are limited by the `maxRetries` parameter, which defaults to 6. This
51
- * means that by default, each call will be retried up to 6 times, with an
52
- * exponential backoff between each attempt.
53
- */
54
- export class AsyncCaller {
55
- constructor(params) {
56
- Object.defineProperty(this, "maxConcurrency", {
57
- enumerable: true,
58
- configurable: true,
59
- writable: true,
60
- value: void 0
61
- });
62
- Object.defineProperty(this, "maxRetries", {
63
- enumerable: true,
64
- configurable: true,
65
- writable: true,
66
- value: void 0
67
- });
68
- Object.defineProperty(this, "onFailedAttempt", {
69
- enumerable: true,
70
- configurable: true,
71
- writable: true,
72
- value: void 0
73
- });
74
- Object.defineProperty(this, "queue", {
75
- enumerable: true,
76
- configurable: true,
77
- writable: true,
78
- value: void 0
79
- });
80
- this.maxConcurrency = params.maxConcurrency ?? Infinity;
81
- this.maxRetries = params.maxRetries ?? 6;
82
- this.onFailedAttempt =
83
- params.onFailedAttempt ?? defaultFailedAttemptHandler;
84
- const PQueue = "default" in PQueueMod ? PQueueMod.default : PQueueMod;
85
- this.queue = new PQueue({ concurrency: this.maxConcurrency });
86
- }
87
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
88
- call(callable, ...args) {
89
- return this.queue.add(() => pRetry(() => callable(...args).catch((error) => {
90
- // eslint-disable-next-line no-instanceof/no-instanceof
91
- if (error instanceof Error) {
92
- throw error;
93
- }
94
- else {
95
- throw new Error(error);
96
- }
97
- }), {
98
- onFailedAttempt: this.onFailedAttempt,
99
- retries: this.maxRetries,
100
- randomize: true,
101
- // If needed we can change some of the defaults here,
102
- // but they're quite sensible.
103
- }), { throwOnTimeout: true });
104
- }
105
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
106
- callWithOptions(options, callable, ...args) {
107
- // Note this doesn't cancel the underlying request,
108
- // when available prefer to use the signal option of the underlying call
109
- if (options.signal) {
110
- return Promise.race([
111
- this.call(callable, ...args),
112
- new Promise((_, reject) => {
113
- options.signal?.addEventListener("abort", () => {
114
- reject(new Error("AbortError"));
115
- });
116
- }),
117
- ]);
118
- }
119
- return this.call(callable, ...args);
120
- }
121
- fetch(...args) {
122
- return this.call(() => fetch(...args).then((res) => (res.ok ? res : Promise.reject(res))));
123
- }
124
- }
1
+ export * from "langchain-core/utils/async_caller";
@@ -30,6 +30,7 @@ const sdk_core_1 = require("@gomomento/sdk-core");
30
30
  const uuid = __importStar(require("uuid"));
31
31
  const document_js_1 = require("../document.cjs");
32
32
  const base_js_1 = require("./base.cjs");
33
+ const math_js_1 = require("../util/math.cjs");
33
34
  /**
34
35
  * A vector store that uses the Momento Vector Index.
35
36
  *
@@ -234,6 +235,44 @@ class MomentoVectorIndex extends base_js_1.VectorStore {
234
235
  throw new Error(`Unknown response type: ${response.toString()}`);
235
236
  }
236
237
  }
238
+ /**
239
+ * Return documents selected using the maximal marginal relevance.
240
+ * Maximal marginal relevance optimizes for similarity to the query AND diversity
241
+ * among selected documents.
242
+ *
243
+ * @param {string} query - Text to look up documents similar to.
244
+ * @param {number} options.k - Number of documents to return.
245
+ * @param {number} options.fetchK - Number of documents to fetch before passing to the MMR algorithm.
246
+ * @param {number} options.lambda - Number between 0 and 1 that determines the degree of diversity among the results,
247
+ * where 0 corresponds to maximum diversity and 1 to minimum diversity.
248
+ * @param {this["FilterType"]} options.filter - Optional filter
249
+ * @param _callbacks
250
+ *
251
+ * @returns {Promise<Document[]>} - List of documents selected by maximal marginal relevance.
252
+ */
253
+ async maxMarginalRelevanceSearch(query, options) {
254
+ const queryEmbedding = await this.embeddings.embedQuery(query);
255
+ const response = await this.client.searchAndFetchVectors(this.indexName, queryEmbedding, { topK: options.fetchK ?? 20, metadataFields: sdk_core_1.ALL_VECTOR_METADATA });
256
+ if (response instanceof sdk_core_1.VectorSearchAndFetchVectors.Success) {
257
+ const hits = response.hits();
258
+ // Gather the embeddings of the search results
259
+ const embeddingList = hits.map((hit) => hit.vector);
260
+ // Gather the ids of the most relevant results when applying MMR
261
+ const mmrIndexes = (0, math_js_1.maximalMarginalRelevance)(queryEmbedding, embeddingList, options.lambda, options.k);
262
+ const finalResult = mmrIndexes.map((index) => {
263
+ const hit = hits[index];
264
+ const { [this.textField]: pageContent, ...metadata } = hit.metadata;
265
+ return new document_js_1.Document({ metadata, pageContent: pageContent });
266
+ });
267
+ return finalResult;
268
+ }
269
+ else if (response instanceof sdk_core_1.VectorSearchAndFetchVectors.Error) {
270
+ throw new Error(response.toString());
271
+ }
272
+ else {
273
+ throw new Error(`Unknown response type: ${response.toString()}`);
274
+ }
275
+ }
237
276
  /**
238
277
  * Stores the documents in the index.
239
278
  *
@@ -1,7 +1,7 @@
1
1
  import { IVectorIndexClient } from "@gomomento/sdk-core";
2
2
  import { Document } from "../document.js";
3
3
  import { Embeddings } from "../embeddings/base.js";
4
- import { VectorStore } from "./base.js";
4
+ import { MaxMarginalRelevanceSearchOptions, VectorStore } from "./base.js";
5
5
  export interface DocumentProps {
6
6
  ids: string[];
7
7
  }
@@ -103,6 +103,22 @@ export declare class MomentoVectorIndex extends VectorStore {
103
103
  * to the query vector.
104
104
  */
105
105
  similaritySearchVectorWithScore(query: number[], k: number): Promise<[Document<Record<string, any>>, number][]>;
106
+ /**
107
+ * Return documents selected using the maximal marginal relevance.
108
+ * Maximal marginal relevance optimizes for similarity to the query AND diversity
109
+ * among selected documents.
110
+ *
111
+ * @param {string} query - Text to look up documents similar to.
112
+ * @param {number} options.k - Number of documents to return.
113
+ * @param {number} options.fetchK - Number of documents to fetch before passing to the MMR algorithm.
114
+ * @param {number} options.lambda - Number between 0 and 1 that determines the degree of diversity among the results,
115
+ * where 0 corresponds to maximum diversity and 1 to minimum diversity.
116
+ * @param {this["FilterType"]} options.filter - Optional filter
117
+ * @param _callbacks
118
+ *
119
+ * @returns {Promise<Document[]>} - List of documents selected by maximal marginal relevance.
120
+ */
121
+ maxMarginalRelevanceSearch(query: string, options: MaxMarginalRelevanceSearchOptions<this["FilterType"]>): Promise<Document[]>;
106
122
  /**
107
123
  * Stores the documents in the index.
108
124
  *
@@ -1,9 +1,10 @@
1
1
  /* eslint-disable no-instanceof/no-instanceof */
2
2
  /* eslint-disable @typescript-eslint/no-explicit-any */
3
- import { ALL_VECTOR_METADATA, CreateVectorIndex, VectorUpsertItemBatch, VectorDeleteItemBatch, VectorSearch, } from "@gomomento/sdk-core";
3
+ import { ALL_VECTOR_METADATA, CreateVectorIndex, VectorUpsertItemBatch, VectorDeleteItemBatch, VectorSearch, VectorSearchAndFetchVectors, } from "@gomomento/sdk-core";
4
4
  import * as uuid from "uuid";
5
5
  import { Document } from "../document.js";
6
6
  import { VectorStore } from "./base.js";
7
+ import { maximalMarginalRelevance } from "../util/math.js";
7
8
  /**
8
9
  * A vector store that uses the Momento Vector Index.
9
10
  *
@@ -208,6 +209,44 @@ export class MomentoVectorIndex extends VectorStore {
208
209
  throw new Error(`Unknown response type: ${response.toString()}`);
209
210
  }
210
211
  }
212
+ /**
213
+ * Return documents selected using the maximal marginal relevance.
214
+ * Maximal marginal relevance optimizes for similarity to the query AND diversity
215
+ * among selected documents.
216
+ *
217
+ * @param {string} query - Text to look up documents similar to.
218
+ * @param {number} options.k - Number of documents to return.
219
+ * @param {number} options.fetchK - Number of documents to fetch before passing to the MMR algorithm.
220
+ * @param {number} options.lambda - Number between 0 and 1 that determines the degree of diversity among the results,
221
+ * where 0 corresponds to maximum diversity and 1 to minimum diversity.
222
+ * @param {this["FilterType"]} options.filter - Optional filter
223
+ * @param _callbacks
224
+ *
225
+ * @returns {Promise<Document[]>} - List of documents selected by maximal marginal relevance.
226
+ */
227
+ async maxMarginalRelevanceSearch(query, options) {
228
+ const queryEmbedding = await this.embeddings.embedQuery(query);
229
+ const response = await this.client.searchAndFetchVectors(this.indexName, queryEmbedding, { topK: options.fetchK ?? 20, metadataFields: ALL_VECTOR_METADATA });
230
+ if (response instanceof VectorSearchAndFetchVectors.Success) {
231
+ const hits = response.hits();
232
+ // Gather the embeddings of the search results
233
+ const embeddingList = hits.map((hit) => hit.vector);
234
+ // Gather the ids of the most relevant results when applying MMR
235
+ const mmrIndexes = maximalMarginalRelevance(queryEmbedding, embeddingList, options.lambda, options.k);
236
+ const finalResult = mmrIndexes.map((index) => {
237
+ const hit = hits[index];
238
+ const { [this.textField]: pageContent, ...metadata } = hit.metadata;
239
+ return new Document({ metadata, pageContent: pageContent });
240
+ });
241
+ return finalResult;
242
+ }
243
+ else if (response instanceof VectorSearchAndFetchVectors.Error) {
244
+ throw new Error(response.toString());
245
+ }
246
+ else {
247
+ throw new Error(`Unknown response type: ${response.toString()}`);
248
+ }
249
+ }
211
250
  /**
212
251
  * Stores the documents in the index.
213
252
  *
@@ -99,7 +99,7 @@ class MongoDBAtlasVectorSearch extends base_js_1.VectorStore {
99
99
  const pipeline = [
100
100
  {
101
101
  $vectorSearch: {
102
- queryVector: query,
102
+ queryVector: MongoDBAtlasVectorSearch.fixArrayPrecision(query),
103
103
  index: this.indexName,
104
104
  path: this.embeddingKey,
105
105
  limit: k,
@@ -148,7 +148,7 @@ class MongoDBAtlasVectorSearch extends base_js_1.VectorStore {
148
148
  ...filter,
149
149
  includeEmbeddings: true,
150
150
  };
151
- const resultDocs = await this.similaritySearchVectorWithScore(queryEmbedding, fetchK, includeEmbeddingsFilter);
151
+ const resultDocs = await this.similaritySearchVectorWithScore(MongoDBAtlasVectorSearch.fixArrayPrecision(queryEmbedding), fetchK, includeEmbeddingsFilter);
152
152
  const embeddingList = resultDocs.map((doc) => doc[0].metadata[this.embeddingKey]);
153
153
  const mmrIndexes = (0, math_js_1.maximalMarginalRelevance)(queryEmbedding, embeddingList, lambda, k);
154
154
  return mmrIndexes.map((idx) => {
@@ -196,5 +196,25 @@ class MongoDBAtlasVectorSearch extends base_js_1.VectorStore {
196
196
  await instance.addDocuments(docs);
197
197
  return instance;
198
198
  }
199
+ /**
200
+ * Static method to fix the precision of the array that ensures that
201
+ * every number in this array is always float when casted to other types.
202
+ * This is needed since MongoDB Atlas Vector Search does not cast integer
203
+ * inside vector search to float automatically.
204
+ * This method shall introduce a hint of error but should be safe to use
205
+ * since introduced error is very small, only applies to integer numbers
206
+ * returned by embeddings, and most embeddings shall not have precision
207
+ * as high as 15 decimal places.
208
+ * @param array Array of number to be fixed.
209
+ * @returns
210
+ */
211
+ static fixArrayPrecision(array) {
212
+ return array.map((value) => {
213
+ if (Number.isInteger(value)) {
214
+ return value + 0.000000000000001;
215
+ }
216
+ return value;
217
+ });
218
+ }
199
219
  }
200
220
  exports.MongoDBAtlasVectorSearch = MongoDBAtlasVectorSearch;
@@ -101,5 +101,18 @@ export declare class MongoDBAtlasVectorSearch extends VectorStore {
101
101
  * @returns Promise that resolves to a new instance of MongoDBAtlasVectorSearch.
102
102
  */
103
103
  static fromDocuments(docs: Document[], embeddings: Embeddings, dbConfig: MongoDBAtlasVectorSearchLibArgs): Promise<MongoDBAtlasVectorSearch>;
104
+ /**
105
+ * Static method to fix the precision of the array that ensures that
106
+ * every number in this array is always float when casted to other types.
107
+ * This is needed since MongoDB Atlas Vector Search does not cast integer
108
+ * inside vector search to float automatically.
109
+ * This method shall introduce a hint of error but should be safe to use
110
+ * since introduced error is very small, only applies to integer numbers
111
+ * returned by embeddings, and most embeddings shall not have precision
112
+ * as high as 15 decimal places.
113
+ * @param array Array of number to be fixed.
114
+ * @returns
115
+ */
116
+ static fixArrayPrecision(array: number[]): number[];
104
117
  }
105
118
  export {};
@@ -96,7 +96,7 @@ export class MongoDBAtlasVectorSearch extends VectorStore {
96
96
  const pipeline = [
97
97
  {
98
98
  $vectorSearch: {
99
- queryVector: query,
99
+ queryVector: MongoDBAtlasVectorSearch.fixArrayPrecision(query),
100
100
  index: this.indexName,
101
101
  path: this.embeddingKey,
102
102
  limit: k,
@@ -145,7 +145,7 @@ export class MongoDBAtlasVectorSearch extends VectorStore {
145
145
  ...filter,
146
146
  includeEmbeddings: true,
147
147
  };
148
- const resultDocs = await this.similaritySearchVectorWithScore(queryEmbedding, fetchK, includeEmbeddingsFilter);
148
+ const resultDocs = await this.similaritySearchVectorWithScore(MongoDBAtlasVectorSearch.fixArrayPrecision(queryEmbedding), fetchK, includeEmbeddingsFilter);
149
149
  const embeddingList = resultDocs.map((doc) => doc[0].metadata[this.embeddingKey]);
150
150
  const mmrIndexes = maximalMarginalRelevance(queryEmbedding, embeddingList, lambda, k);
151
151
  return mmrIndexes.map((idx) => {
@@ -193,4 +193,24 @@ export class MongoDBAtlasVectorSearch extends VectorStore {
193
193
  await instance.addDocuments(docs);
194
194
  return instance;
195
195
  }
196
+ /**
197
+ * Static method to fix the precision of the array that ensures that
198
+ * every number in this array is always float when casted to other types.
199
+ * This is needed since MongoDB Atlas Vector Search does not cast integer
200
+ * inside vector search to float automatically.
201
+ * This method shall introduce a hint of error but should be safe to use
202
+ * since introduced error is very small, only applies to integer numbers
203
+ * returned by embeddings, and most embeddings shall not have precision
204
+ * as high as 15 decimal places.
205
+ * @param array Array of number to be fixed.
206
+ * @returns
207
+ */
208
+ static fixArrayPrecision(array) {
209
+ return array.map((value) => {
210
+ if (Number.isInteger(value)) {
211
+ return value + 0.000000000000001;
212
+ }
213
+ return value;
214
+ });
215
+ }
196
216
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "langchain",
3
- "version": "0.0.195",
3
+ "version": "0.0.197-rc.0",
4
4
  "description": "Typescript bindings for langchain",
5
5
  "type": "module",
6
6
  "engines": {
@@ -805,6 +805,9 @@
805
805
  "evaluation.cjs",
806
806
  "evaluation.js",
807
807
  "evaluation.d.ts",
808
+ "runnables.cjs",
809
+ "runnables.js",
810
+ "runnables.d.ts",
808
811
  "runnables/remote.cjs",
809
812
  "runnables/remote.js",
810
813
  "runnables/remote.d.ts",
@@ -856,12 +859,13 @@
856
859
  "@faker-js/faker": "^7.6.0",
857
860
  "@getmetal/metal-sdk": "^4.0.0",
858
861
  "@getzep/zep-js": "^0.9.0",
859
- "@gomomento/sdk": "^1.47.1",
860
- "@gomomento/sdk-core": "^1.47.1",
862
+ "@gomomento/sdk": "^1.51.1",
863
+ "@gomomento/sdk-core": "^1.51.1",
861
864
  "@google-ai/generativelanguage": "^0.2.1",
862
865
  "@google-cloud/storage": "^6.10.1",
863
866
  "@huggingface/inference": "^2.6.4",
864
867
  "@jest/globals": "^29.5.0",
868
+ "@langchain/anthropic": "workspace:*",
865
869
  "@mozilla/readability": "^0.4.4",
866
870
  "@notionhq/client": "^2.2.10",
867
871
  "@opensearch-project/opensearch": "^2.2.0",
@@ -939,6 +943,7 @@
939
943
  "jest": "^29.5.0",
940
944
  "jest-environment-node": "^29.6.4",
941
945
  "jsdom": "^22.1.0",
946
+ "langchain-core": "workspace:*",
942
947
  "llmonitor": "^0.5.9",
943
948
  "lodash": "^4.17.21",
944
949
  "mammoth": "^1.5.1",
@@ -993,9 +998,9 @@
993
998
  "@elastic/elasticsearch": "^8.4.0",
994
999
  "@getmetal/metal-sdk": "*",
995
1000
  "@getzep/zep-js": "^0.9.0",
996
- "@gomomento/sdk": "^1.47.1",
997
- "@gomomento/sdk-core": "^1.47.1",
998
- "@gomomento/sdk-web": "^1.47.1",
1001
+ "@gomomento/sdk": "^1.51.1",
1002
+ "@gomomento/sdk-core": "^1.51.1",
1003
+ "@gomomento/sdk-web": "^1.51.1",
999
1004
  "@google-ai/generativelanguage": "^0.2.1",
1000
1005
  "@google-cloud/storage": "^6.10.1",
1001
1006
  "@huggingface/inference": "^2.6.4",
@@ -1374,22 +1379,19 @@
1374
1379
  }
1375
1380
  },
1376
1381
  "dependencies": {
1377
- "@anthropic-ai/sdk": "^0.9.1",
1378
- "ansi-styles": "^5.0.0",
1382
+ "@langchain/anthropic": "^0.0.2",
1379
1383
  "binary-extensions": "^2.2.0",
1380
- "camelcase": "6",
1381
- "decamelize": "^1.2.0",
1382
1384
  "expr-eval": "^2.0.2",
1383
1385
  "flat": "^5.0.2",
1384
1386
  "js-tiktoken": "^1.0.7",
1385
1387
  "js-yaml": "^4.1.0",
1386
1388
  "jsonpointer": "^5.0.1",
1389
+ "langchain-core": "^0.0.4",
1387
1390
  "langchainhub": "~0.0.6",
1388
1391
  "langsmith": "~0.0.48",
1389
1392
  "ml-distance": "^4.0.0",
1390
1393
  "openai": "^4.19.0",
1391
1394
  "openapi-types": "^12.1.3",
1392
- "p-queue": "^6.6.2",
1393
1395
  "p-retry": "4",
1394
1396
  "uuid": "^9.0.0",
1395
1397
  "yaml": "^2.2.1",
@@ -2739,6 +2741,11 @@
2739
2741
  "import": "./evaluation.js",
2740
2742
  "require": "./evaluation.cjs"
2741
2743
  },
2744
+ "./runnables": {
2745
+ "types": "./runnables.d.ts",
2746
+ "import": "./runnables.js",
2747
+ "require": "./runnables.cjs"
2748
+ },
2742
2749
  "./runnables/remote": {
2743
2750
  "types": "./runnables/remote.d.ts",
2744
2751
  "import": "./runnables/remote.js",
package/runnables.cjs ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('./dist/runnables/index.cjs');
package/runnables.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/runnables/index.js'
package/runnables.js ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/runnables/index.js'
@@ -1 +0,0 @@
1
- export * from "./src/index.js";
@@ -1 +0,0 @@
1
- export * from "./src/index.js";
@@ -1,43 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.deepCompareStrict = void 0;
4
- function deepCompareStrict(a, b) {
5
- const typeofa = typeof a;
6
- if (typeofa !== typeof b) {
7
- return false;
8
- }
9
- if (Array.isArray(a)) {
10
- if (!Array.isArray(b)) {
11
- return false;
12
- }
13
- const length = a.length;
14
- if (length !== b.length) {
15
- return false;
16
- }
17
- for (let i = 0; i < length; i++) {
18
- if (!deepCompareStrict(a[i], b[i])) {
19
- return false;
20
- }
21
- }
22
- return true;
23
- }
24
- if (typeofa === "object") {
25
- if (!a || !b) {
26
- return a === b;
27
- }
28
- const aKeys = Object.keys(a);
29
- const bKeys = Object.keys(b);
30
- const length = aKeys.length;
31
- if (length !== bKeys.length) {
32
- return false;
33
- }
34
- for (const k of aKeys) {
35
- if (!deepCompareStrict(a[k], b[k])) {
36
- return false;
37
- }
38
- }
39
- return true;
40
- }
41
- return a === b;
42
- }
43
- exports.deepCompareStrict = deepCompareStrict;
@@ -1 +0,0 @@
1
- export declare function deepCompareStrict(a: any, b: any): boolean;
@@ -1,39 +0,0 @@
1
- export function deepCompareStrict(a, b) {
2
- const typeofa = typeof a;
3
- if (typeofa !== typeof b) {
4
- return false;
5
- }
6
- if (Array.isArray(a)) {
7
- if (!Array.isArray(b)) {
8
- return false;
9
- }
10
- const length = a.length;
11
- if (length !== b.length) {
12
- return false;
13
- }
14
- for (let i = 0; i < length; i++) {
15
- if (!deepCompareStrict(a[i], b[i])) {
16
- return false;
17
- }
18
- }
19
- return true;
20
- }
21
- if (typeofa === "object") {
22
- if (!a || !b) {
23
- return a === b;
24
- }
25
- const aKeys = Object.keys(a);
26
- const bKeys = Object.keys(b);
27
- const length = aKeys.length;
28
- if (length !== bKeys.length) {
29
- return false;
30
- }
31
- for (const k of aKeys) {
32
- if (!deepCompareStrict(a[k], b[k])) {
33
- return false;
34
- }
35
- }
36
- return true;
37
- }
38
- return a === b;
39
- }