langchain 0.0.146 → 0.0.147

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 (64) hide show
  1. package/dist/base_language/index.cjs +2 -2
  2. package/dist/base_language/index.d.ts +2 -1
  3. package/dist/base_language/index.js +1 -1
  4. package/dist/chains/base.d.ts +1 -1
  5. package/dist/chains/openai_functions/openapi.cjs +32 -27
  6. package/dist/chains/openai_functions/openapi.d.ts +9 -0
  7. package/dist/chains/openai_functions/openapi.js +31 -27
  8. package/dist/chat_models/base.d.ts +1 -1
  9. package/dist/chat_models/openai.cjs +1 -1
  10. package/dist/chat_models/openai.js +1 -1
  11. package/dist/experimental/llms/bittensor.cjs +141 -0
  12. package/dist/experimental/llms/bittensor.d.ts +33 -0
  13. package/dist/experimental/llms/bittensor.js +137 -0
  14. package/dist/hub.d.ts +1 -1
  15. package/dist/llms/base.d.ts +1 -1
  16. package/dist/llms/openai-chat.cjs +1 -1
  17. package/dist/llms/openai-chat.js +1 -1
  18. package/dist/llms/openai.cjs +1 -1
  19. package/dist/llms/openai.js +1 -1
  20. package/dist/load/import_constants.cjs +1 -0
  21. package/dist/load/import_constants.js +1 -0
  22. package/dist/load/import_map.cjs +1 -1
  23. package/dist/load/import_map.d.ts +1 -1
  24. package/dist/load/import_map.js +1 -1
  25. package/dist/load/index.cjs +2 -1
  26. package/dist/load/index.js +2 -1
  27. package/dist/prompts/base.cjs +2 -2
  28. package/dist/prompts/base.d.ts +1 -1
  29. package/dist/prompts/base.js +1 -1
  30. package/dist/prompts/chat.cjs +2 -2
  31. package/dist/prompts/chat.d.ts +1 -1
  32. package/dist/prompts/chat.js +1 -1
  33. package/dist/schema/document.cjs +2 -2
  34. package/dist/schema/document.d.ts +1 -1
  35. package/dist/schema/document.js +1 -1
  36. package/dist/schema/output_parser.cjs +2 -2
  37. package/dist/schema/output_parser.d.ts +2 -1
  38. package/dist/schema/output_parser.js +1 -1
  39. package/dist/schema/retriever.cjs +2 -2
  40. package/dist/schema/retriever.d.ts +2 -1
  41. package/dist/schema/retriever.js +1 -1
  42. package/dist/schema/runnable/config.cjs +8 -0
  43. package/dist/schema/runnable/config.d.ts +3 -0
  44. package/dist/schema/runnable/config.js +4 -0
  45. package/dist/schema/{runnable.cjs → runnable/index.cjs} +290 -101
  46. package/dist/schema/{runnable.d.ts → runnable/index.d.ts} +127 -41
  47. package/dist/schema/{runnable.js → runnable/index.js} +284 -99
  48. package/dist/tools/base.d.ts +1 -1
  49. package/dist/util/async_caller.cjs +35 -25
  50. package/dist/util/async_caller.d.ts +8 -0
  51. package/dist/util/async_caller.js +35 -25
  52. package/dist/vectorstores/pinecone.cjs +30 -22
  53. package/dist/vectorstores/pinecone.d.ts +3 -1
  54. package/dist/vectorstores/pinecone.js +30 -22
  55. package/dist/vectorstores/vectara.cjs +20 -23
  56. package/dist/vectorstores/vectara.d.ts +9 -2
  57. package/dist/vectorstores/vectara.js +20 -23
  58. package/experimental/llms/bittensor.cjs +1 -0
  59. package/experimental/llms/bittensor.d.ts +1 -0
  60. package/experimental/llms/bittensor.js +1 -0
  61. package/package.json +9 -1
  62. package/schema/runnable.cjs +1 -1
  63. package/schema/runnable.d.ts +1 -1
  64. package/schema/runnable.js +1 -1
