langchain 0.0.146 → 0.0.148

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 (168) hide show
  1. package/chat_models/googlevertexai/web.cjs +1 -0
  2. package/chat_models/googlevertexai/web.d.ts +1 -0
  3. package/chat_models/googlevertexai/web.js +1 -0
  4. package/chat_models/googlevertexai.cjs +1 -1
  5. package/chat_models/googlevertexai.d.ts +1 -1
  6. package/chat_models/googlevertexai.js +1 -1
  7. package/dist/base_language/index.cjs +2 -2
  8. package/dist/base_language/index.d.ts +2 -1
  9. package/dist/base_language/index.js +1 -1
  10. package/dist/chains/base.d.ts +1 -1
  11. package/dist/chains/constitutional_ai/constitutional_principle.cjs +272 -1
  12. package/dist/chains/constitutional_ai/constitutional_principle.js +272 -1
  13. package/dist/chains/openai_functions/openapi.cjs +32 -27
  14. package/dist/chains/openai_functions/openapi.d.ts +9 -0
  15. package/dist/chains/openai_functions/openapi.js +31 -27
  16. package/dist/chat_models/base.d.ts +1 -1
  17. package/dist/chat_models/{googlevertexai.cjs → googlevertexai/common.cjs} +14 -26
  18. package/dist/chat_models/{googlevertexai.d.ts → googlevertexai/common.d.ts} +13 -22
  19. package/dist/chat_models/{googlevertexai.js → googlevertexai/common.js} +12 -24
  20. package/dist/chat_models/googlevertexai/index.cjs +36 -0
  21. package/dist/chat_models/googlevertexai/index.d.ts +21 -0
  22. package/dist/chat_models/googlevertexai/index.js +31 -0
  23. package/dist/chat_models/googlevertexai/web.cjs +33 -0
  24. package/dist/chat_models/googlevertexai/web.d.ts +19 -0
  25. package/dist/chat_models/googlevertexai/web.js +28 -0
  26. package/dist/chat_models/openai.cjs +1 -1
  27. package/dist/chat_models/openai.js +1 -1
  28. package/dist/document_loaders/web/notionapi.cjs +93 -70
  29. package/dist/document_loaders/web/notionapi.d.ts +33 -1
  30. package/dist/document_loaders/web/notionapi.js +89 -71
  31. package/dist/embeddings/googlevertexai.cjs +5 -1
  32. package/dist/embeddings/googlevertexai.d.ts +2 -1
  33. package/dist/embeddings/googlevertexai.js +5 -1
  34. package/dist/evaluation/agents/index.cjs +17 -0
  35. package/dist/evaluation/agents/index.d.ts +1 -0
  36. package/dist/evaluation/agents/index.js +1 -0
  37. package/dist/evaluation/agents/prompt.cjs +132 -0
  38. package/dist/evaluation/agents/prompt.d.ts +6 -0
  39. package/dist/evaluation/agents/prompt.js +129 -0
  40. package/dist/evaluation/agents/trajectory.cjs +189 -0
  41. package/dist/evaluation/agents/trajectory.d.ts +54 -0
  42. package/dist/evaluation/agents/trajectory.js +184 -0
  43. package/dist/evaluation/base.cjs +274 -0
  44. package/dist/evaluation/base.d.ts +232 -0
  45. package/dist/evaluation/base.js +263 -0
  46. package/dist/evaluation/comparison/index.cjs +17 -0
  47. package/dist/evaluation/comparison/index.d.ts +1 -0
  48. package/dist/evaluation/comparison/index.js +1 -0
  49. package/dist/evaluation/comparison/pairwise.cjs +244 -0
  50. package/dist/evaluation/comparison/pairwise.d.ts +50 -0
  51. package/dist/evaluation/comparison/pairwise.js +238 -0
  52. package/dist/evaluation/comparison/prompt.cjs +74 -0
  53. package/dist/evaluation/comparison/prompt.d.ts +21 -0
  54. package/dist/evaluation/comparison/prompt.js +71 -0
  55. package/dist/evaluation/criteria/criteria.cjs +259 -0
  56. package/dist/evaluation/criteria/criteria.d.ts +73 -0
  57. package/dist/evaluation/criteria/criteria.js +253 -0
  58. package/dist/evaluation/criteria/index.cjs +17 -0
  59. package/dist/evaluation/criteria/index.d.ts +1 -0
  60. package/dist/evaluation/criteria/index.js +1 -0
  61. package/dist/evaluation/criteria/prompt.cjs +36 -0
  62. package/dist/evaluation/criteria/prompt.d.ts +12 -0
  63. package/dist/evaluation/criteria/prompt.js +33 -0
  64. package/dist/evaluation/embedding_distance/base.cjs +163 -0
  65. package/dist/evaluation/embedding_distance/base.d.ts +78 -0
  66. package/dist/evaluation/embedding_distance/base.js +156 -0
  67. package/dist/evaluation/embedding_distance/index.cjs +17 -0
  68. package/dist/evaluation/embedding_distance/index.d.ts +1 -0
  69. package/dist/evaluation/embedding_distance/index.js +1 -0
  70. package/dist/evaluation/index.cjs +6 -0
  71. package/dist/evaluation/index.d.ts +6 -0
  72. package/dist/evaluation/index.js +6 -0
  73. package/dist/evaluation/loader.cjs +60 -0
  74. package/dist/evaluation/loader.d.ts +27 -0
  75. package/dist/evaluation/loader.js +56 -0
  76. package/dist/evaluation/types.cjs +2 -0
  77. package/dist/evaluation/types.d.ts +35 -0
  78. package/dist/evaluation/types.js +1 -0
  79. package/dist/experimental/llms/bittensor.cjs +141 -0
  80. package/dist/experimental/llms/bittensor.d.ts +33 -0
  81. package/dist/experimental/llms/bittensor.js +137 -0
  82. package/dist/experimental/multimodal_embeddings/googlevertexai.cjs +5 -1
  83. package/dist/experimental/multimodal_embeddings/googlevertexai.d.ts +2 -1
  84. package/dist/experimental/multimodal_embeddings/googlevertexai.js +5 -1
  85. package/dist/hub.d.ts +1 -1
  86. package/dist/llms/base.d.ts +1 -1
  87. package/dist/llms/{googlevertexai.js → googlevertexai/common.cjs} +21 -17
  88. package/dist/llms/{googlevertexai.d.ts → googlevertexai/common.d.ts} +13 -23
  89. package/dist/llms/{googlevertexai.cjs → googlevertexai/common.js} +17 -21
  90. package/dist/llms/googlevertexai/index.cjs +34 -0
  91. package/dist/llms/googlevertexai/index.d.ts +26 -0
  92. package/dist/llms/googlevertexai/index.js +30 -0
  93. package/dist/llms/googlevertexai/web.cjs +31 -0
  94. package/dist/llms/googlevertexai/web.d.ts +24 -0
  95. package/dist/llms/googlevertexai/web.js +27 -0
  96. package/dist/llms/openai-chat.cjs +1 -1
  97. package/dist/llms/openai-chat.js +1 -1
  98. package/dist/llms/openai.cjs +1 -1
  99. package/dist/llms/openai.js +1 -1
  100. package/dist/load/import_constants.cjs +3 -0
  101. package/dist/load/import_constants.js +3 -0
  102. package/dist/load/import_map.cjs +3 -2
  103. package/dist/load/import_map.d.ts +2 -1
  104. package/dist/load/import_map.js +2 -1
  105. package/dist/load/index.cjs +2 -1
  106. package/dist/load/index.js +2 -1
  107. package/dist/load/serializable.cjs +23 -4
  108. package/dist/load/serializable.js +23 -4
  109. package/dist/prompts/base.cjs +2 -2
  110. package/dist/prompts/base.d.ts +1 -1
  111. package/dist/prompts/base.js +1 -1
  112. package/dist/prompts/chat.cjs +2 -2
  113. package/dist/prompts/chat.d.ts +1 -1
  114. package/dist/prompts/chat.js +1 -1
  115. package/dist/retrievers/multi_query.cjs +140 -0
  116. package/dist/retrievers/multi_query.d.ts +33 -0
  117. package/dist/retrievers/multi_query.js +136 -0
  118. package/dist/schema/document.cjs +2 -2
  119. package/dist/schema/document.d.ts +1 -1
  120. package/dist/schema/document.js +1 -1
  121. package/dist/schema/output_parser.cjs +2 -2
  122. package/dist/schema/output_parser.d.ts +2 -1
  123. package/dist/schema/output_parser.js +1 -1
  124. package/dist/schema/retriever.cjs +2 -2
  125. package/dist/schema/retriever.d.ts +2 -1
  126. package/dist/schema/retriever.js +1 -1
  127. package/dist/schema/runnable/config.cjs +8 -0
  128. package/dist/schema/runnable/config.d.ts +3 -0
  129. package/dist/schema/runnable/config.js +4 -0
  130. package/dist/schema/{runnable.cjs → runnable/index.cjs} +290 -101
  131. package/dist/schema/{runnable.d.ts → runnable/index.d.ts} +127 -41
  132. package/dist/schema/{runnable.js → runnable/index.js} +284 -99
  133. package/dist/tools/base.d.ts +1 -1
  134. package/dist/types/googlevertexai-types.d.ts +11 -4
  135. package/dist/util/async_caller.cjs +35 -25
  136. package/dist/util/async_caller.d.ts +8 -0
  137. package/dist/util/async_caller.js +35 -25
  138. package/dist/util/googlevertexai-connection.cjs +14 -15
  139. package/dist/util/googlevertexai-connection.d.ts +7 -7
  140. package/dist/util/googlevertexai-connection.js +14 -15
  141. package/dist/util/googlevertexai-webauth.cjs +56 -0
  142. package/dist/util/googlevertexai-webauth.d.ts +25 -0
  143. package/dist/util/googlevertexai-webauth.js +52 -0
  144. package/dist/vectorstores/googlevertexai.cjs +9 -8
  145. package/dist/vectorstores/googlevertexai.d.ts +8 -7
  146. package/dist/vectorstores/googlevertexai.js +9 -8
  147. package/dist/vectorstores/pinecone.cjs +30 -22
  148. package/dist/vectorstores/pinecone.d.ts +3 -1
  149. package/dist/vectorstores/pinecone.js +30 -22
  150. package/dist/vectorstores/vectara.cjs +20 -23
  151. package/dist/vectorstores/vectara.d.ts +9 -2
  152. package/dist/vectorstores/vectara.js +20 -23
  153. package/experimental/llms/bittensor.cjs +1 -0
  154. package/experimental/llms/bittensor.d.ts +1 -0
  155. package/experimental/llms/bittensor.js +1 -0
  156. package/llms/googlevertexai/web.cjs +1 -0
  157. package/llms/googlevertexai/web.d.ts +1 -0
  158. package/llms/googlevertexai/web.js +1 -0
  159. package/llms/googlevertexai.cjs +1 -1
  160. package/llms/googlevertexai.d.ts +1 -1
  161. package/llms/googlevertexai.js +1 -1
  162. package/package.json +40 -3
  163. package/retrievers/multi_query.cjs +1 -0
  164. package/retrievers/multi_query.d.ts +1 -0
  165. package/retrievers/multi_query.js +1 -0
  166. package/schema/runnable.cjs +1 -1
  167. package/schema/runnable.d.ts +1 -1
  168. package/schema/runnable.js +1 -1