@@ -1,6 +1,9 @@
1
- import { CallbackManager, } from "../callbacks/manager.js";
2
- import { Serializable } from "../load/serializable.js";
3
- import { IterableReadableStream } from "../util/stream.js";
1
+ import pRetry from "p-retry";
2
+ import { CallbackManager, } from "../../callbacks/manager.js";
3
+ import { Serializable } from "../../load/serializable.js";
4
+ import { IterableReadableStream } from "../../util/stream.js";
5
+ import { getCallbackMangerForConfig, } from "./config.js";
6
+ import { AsyncCaller } from "../../util/async_caller.js";
4
7
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
5
8
  function _coerceToDict(value, defaultKey) {
6
9
  return value && !Array.isArray(value) && typeof value === "object"
@@ -30,6 +33,20 @@ export class Runnable extends Serializable {
30
33
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
31
34
  return new RunnableBinding({ bound: this, kwargs });
32
35
  }
36
+ /**
37
+ * Bind arguments to a Runnable, returning a new Runnable.
38
+ * @param kwargs
39
+ * @returns A new RunnableBinding that, when invoked, will apply the bound args.
40
+ */
41
+ withRetry(fields) {
42
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
43
+ return new RunnableRetry({
44
+ bound: this,
45
+ kwargs: {},
46
+ maxAttemptNumber: fields?.stopAfterAttempt,
47
+ ...fields,
48
+ });
49
+ }
33
50
  /**
34
51
  * Create a new runnable from the current one that will try invoking
35
52
  * other passed fallback runnables if the initial invocation fails.
@@ -52,28 +69,27 @@ export class Runnable extends Serializable {
52
69
  }
53
70
  return Array.from({ length }, () => options);
54
71
  }
55
- /**
56
- * Default implementation of batch, which calls invoke N times.
57
- * Subclasses should override this method if they can batch more efficiently.
58
- * @param inputs Array of inputs to each batch call.
59
- * @param options Either a single call options object to apply to each batch call or an array for each call.
60
- * @param batchOptions.maxConcurrency Maximum number of calls to run at once.
61
- * @returns An array of RunOutputs
62
- */
63
72
  async batch(inputs, options, batchOptions) {
64
73
  const configList = this._getOptionsList(options ?? {}, inputs.length);
65
- const batchSize = batchOptions?.maxConcurrency && batchOptions.maxConcurrency > 0
66
- ? batchOptions?.maxConcurrency
67
- : inputs.length;
68
- const batchResults = [];
69
- for (let i = 0; i < inputs.length; i += batchSize) {
70
- const batchPromises = inputs
71
- .slice(i, i + batchSize)
72
- .map((input, j) => this.invoke(input, configList[j]));
73
- const batchResult = await Promise.all(batchPromises);
74
- batchResults.push(batchResult);
75
- }
76
- return batchResults.flat();
74
+ const caller = new AsyncCaller({
75
+ maxConcurrency: batchOptions?.maxConcurrency,
76
+ onFailedAttempt: (e) => {
77
+ throw e;
78
+ },
79
+ });
80
+ const batchCalls = inputs.map((input, i) => caller.call(async () => {
81
+ try {
82
+ const result = await this.invoke(input, configList[i]);
83
+ return result;
84
+ }
85
+ catch (e) {
86
+ if (batchOptions?.returnExceptions) {
87
+ return e;
88
+ }
89
+ throw e;
90
+ }
91
+ }));
92
+ return Promise.all(batchCalls);
77
93
  }
78
94
  /**
79
95
  * Default streaming implementation.
@@ -106,11 +122,11 @@ export class Runnable extends Serializable {
106
122
  return [runnableConfig, callOptions];
107
123
  }
108
124
  async _callWithConfig(func, input, options) {
109
- const callbackManager_ = await CallbackManager.configure(options?.callbacks, undefined, options?.tags, undefined, options?.metadata);
125
+ const callbackManager_ = await getCallbackMangerForConfig(options);
110
126
  const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), undefined, options?.runType);
111
127
  let output;
112
128
  try {
113
- output = await func.bind(this)(input);
129
+ output = await func.bind(this)(input, options, runManager);
114
130
  }
115
131
  catch (e) {
116
132
  await runManager?.handleChainError(e);
@@ -119,6 +135,30 @@ export class Runnable extends Serializable {
119
135
  await runManager?.handleChainEnd(_coerceToDict(output, "output"));
120
136
  return output;
121
137
  }
138
+ /**
139
+ * Internal method that handles batching and configuration for a runnable
140
+ * It takes a function, input values, and optional configuration, and
141
+ * returns a promise that resolves to the output values.
142
+ * @param func The function to be executed for each input value.
143
+ * @param input The input values to be processed.
144
+ * @param config Optional configuration for the function execution.
145
+ * @returns A promise that resolves to the output values.
146
+ */
147
+ async _batchWithConfig(func, inputs, options, batchOptions) {
148
+ const configs = this._getOptionsList((options ?? {}), inputs.length);
149
+ const callbackManagers = await Promise.all(configs.map(getCallbackMangerForConfig));
150
+ const runManagers = await Promise.all(callbackManagers.map((callbackManager, i) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"))));
151
+ let outputs;
152
+ try {
153
+ outputs = await func(inputs, configs, runManagers, batchOptions);
154
+ }
155
+ catch (e) {
156
+ await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e)));
157
+ throw e;
158
+ }
159
+ await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict(outputs, "output"))));
160
+ return outputs;
161
+ }
122
162
  /**
123
163
  * Helper method to transform an Iterator of Input values into an Iterator of
124
164
  * Output values, with callbacks.
@@ -129,7 +169,7 @@ export class Runnable extends Serializable {
129
169
  let finalInputSupported = true;
130
170
  let finalOutput;
131
171
  let finalOutputSupported = true;
132
- const callbackManager_ = await CallbackManager.configure(options?.callbacks, undefined, options?.tags, undefined, options?.metadata);
172
+ const callbackManager_ = await getCallbackMangerForConfig(options);
133
173
  let runManager;
134
174
  const serializedRepresentation = this.toJSON();
135
175
  async function* wrapInputForTracing() {
@@ -203,11 +243,212 @@ export class Runnable extends Serializable {
203
243
  last: _coerceToRunnable(coerceable),
204
244
  });
205
245
  }
246
+ /**
247
+ * Default implementation of transform, which buffers input and then calls stream.
248
+ * Subclasses should override this method if they can start producing output while
249
+ * input is still being generated.
250
+ * @param generator
251
+ * @param options
252
+ */
253
+ async *transform(generator, options) {
254
+ let finalChunk;
255
+ for await (const chunk of generator) {
256
+ if (!finalChunk) {
257
+ finalChunk = chunk;
258
+ }
259
+ else {
260
+ // Make a best effort to gather, for any type that supports concat.
261
+ // This method should throw an error if gathering fails.
262
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
263
+ finalChunk = finalChunk.concat(chunk);
264
+ }
265
+ }
266
+ yield* this._streamIterator(finalChunk, options);
267
+ }
206
268
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
207
269
  static isRunnable(thing) {
208
270
  return thing.lc_runnable;
209
271
  }