@@ -1,9 +1,15 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RunnableWithFallbacks = exports.RouterRunnable = exports.RunnableBinding = exports.RunnablePassthrough = exports.RunnableLambda = exports.RunnableMap = exports.RunnableSequence = exports.Runnable = void 0;
4
- const manager_js_1 = require("../callbacks/manager.cjs");
5
- const serializable_js_1 = require("../load/serializable.cjs");
6
- const stream_js_1 = require("../util/stream.cjs");
6
+ exports.RunnableWithFallbacks = exports.RouterRunnable = exports.RunnablePassthrough = exports.RunnableLambda = exports.RunnableMap = exports.RunnableSequence = exports.RunnableRetry = exports.RunnableBinding = exports.Runnable = void 0;
7
+ const p_retry_1 = __importDefault(require("p-retry"));
8
+ const manager_js_1 = require("../../callbacks/manager.cjs");
9
+ const serializable_js_1 = require("../../load/serializable.cjs");
10
+ const stream_js_1 = require("../../util/stream.cjs");
11
+ const config_js_1 = require("./config.cjs");
12
+ const async_caller_js_1 = require("../../util/async_caller.cjs");
7
13
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
8
14
  function _coerceToDict(value, defaultKey) {
9
15
  return value && !Array.isArray(value) && typeof value === "object"
@@ -33,6 +39,20 @@ class Runnable extends serializable_js_1.Serializable {
33
39
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
34
40
  return new RunnableBinding({ bound: this, kwargs });
35
41
  }
42
+ /**
43
+ * Bind arguments to a Runnable, returning a new Runnable.
44
+ * @param kwargs
45
+ * @returns A new RunnableBinding that, when invoked, will apply the bound args.
46
+ */
47
+ withRetry(fields) {
48
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
49
+ return new RunnableRetry({
50
+ bound: this,
51
+ kwargs: {},
52
+ maxAttemptNumber: fields?.stopAfterAttempt,
53
+ ...fields,
54
+ });
55
+ }
36
56
  /**
37
57
  * Create a new runnable from the current one that will try invoking
38
58
  * other passed fallback runnables if the initial invocation fails.
@@ -55,28 +75,27 @@ class Runnable extends serializable_js_1.Serializable {
55
75
  }
56
76
  return Array.from({ length }, () => options);
57
77
  }
58
- /**
59
- * Default implementation of batch, which calls invoke N times.
60
- * Subclasses should override this method if they can batch more efficiently.
61
- * @param inputs Array of inputs to each batch call.
62
- * @param options Either a single call options object to apply to each batch call or an array for each call.
63
- * @param batchOptions.maxConcurrency Maximum number of calls to run at once.
64
- * @returns An array of RunOutputs
65
- */
66
78
  async batch(inputs, options, batchOptions) {
67
79
  const configList = this._getOptionsList(options ?? {}, inputs.length);
68
- const batchSize = batchOptions?.maxConcurrency && batchOptions.maxConcurrency > 0
69
- ? batchOptions?.maxConcurrency
70
- : inputs.length;
71
- const batchResults = [];
72
- for (let i = 0; i < inputs.length; i += batchSize) {
73
- const batchPromises = inputs
74
- .slice(i, i + batchSize)
75
- .map((input, j) => this.invoke(input, configList[j]));
76
- const batchResult = await Promise.all(batchPromises);
77
- batchResults.push(batchResult);
78
- }
79
- return batchResults.flat();
80
+ const caller = new async_caller_js_1.AsyncCaller({
81
+ maxConcurrency: batchOptions?.maxConcurrency,
82
+ onFailedAttempt: (e) => {
83
+ throw e;
84
+ },
85
+ });
86
+ const batchCalls = inputs.map((input, i) => caller.call(async () => {
87
+ try {
88
+ const result = await this.invoke(input, configList[i]);
89
+ return result;
90
+ }
91
+ catch (e) {
92
+ if (batchOptions?.returnExceptions) {
93
+ return e;
94
+ }
95
+ throw e;
96
+ }
97
+ }));
98
+ return Promise.all(batchCalls);
80
99
  }
81
100
  /**
82
101
  * Default streaming implementation.
@@ -109,11 +128,11 @@ class Runnable extends serializable_js_1.Serializable {
109
128
  return [runnableConfig, callOptions];
110
129
  }
111
130
  async _callWithConfig(func, input, options) {
112
- const callbackManager_ = await manager_js_1.CallbackManager.configure(options?.callbacks, undefined, options?.tags, undefined, options?.metadata);
131
+ const callbackManager_ = await (0, config_js_1.getCallbackMangerForConfig)(options);
113
132
  const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), undefined, options?.runType);
114
133
  let output;
115
134
  try {
116
- output = await func.bind(this)(input);
135
+ output = await func.bind(this)(input, options, runManager);
117
136
  }
118
137
  catch (e) {
119
138
  await runManager?.handleChainError(e);
@@ -122,6 +141,30 @@ class Runnable extends serializable_js_1.Serializable {
122
141
  await runManager?.handleChainEnd(_coerceToDict(output, "output"));
123
142
  return output;
124
143
  }
144
+ /**
145
+ * Internal method that handles batching and configuration for a runnable
146
+ * It takes a function, input values, and optional configuration, and
147
+ * returns a promise that resolves to the output values.
148
+ * @param func The function to be executed for each input value.
149
+ * @param input The input values to be processed.
150
+ * @param config Optional configuration for the function execution.
151
+ * @returns A promise that resolves to the output values.
152
+ */
153
+ async _batchWithConfig(func, inputs, options, batchOptions) {
154
+ const configs = this._getOptionsList((options ?? {}), inputs.length);
155
+ const callbackManagers = await Promise.all(configs.map(config_js_1.getCallbackMangerForConfig));
156
+ const runManagers = await Promise.all(callbackManagers.map((callbackManager, i) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"))));
157
+ let outputs;
158
+ try {
159
+ outputs = await func(inputs, configs, runManagers, batchOptions);
160
+ }
161
+ catch (e) {
162
+ await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e)));
163
+ throw e;
164
+ }
165
+ await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict(outputs, "output"))));
166
+ return outputs;
167
+ }
125
168
  /**
126
169
  * Helper method to transform an Iterator of Input values into an Iterator of
127
170
  * Output values, with callbacks.
@@ -132,7 +175,7 @@ class Runnable extends serializable_js_1.Serializable {
132
175
  let finalInputSupported = true;
133
176
  let finalOutput;
134
177
  let finalOutputSupported = true;
135
- const callbackManager_ = await manager_js_1.CallbackManager.configure(options?.callbacks, undefined, options?.tags, undefined, options?.metadata);
178
+ const callbackManager_ = await (0, config_js_1.getCallbackMangerForConfig)(options);
136
179
  let runManager;
137
180
  const serializedRepresentation = this.toJSON();
138
181
  async function* wrapInputForTracing() {
@@ -206,12 +249,215 @@ class Runnable extends serializable_js_1.Serializable {
206
249
  last: _coerceToRunnable(coerceable),
207
250
  });
208
251
  }
252
+ /**
253
+ * Default implementation of transform, which buffers input and then calls stream.
254
+ * Subclasses should override this method if they can start producing output while
255
+ * input is still being generated.
256
+ * @param generator
257
+ * @param options
258
+ */
259
+ async *transform(generator, options) {
260
+ let finalChunk;
261
+ for await (const chunk of generator) {
262
+ if (!finalChunk) {
263
+ finalChunk = chunk;
264
+ }
265
+ else {
266
+ // Make a best effort to gather, for any type that supports concat.
267
+ // This method should throw an error if gathering fails.
268
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
269
+ finalChunk = finalChunk.concat(chunk);
270
+ }
271
+ }
272
+ yield* this._streamIterator(finalChunk, options);
273
+ }
209
274
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
210
275
  static isRunnable(thing) {
211
276
  return thing.lc_runnable;
212
277
  }