210
272
  }
273
+ /**
274
+ * A runnable that delegates calls to another runnable with a set of kwargs.
275
+ */
276
+ export class RunnableBinding extends Runnable {
277
+ static lc_name() {
278
+ return "RunnableBinding";
279
+ }
280
+ constructor(fields) {
281
+ super(fields);
282
+ Object.defineProperty(this, "lc_namespace", {
283
+ enumerable: true,
284
+ configurable: true,
285
+ writable: true,
286
+ value: ["langchain", "schema", "runnable"]
287
+ });
288
+ Object.defineProperty(this, "lc_serializable", {
289
+ enumerable: true,
290
+ configurable: true,
291
+ writable: true,
292
+ value: true
293
+ });
294
+ Object.defineProperty(this, "bound", {
295
+ enumerable: true,
296
+ configurable: true,
297
+ writable: true,
298
+ value: void 0
299
+ });
300
+ Object.defineProperty(this, "kwargs", {
301
+ enumerable: true,
302
+ configurable: true,
303
+ writable: true,
304
+ value: void 0
305
+ });
306
+ this.bound = fields.bound;
307
+ this.kwargs = fields.kwargs;
308
+ }
309
+ bind(kwargs) {
310
+ return new RunnableBinding({
311
+ bound: this.bound,
312
+ kwargs: { ...this.kwargs, ...kwargs },
313
+ });
314
+ }
315
+ async invoke(input, options) {
316
+ return this.bound.invoke(input, { ...options, ...this.kwargs });
317
+ }
318
+ async batch(inputs, options, batchOptions) {
319
+ const mergedOptions = Array.isArray(options)
320
+ ? options.map((individualOption) => ({
321
+ ...individualOption,
322
+ ...this.kwargs,
323
+ }))
324
+ : { ...options, ...this.kwargs };
325
+ return this.bound.batch(inputs, mergedOptions, batchOptions);
326
+ }
327
+ async *_streamIterator(input, options) {
328
+ yield* this.bound._streamIterator(input, { ...options, ...this.kwargs });
329
+ }
330
+ async stream(input, options) {
331
+ return this.bound.stream(input, { ...options, ...this.kwargs });
332
+ }
333
+ async *transform(
334
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
335
+ generator, options) {
336
+ yield* this.bound.transform(generator, options);
337
+ }
338
+ static isRunnableBinding(
339
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
340
+ thing
341
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
342
+ ) {
343
+ return thing.bound && Runnable.isRunnable(thing.bound);
344
+ }
345
+ }
346
+ /**
347
+ * Base class for runnables that can be retried a
348
+ * specified number of times.
349
+ */
350
+ export class RunnableRetry extends RunnableBinding {
351
+ static lc_name() {
352
+ return "RunnableRetry";
353
+ }
354
+ constructor(fields) {
355
+ super(fields);
356
+ Object.defineProperty(this, "lc_namespace", {
357
+ enumerable: true,
358
+ configurable: true,
359
+ writable: true,
360
+ value: ["langchain", "schema", "runnable"]
361
+ });
362
+ Object.defineProperty(this, "maxAttemptNumber", {
363
+ enumerable: true,
364
+ configurable: true,
365
+ writable: true,
366
+ value: 3
367
+ });
368
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
369
+ Object.defineProperty(this, "onFailedAttempt", {
370
+ enumerable: true,
371
+ configurable: true,
372
+ writable: true,
373
+ value: () => { }
374
+ });
375
+ this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber;
376
+ this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt;
377
+ }
378
+ _patchConfigForRetry(attempt, config, runManager) {
379
+ const tag = attempt > 1 ? `retry:attempt:${attempt}` : undefined;
380
+ return this._patchConfig(config, runManager?.getChild(tag));
381
+ }
382
+ async _invoke(input, config, runManager) {
383
+ return pRetry((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), {
384
+ onFailedAttempt: this.onFailedAttempt,
385
+ retries: Math.max(this.maxAttemptNumber - 1, 0),
386
+ randomize: true,
387
+ });
388
+ }
389
+ /**
390
+ * Method that invokes the runnable with the specified input, run manager,
391
+ * and config. It handles the retry logic by catching any errors and
392
+ * recursively invoking itself with the updated config for the next retry
393
+ * attempt.
394
+ * @param input The input for the runnable.
395
+ * @param runManager The run manager for the runnable.
396
+ * @param config The config for the runnable.
397
+ * @returns A promise that resolves to the output of the runnable.
398
+ */
399
+ async invoke(input, config) {
400
+ return this._callWithConfig(this._invoke, input, config);
401
+ }
402
+ async _batch(inputs, configs, runManagers, batchOptions) {
403
+ const resultsMap = {};
404
+ try {
405
+ await pRetry(async (attemptNumber) => {
406
+ const remainingIndexes = inputs
407
+ .map((_, i) => i)
408
+ .filter((i) => resultsMap[i.toString()] === undefined ||
409
+ // eslint-disable-next-line no-instanceof/no-instanceof
410
+ resultsMap[i.toString()] instanceof Error);
411
+ const remainingInputs = remainingIndexes.map((i) => inputs[i]);
412
+ const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i]));
413
+ const results = await super.batch(remainingInputs, patchedConfigs, {
414
+ ...batchOptions,
415
+ returnExceptions: true,
416
+ });
417
+ let firstException;
418
+ for (let i = 0; i < results.length; i += 1) {
419
+ const result = results[i];
420
+ const resultMapIndex = remainingIndexes[i];
421
+ // eslint-disable-next-line no-instanceof/no-instanceof
422
+ if (result instanceof Error) {
423
+ if (firstException === undefined) {
424
+ firstException = result;
425
+ }
426
+ }
427
+ resultsMap[resultMapIndex.toString()] = result;
428
+ }
429
+ if (firstException) {
430
+ throw firstException;
431
+ }
432
+ return results;
433
+ }, {
434
+ onFailedAttempt: this.onFailedAttempt,
435
+ retries: Math.max(this.maxAttemptNumber - 1, 0),
436
+ randomize: true,
437
+ });
438
+ }
439
+ catch (e) {
440
+ if (batchOptions?.returnExceptions !== true) {
441
+ throw e;
442
+ }
443
+ }
444
+ return Object.keys(resultsMap)
445
+ .sort((a, b) => parseInt(a, 10) - parseInt(b, 10))
446
+ .map((key) => resultsMap[parseInt(key, 10)]);
447
+ }
448
+ async batch(inputs, options, batchOptions) {
449
+ return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions);
450
+ }
451
+ }
211
452
  /**
212
453
  * A sequence of runnables, where the output of each is the input of the next.
213
454
  */
@@ -256,7 +497,7 @@ export class RunnableSequence extends Runnable {
256
497
  return [this.first, ...this.middle, this.last];
257
498
  }
258
499
  async invoke(input, options) {
259
- const callbackManager_ = await CallbackManager.configure(options?.callbacks, undefined, options?.tags, undefined, options?.metadata);
500
+ const callbackManager_ = await getCallbackMangerForConfig(options);
260
501
  const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"));
261
502
  let nextStepInput = input;
262
503
  let finalOutput;
@@ -276,7 +517,7 @@ export class RunnableSequence extends Runnable {
276
517
  }
277
518
  async batch(inputs, options, batchOptions) {
278
519
  const configList = this._getOptionsList(options ?? {}, inputs.length);
279
- const callbackManagers = await Promise.all(configList.map((config) => CallbackManager.configure(config?.callbacks, undefined, config?.tags, undefined, config?.metadata)));
520
+ const callbackManagers = await Promise.all(configList.map(getCallbackMangerForConfig));
280
521
  const runManagers = await Promise.all(callbackManagers.map((callbackManager, i) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"))));
281
522
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
282
523
  let nextStepInputs = inputs;
@@ -296,17 +537,20 @@ export class RunnableSequence extends Runnable {
296
537
  return finalOutputs;
297
538
  }
298
539
  async *_streamIterator(input, options) {
299
- const callbackManager_ = await CallbackManager.configure(options?.callbacks, undefined, options?.tags, undefined, options?.metadata);
540
+ const callbackManager_ = await getCallbackMangerForConfig(options);
300
541
  const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"));
301
542
  let nextStepInput = input;
302
543
  const steps = [this.first, ...this.middle, this.last];
303
- // Find the index of the last runnable in the sequence that doesn't have a .transform() method
544
+ // Find the index of the last runnable in the sequence that doesn't have an overridden .transform() method
304
545
  // and start streaming from there
305
- const streamingStartStepIndex = steps.length -
306
- [...steps]
307
- .reverse()
308
- .findIndex((step) => typeof step.transform !== "function") -
309
- 1;
546
+ const streamingStartStepIndex = Math.min(steps.length - 1, steps.length -
547
+ [...steps].reverse().findIndex((step) => {
548
+ const isDefaultImplementation = step.transform === Runnable.prototype.transform;
549
+ const boundRunnableIsDefaultImplementation = RunnableBinding.isRunnableBinding(step) &&
550
+ step.bound?.transform === Runnable.prototype.transform;
551
+ return (isDefaultImplementation || boundRunnableIsDefaultImplementation);
552
+ }) -
553
+ 1);
310
554
  try {
311
555
  for (const step of steps.slice(0, streamingStartStepIndex)) {
312
556
  nextStepInput = await step.invoke(nextStepInput, this._patchConfig(options, runManager?.getChild()));
@@ -321,7 +565,6 @@ export class RunnableSequence extends Runnable {
321
565
  try {
322
566
  let finalGenerator = await steps[streamingStartStepIndex]._streamIterator(nextStepInput, this._patchConfig(options, runManager?.getChild()));
323
567
  for (const step of steps.slice(streamingStartStepIndex + 1)) {
324
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
325
568
  finalGenerator = await step.transform(finalGenerator, this._patchConfig(options, runManager?.getChild()));
326
569
  }
327
570
  for await (const chunk of finalGenerator) {
@@ -417,7 +660,7 @@ export class RunnableMap extends Runnable {
417
660
  async invoke(input, options
418
661
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
419
662
  ) {
420
- const callbackManager_ = await CallbackManager.configure(options?.callbacks, undefined, options?.tags, undefined, options?.metadata);
663
+ const callbackManager_ = await getCallbackMangerForConfig(options);
421
664
  const runManager = await callbackManager_?.handleChainStart(this.toJSON(), {
422
665
  input,
423
666
  });
@@ -490,67 +733,6 @@ export class RunnablePassthrough extends Runnable {
490
733
  return this._callWithConfig((input) => Promise.resolve(input), input, options);
491
734
  }
492
735
  }
493
- /**
494
- * A runnable that delegates calls to another runnable with a set of kwargs.
495
- */
496
- export class RunnableBinding extends Runnable {
497
- static lc_name() {
498
- return "RunnableBinding";
499
- }
500
- constructor(fields) {
501
- super(fields);
502
- Object.defineProperty(this, "lc_namespace", {
503
- enumerable: true,
504
- configurable: true,
505
- writable: true,
506
- value: ["langchain", "schema", "runnable"]
507
- });
508
- Object.defineProperty(this, "lc_serializable", {
509
- enumerable: true,
510
- configurable: true,
511
- writable: true,
512
- value: true
513
- });
514
- Object.defineProperty(this, "bound", {
515
- enumerable: true,
516
- configurable: true,
517
- writable: true,
518
- value: void 0
519
- });
520
- Object.defineProperty(this, "kwargs", {
521
- enumerable: true,
522
- configurable: true,
523
- writable: true,
524
- value: void 0
525
- });
526
- this.bound = fields.bound;
527
- this.kwargs = fields.kwargs;
528
- }
529
- bind(kwargs) {
530
- return new RunnableBinding({
531
- bound: this.bound,
532
- kwargs: { ...this.kwargs, ...kwargs },
533
- });
534
- }
535
- async invoke(input, options) {
536
- return this.bound.invoke(input, { ...options, ...this.kwargs });
537
- }
538
- async batch(inputs, options, batchOptions) {
539
- const mergedOptions = Array.isArray(options)
540
- ? options.map((individualOption) => ({
541
- ...individualOption,
542
- ...this.kwargs,
543
- }))
544
- : { ...options, ...this.kwargs };
545
- return this.bound.batch(inputs, mergedOptions, batchOptions);
546
- }
547
- async *_streamIterator(input, options) {
548
- yield* this.bound._streamIterator(input, { ...options, ...this.kwargs });
549
- }
550
- async stream(input, options) {
551
- return this.bound.stream(input, { ...options, ...this.kwargs });
552
- }
553
- }
554
736
  /**
555
737
  * A runnable that routes to a set of runnables based on Input['key'].
556
738
  * Returns the output of the selected runnable.
@@ -709,6 +891,7 @@ export class RunnableWithFallbacks extends Runnable {
709
891
  throw firstError;
710
892
  }
711
893
  }
894
+ // TODO: Figure out why the compiler needs help eliminating Error as a RunOutput type
712
895
  function _coerceToRunnable(coerceable) {
713
896
  if (typeof coerceable === "function") {
714
897
  return new RunnableLambda({ func: coerceable });
@@ -721,7 +904,9 @@ function _coerceToRunnable(coerceable) {
721
904
  for (const [key, value] of Object.entries(coerceable)) {
722
905
  runnables[key] = _coerceToRunnable(value);
723
906
  }
724
- return new RunnableMap({ steps: runnables });
907
+ return new RunnableMap({
908
+ steps: runnables,
909
+ });
725
910
  }
726
911
  else {
727
912
  throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`);
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { CallbackManagerForToolRun, Callbacks } from "../callbacks/manager.js";
3
3
  import { BaseLangChain, BaseLangChainParams } from "../base_language/index.js";
4
- import { RunnableConfig } from "../schema/runnable.js";
4
+ import { RunnableConfig } from "../schema/runnable/config.js";
5
5
  /**
6
6
  * Parameters for the Tool classes.
7
7
  */
@@ -18,6 +18,32 @@ const STATUS_NO_RETRY = [
18
18
  408,
19
19
  409, // Conflict
20
20
  ];
21
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
22
+ const defaultFailedAttemptHandler = (error) => {
23
+ if (error.message.startsWith("Cancel") ||
24
+ error.message.startsWith("TimeoutError") ||
25
+ error.name === "TimeoutError" ||
26
+ error.message.startsWith("AbortError") ||
27
+ error.name === "AbortError") {
28
+ throw error;
29
+ }
30
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
31
+ if (error?.code === "ECONNABORTED") {
32
+ throw error;
33
+ }
34
+ const status =
35
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
36
+ error?.response?.status ?? error?.status;
37
+ if (status && STATUS_NO_RETRY.includes(+status)) {
38
+ throw error;
39
+ }
40
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
41
+ if (error?.error?.code === "insufficient_quota") {
42
+ const err = new Error(error?.message);
43
+ err.name = "InsufficientQuotaError";
44
+ throw err;
45
+ }
46
+ };
21
47
  /**
22
48
  * A class that can be used to make async calls with concurrency and retry logic.
23
49
  *
@@ -45,6 +71,12 @@ class AsyncCaller {
45
71
  writable: true,
46
72
  value: void 0
47
73
  });
74
+ Object.defineProperty(this, "onFailedAttempt", {
75
+ enumerable: true,
76
+ configurable: true,
77
+ writable: true,
78
+ value: void 0
79
+ });
48
80
  Object.defineProperty(this, "queue", {
49
81
  enumerable: true,
50
82
  configurable: true,
@@ -53,6 +85,8 @@ class AsyncCaller {
53
85
  });
54
86
  this.maxConcurrency = params.maxConcurrency ?? Infinity;
55
87
  this.maxRetries = params.maxRetries ?? 6;
88
+ this.onFailedAttempt =
89
+ params.onFailedAttempt ?? defaultFailedAttemptHandler;
56
90
  const PQueue = "default" in p_queue_1.default ? p_queue_1.default.default : p_queue_1.default;
57
91
  this.queue = new PQueue({ concurrency: this.maxConcurrency });
58
92
  }
@@ -67,31 +101,7 @@ class AsyncCaller {
67
101
  throw new Error(error);
68
102
  }
69
103
  }), {
70
- onFailedAttempt(error) {
71
- if (error.message.startsWith("Cancel") ||
72
- error.message.startsWith("TimeoutError") ||
73
- error.name === "TimeoutError" ||
74
- error.message.startsWith("AbortError") ||
75
- error.name === "AbortError") {
76
- throw error;
77
- }
78
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
79
- if (error?.code === "ECONNABORTED") {
80
- throw error;
81
- }
82
- const status =
83
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
84
- error?.response?.status ?? error?.status;
85
- if (status && STATUS_NO_RETRY.includes(+status)) {
86
- throw error;
87
- }
88
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
89
- if (error?.error?.code === "insufficient_quota") {
90
- const err = new Error(error?.message);
91
- err.name = "InsufficientQuotaError";
92
- throw err;
93
- }
94
- },
104
+ onFailedAttempt: this.onFailedAttempt,
95
105
  retries: this.maxRetries,
96
106
  randomize: true,
97
107
  // If needed we can change some of the defaults here,
@@ -1,3 +1,4 @@
1
+ export type FailedAttemptHandler = (error: any) => any;
1
2
  export interface AsyncCallerParams {
2
3
  /**
3
4
  * The maximum number of concurrent calls that can be made.
@@ -9,6 +10,12 @@ export interface AsyncCallerParams {
9
10
  * with an exponential backoff between each attempt. Defaults to 6.
10
11
  */
11
12
  maxRetries?: number;
13
+ /**
14
+ * Custom handler to handle failed attempts. Takes the originally thrown
15
+ * error object as input, and should itself throw an error if the input
16
+ * error is not retryable.
17
+ */
18
+ onFailedAttempt?: FailedAttemptHandler;
12
19
  }
13
20
  export interface AsyncCallerCallOptions {
14
21
  signal?: AbortSignal;
@@ -29,6 +36,7 @@ export interface AsyncCallerCallOptions {
29
36
  export declare class AsyncCaller {
30
37
  protected maxConcurrency: AsyncCallerParams["maxConcurrency"];
31
38
  protected maxRetries: AsyncCallerParams["maxRetries"];
39
+ protected onFailedAttempt: AsyncCallerParams["onFailedAttempt"];
32
40
  private queue;
33
41
  constructor(params: AsyncCallerParams);
34
42
  call<A extends any[], T extends (...args: A) => Promise<any>>(callable: T, ...args: Parameters<T>): Promise<Awaited<ReturnType<T>>>;