213
278
  }
214
279
  exports.Runnable = Runnable;
280
+ /**
281
+ * A runnable that delegates calls to another runnable with a set of kwargs.
282
+ */
283
+ class RunnableBinding extends Runnable {
284
+ static lc_name() {
285
+ return "RunnableBinding";
286
+ }
287
+ constructor(fields) {
288
+ super(fields);
289
+ Object.defineProperty(this, "lc_namespace", {
290
+ enumerable: true,
291
+ configurable: true,
292
+ writable: true,
293
+ value: ["langchain", "schema", "runnable"]
294
+ });
295
+ Object.defineProperty(this, "lc_serializable", {
296
+ enumerable: true,
297
+ configurable: true,
298
+ writable: true,
299
+ value: true
300
+ });
301
+ Object.defineProperty(this, "bound", {
302
+ enumerable: true,
303
+ configurable: true,
304
+ writable: true,
305
+ value: void 0
306
+ });
307
+ Object.defineProperty(this, "kwargs", {
308
+ enumerable: true,
309
+ configurable: true,
310
+ writable: true,
311
+ value: void 0
312
+ });
313
+ this.bound = fields.bound;
314
+ this.kwargs = fields.kwargs;
315
+ }
316
+ bind(kwargs) {
317
+ return new RunnableBinding({
318
+ bound: this.bound,
319
+ kwargs: { ...this.kwargs, ...kwargs },
320
+ });
321
+ }
322
+ async invoke(input, options) {
323
+ return this.bound.invoke(input, { ...options, ...this.kwargs });
324
+ }
325
+ async batch(inputs, options, batchOptions) {
326
+ const mergedOptions = Array.isArray(options)
327
+ ? options.map((individualOption) => ({
328
+ ...individualOption,
329
+ ...this.kwargs,
330
+ }))
331
+ : { ...options, ...this.kwargs };
332
+ return this.bound.batch(inputs, mergedOptions, batchOptions);
333
+ }
334
+ async *_streamIterator(input, options) {
335
+ yield* this.bound._streamIterator(input, { ...options, ...this.kwargs });
336
+ }
337
+ async stream(input, options) {
338
+ return this.bound.stream(input, { ...options, ...this.kwargs });
339
+ }
340
+ async *transform(
341
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
342
+ generator, options) {
343
+ yield* this.bound.transform(generator, options);
344
+ }
345
+ static isRunnableBinding(
346
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
347
+ thing
348
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
349
+ ) {
350
+ return thing.bound && Runnable.isRunnable(thing.bound);
351
+ }
352
+ }
353
+ exports.RunnableBinding = RunnableBinding;
354
+ /**
355
+ * Base class for runnables that can be retried a
356
+ * specified number of times.
357
+ */
358
+ class RunnableRetry extends RunnableBinding {
359
+ static lc_name() {
360
+ return "RunnableRetry";
361
+ }
362
+ constructor(fields) {
363
+ super(fields);
364
+ Object.defineProperty(this, "lc_namespace", {
365
+ enumerable: true,
366
+ configurable: true,
367
+ writable: true,
368
+ value: ["langchain", "schema", "runnable"]
369
+ });
370
+ Object.defineProperty(this, "maxAttemptNumber", {
371
+ enumerable: true,
372
+ configurable: true,
373
+ writable: true,
374
+ value: 3
375
+ });
376
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
377
+ Object.defineProperty(this, "onFailedAttempt", {
378
+ enumerable: true,
379
+ configurable: true,
380
+ writable: true,
381
+ value: () => { }
382
+ });
383
+ this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber;
384
+ this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt;
385
+ }
386
+ _patchConfigForRetry(attempt, config, runManager) {
387
+ const tag = attempt > 1 ? `retry:attempt:${attempt}` : undefined;
388
+ return this._patchConfig(config, runManager?.getChild(tag));
389
+ }
390
+ async _invoke(input, config, runManager) {
391
+ return (0, p_retry_1.default)((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), {
392
+ onFailedAttempt: this.onFailedAttempt,
393
+ retries: Math.max(this.maxAttemptNumber - 1, 0),
394
+ randomize: true,
395
+ });
396
+ }
397
+ /**
398
+ * Method that invokes the runnable with the specified input, run manager,
399
+ * and config. It handles the retry logic by catching any errors and
400
+ * recursively invoking itself with the updated config for the next retry
401
+ * attempt.
402
+ * @param input The input for the runnable.
403
+ * @param runManager The run manager for the runnable.
404
+ * @param config The config for the runnable.
405
+ * @returns A promise that resolves to the output of the runnable.
406
+ */
407
+ async invoke(input, config) {
408
+ return this._callWithConfig(this._invoke, input, config);
409
+ }
410
+ async _batch(inputs, configs, runManagers, batchOptions) {
411
+ const resultsMap = {};
412
+ try {
413
+ await (0, p_retry_1.default)(async (attemptNumber) => {
414
+ const remainingIndexes = inputs
415
+ .map((_, i) => i)
416
+ .filter((i) => resultsMap[i.toString()] === undefined ||
417
+ // eslint-disable-next-line no-instanceof/no-instanceof
418
+ resultsMap[i.toString()] instanceof Error);
419
+ const remainingInputs = remainingIndexes.map((i) => inputs[i]);
420
+ const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i]));
421
+ const results = await super.batch(remainingInputs, patchedConfigs, {
422
+ ...batchOptions,
423
+ returnExceptions: true,
424
+ });
425
+ let firstException;
426
+ for (let i = 0; i < results.length; i += 1) {
427
+ const result = results[i];
428
+ const resultMapIndex = remainingIndexes[i];
429
+ // eslint-disable-next-line no-instanceof/no-instanceof
430
+ if (result instanceof Error) {
431
+ if (firstException === undefined) {
432
+ firstException = result;
433
+ }
434
+ }
435
+ resultsMap[resultMapIndex.toString()] = result;
436
+ }
437
+ if (firstException) {
438
+ throw firstException;
439
+ }
440
+ return results;
441
+ }, {
442
+ onFailedAttempt: this.onFailedAttempt,
443
+ retries: Math.max(this.maxAttemptNumber - 1, 0),
444
+ randomize: true,
445
+ });
446
+ }
447
+ catch (e) {
448
+ if (batchOptions?.returnExceptions !== true) {
449
+ throw e;
450
+ }
451
+ }
452
+ return Object.keys(resultsMap)
453
+ .sort((a, b) => parseInt(a, 10) - parseInt(b, 10))
454
+ .map((key) => resultsMap[parseInt(key, 10)]);
455
+ }
456
+ async batch(inputs, options, batchOptions) {
457
+ return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions);
458
+ }
459
+ }
460
+ exports.RunnableRetry = RunnableRetry;
215
461
  /**
216
462
  * A sequence of runnables, where the output of each is the input of the next.
217
463
  */
@@ -260,7 +506,7 @@ class RunnableSequence extends Runnable {
260
506
  return [this.first, ...this.middle, this.last];
261
507
  }
262
508
  async invoke(input, options) {
263
- const callbackManager_ = await manager_js_1.CallbackManager.configure(options?.callbacks, undefined, options?.tags, undefined, options?.metadata);
509
+ const callbackManager_ = await (0, config_js_1.getCallbackMangerForConfig)(options);
264
510
  const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"));
265
511
  let nextStepInput = input;
266
512
  let finalOutput;
@@ -280,7 +526,7 @@ class RunnableSequence extends Runnable {
280
526
  }
281
527
  async batch(inputs, options, batchOptions) {
282
528
  const configList = this._getOptionsList(options ?? {}, inputs.length);
283
- const callbackManagers = await Promise.all(configList.map((config) => manager_js_1.CallbackManager.configure(config?.callbacks, undefined, config?.tags, undefined, config?.metadata)));
529
+ const callbackManagers = await Promise.all(configList.map(config_js_1.getCallbackMangerForConfig));
284
530
  const runManagers = await Promise.all(callbackManagers.map((callbackManager, i) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"))));
285
531
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
286
532
  let nextStepInputs = inputs;
@@ -300,17 +546,20 @@ class RunnableSequence extends Runnable {
300
546
  return finalOutputs;
301
547
  }
302
548
  async *_streamIterator(input, options) {
303
- const callbackManager_ = await manager_js_1.CallbackManager.configure(options?.callbacks, undefined, options?.tags, undefined, options?.metadata);
549
+ const callbackManager_ = await (0, config_js_1.getCallbackMangerForConfig)(options);
304
550
  const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"));
305
551
  let nextStepInput = input;
306
552
  const steps = [this.first, ...this.middle, this.last];
307
- // Find the index of the last runnable in the sequence that doesn't have a .transform() method
553
+ // Find the index of the last runnable in the sequence that doesn't have an overridden .transform() method
308
554
  // and start streaming from there
309
- const streamingStartStepIndex = steps.length -
310
- [...steps]
311
- .reverse()
312
- .findIndex((step) => typeof step.transform !== "function") -
313
- 1;
555
+ const streamingStartStepIndex = Math.min(steps.length - 1, steps.length -
556
+ [...steps].reverse().findIndex((step) => {
557
+ const isDefaultImplementation = step.transform === Runnable.prototype.transform;
558
+ const boundRunnableIsDefaultImplementation = RunnableBinding.isRunnableBinding(step) &&
559
+ step.bound?.transform === Runnable.prototype.transform;
560
+ return (isDefaultImplementation || boundRunnableIsDefaultImplementation);
561
+ }) -
562
+ 1);
314
563
  try {
315
564
  for (const step of steps.slice(0, streamingStartStepIndex)) {
316
565
  nextStepInput = await step.invoke(nextStepInput, this._patchConfig(options, runManager?.getChild()));
@@ -325,7 +574,6 @@ class RunnableSequence extends Runnable {
325
574
  try {
326
575
  let finalGenerator = await steps[streamingStartStepIndex]._streamIterator(nextStepInput, this._patchConfig(options, runManager?.getChild()));
327
576
  for (const step of steps.slice(streamingStartStepIndex + 1)) {
328
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
329
577
  finalGenerator = await step.transform(finalGenerator, this._patchConfig(options, runManager?.getChild()));
330
578
  }
331
579
  for await (const chunk of finalGenerator) {
@@ -422,7 +670,7 @@ class RunnableMap extends Runnable {
422
670
  async invoke(input, options
423
671
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
424
672
  ) {
425
- const callbackManager_ = await manager_js_1.CallbackManager.configure(options?.callbacks, undefined, options?.tags, undefined, options?.metadata);
673
+ const callbackManager_ = await (0, config_js_1.getCallbackMangerForConfig)(options);
426
674
  const runManager = await callbackManager_?.handleChainStart(this.toJSON(), {
427
675
  input,
428
676
  });
@@ -498,68 +746,6 @@ class RunnablePassthrough extends Runnable {
498
746
  }
499
747
  }
500
748
  exports.RunnablePassthrough = RunnablePassthrough;
501
- /**
502
- * A runnable that delegates calls to another runnable with a set of kwargs.
503
- */
504
- class RunnableBinding extends Runnable {
505
- static lc_name() {
506
- return "RunnableBinding";
507
- }
508
- constructor(fields) {
509
- super(fields);
510
- Object.defineProperty(this, "lc_namespace", {
511
- enumerable: true,
512
- configurable: true,
513
- writable: true,
514
- value: ["langchain", "schema", "runnable"]
515
- });
516
- Object.defineProperty(this, "lc_serializable", {
517
- enumerable: true,
518
- configurable: true,
519
- writable: true,
520
- value: true
521
- });
522
- Object.defineProperty(this, "bound", {
523
- enumerable: true,
524
- configurable: true,
525
- writable: true,
526
- value: void 0
527
- });
528
- Object.defineProperty(this, "kwargs", {
529
- enumerable: true,
530
- configurable: true,
531
- writable: true,
532
- value: void 0
533
- });
534
- this.bound = fields.bound;
535
- this.kwargs = fields.kwargs;
536
- }
537
- bind(kwargs) {
538
- return new RunnableBinding({
539
- bound: this.bound,
540
- kwargs: { ...this.kwargs, ...kwargs },
541
- });
542
- }
543
- async invoke(input, options) {
544
- return this.bound.invoke(input, { ...options, ...this.kwargs });
545
- }
546
- async batch(inputs, options, batchOptions) {
547
- const mergedOptions = Array.isArray(options)
548
- ? options.map((individualOption) => ({
549
- ...individualOption,
550
- ...this.kwargs,
551
- }))
552
- : { ...options, ...this.kwargs };
553
- return this.bound.batch(inputs, mergedOptions, batchOptions);
554
- }
555
- async *_streamIterator(input, options) {
556
- yield* this.bound._streamIterator(input, { ...options, ...this.kwargs });
557
- }
558
- async stream(input, options) {
559
- return this.bound.stream(input, { ...options, ...this.kwargs });
560
- }
561
- }
562
- exports.RunnableBinding = RunnableBinding;
563
749
  /**
564
750
  * A runnable that routes to a set of runnables based on Input['key'].
565
751
  * Returns the output of the selected runnable.
@@ -720,6 +906,7 @@ class RunnableWithFallbacks extends Runnable {
720
906
  }
721
907
  }
722
908
  exports.RunnableWithFallbacks = RunnableWithFallbacks;
909
+ // TODO: Figure out why the compiler needs help eliminating Error as a RunOutput type
723
910
  function _coerceToRunnable(coerceable) {
724
911
  if (typeof coerceable === "function") {
725
912
  return new RunnableLambda({ func: coerceable });
@@ -732,7 +919,9 @@ function _coerceToRunnable(coerceable) {
732
919
  for (const [key, value] of Object.entries(coerceable)) {
733
920
  runnables[key] = _coerceToRunnable(value);
734
921
  }
735
- return new RunnableMap({ steps: runnables });
922
+ return new RunnableMap({
923
+ steps: runnables,
924
+ });
736
925
  }
737
926
  else {
738
927
  throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`);