@langchain/core 0.2.22 → 0.2.24

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.
@@ -111,10 +111,11 @@ class Runnable extends serializable_js_1.Serializable {
111
111
  * @returns A new RunnableWithFallbacks.
112
112
  */
113
113
  withFallbacks(fields) {
114
+ const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks;
114
115
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
115
116
  return new RunnableWithFallbacks({
116
117
  runnable: this,
117
- fallbacks: fields.fallbacks,
118
+ fallbacks,
118
119
  });
119
120
  }
120
121
  _getOptionsList(options, length = 0) {
@@ -1673,6 +1674,22 @@ class RunnableParallel extends RunnableMap {
1673
1674
  exports.RunnableParallel = RunnableParallel;
1674
1675
  /**
1675
1676
  * A Runnable that can fallback to other Runnables if it fails.
1677
+ * External APIs (e.g., APIs for a language model) may at times experience
1678
+ * degraded performance or even downtime.
1679
+ *
1680
+ * In these cases, it can be useful to have a fallback Runnable that can be
1681
+ * used in place of the original Runnable (e.g., fallback to another LLM provider).
1682
+ *
1683
+ * Fallbacks can be defined at the level of a single Runnable, or at the level
1684
+ * of a chain of Runnables. Fallbacks are tried in order until one succeeds or
1685
+ * all fail.
1686
+ *
1687
+ * While you can instantiate a `RunnableWithFallbacks` directly, it is usually
1688
+ * more convenient to use the `withFallbacks` method on an existing Runnable.
1689
+ *
1690
+ * When streaming, fallbacks will only be called on failures during the initial
1691
+ * stream creation. Errors that occur after a stream starts will not fallback
1692
+ * to the next Runnable.
1676
1693
  */
1677
1694
  class RunnableWithFallbacks extends Runnable {
1678
1695
  static lc_name() {
@@ -1738,6 +1755,51 @@ class RunnableWithFallbacks extends Runnable {
1738
1755
  await runManager?.handleChainError(firstError);
1739
1756
  throw firstError;
1740
1757
  }
1758
+ async *_streamIterator(input, options) {
1759
+ const config = (0, config_js_1.ensureConfig)(options);
1760
+ const callbackManager_ = await (0, config_js_1.getCallbackManagerForConfig)(options);
1761
+ const { runId, ...otherConfigFields } = config;
1762
+ const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherConfigFields?.runName);
1763
+ let firstError;
1764
+ let stream;
1765
+ for (const runnable of this.runnables()) {
1766
+ config?.signal?.throwIfAborted();
1767
+ const childConfig = (0, config_js_1.patchConfig)(otherConfigFields, {
1768
+ callbacks: runManager?.getChild(),
1769
+ });
1770
+ try {
1771
+ stream = await runnable.stream(input, childConfig);
1772
+ break;
1773
+ }
1774
+ catch (e) {
1775
+ if (firstError === undefined) {
1776
+ firstError = e;
1777
+ }
1778
+ }
1779
+ }
1780
+ if (stream === undefined) {
1781
+ const error = firstError ?? new Error("No error stored at end of fallback.");
1782
+ await runManager?.handleChainError(error);
1783
+ throw error;
1784
+ }
1785
+ let output;
1786
+ try {
1787
+ for await (const chunk of stream) {
1788
+ yield chunk;
1789
+ try {
1790
+ output = output === undefined ? output : (0, stream_js_1.concat)(output, chunk);
1791
+ }
1792
+ catch (e) {
1793
+ output = undefined;
1794
+ }
1795
+ }
1796
+ }
1797
+ catch (e) {
1798
+ await runManager?.handleChainError(e);
1799
+ throw e;
1800
+ }
1801
+ await runManager?.handleChainEnd(_coerceToDict(output, "output"));
1802
+ }
1741
1803
  async batch(inputs, options, batchOptions) {
1742
1804
  if (batchOptions?.returnExceptions) {
1743
1805
  throw new Error("Not implemented.");
@@ -67,7 +67,7 @@ export declare abstract class Runnable<RunInput = any, RunOutput = any, CallOpti
67
67
  */
68
68
  withFallbacks(fields: {
69
69
  fallbacks: Runnable<RunInput, RunOutput>[];
70
- }): RunnableWithFallbacks<RunInput, RunOutput>;
70
+ } | Runnable<RunInput, RunOutput>[]): RunnableWithFallbacks<RunInput, RunOutput>;
71
71
  protected _getOptionsList<O extends CallOptions & {
72
72
  runType?: string;
73
73
  }>(options: Partial<O> | Partial<O>[], length?: number): Partial<O>[];
@@ -187,6 +187,7 @@ export declare abstract class Runnable<RunInput = any, RunOutput = any, CallOpti
187
187
  *
188
188
  * **ATTENTION** This reference table is for the V2 version of the schema.
189
189
  *
190
+ * ```md
190
191
  * +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
191
192
  * | event | name | chunk | input | output |
192
193
  * +======================+==================+=================================+===============================================+=================================================+
@@ -220,6 +221,7 @@ export declare abstract class Runnable<RunInput = any, RunOutput = any, CallOpti
220
221
  * +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
221
222
  * | on_prompt_end | [template_name] | | {"question": "hello"} | ChatPromptValue(messages: [SystemMessage, ...]) |
222
223
  * +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
224
+ * ```
223
225
  *
224
226
  * The "on_chain_*" events are the default for Runnables that don't fit one of the above categories.
225
227
  *
@@ -229,6 +231,7 @@ export declare abstract class Runnable<RunInput = any, RunOutput = any, CallOpti
229
231
  *
230
232
  * A custom event has following format:
231
233
  *
234
+ * ```md
232
235
  * +-----------+------+-----------------------------------------------------------------------------------------------------------+
233
236
  * | Attribute | Type | Description |
234
237
  * +===========+======+===========================================================================================================+
@@ -236,9 +239,10 @@ export declare abstract class Runnable<RunInput = any, RunOutput = any, CallOpti
236
239
  * +-----------+------+-----------------------------------------------------------------------------------------------------------+
237
240
  * | data | Any | The data associated with the event. This can be anything, though we suggest making it JSON serializable. |
238
241
  * +-----------+------+-----------------------------------------------------------------------------------------------------------+
242
+ * ```
239
243
  *
240
244
  * Here's an example:
241
- * @example
245
+ *
242
246
  * ```ts
243
247
  * import { RunnableLambda } from "@langchain/core/runnables";
244
248
  * import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch";
@@ -568,6 +572,22 @@ export declare class RunnableParallel<RunInput> extends RunnableMap<RunInput> {
568
572
  }
569
573
  /**
570
574
  * A Runnable that can fallback to other Runnables if it fails.
575
+ * External APIs (e.g., APIs for a language model) may at times experience
576
+ * degraded performance or even downtime.
577
+ *
578
+ * In these cases, it can be useful to have a fallback Runnable that can be
579
+ * used in place of the original Runnable (e.g., fallback to another LLM provider).
580
+ *
581
+ * Fallbacks can be defined at the level of a single Runnable, or at the level
582
+ * of a chain of Runnables. Fallbacks are tried in order until one succeeds or
583
+ * all fail.
584
+ *
585
+ * While you can instantiate a `RunnableWithFallbacks` directly, it is usually
586
+ * more convenient to use the `withFallbacks` method on an existing Runnable.
587
+ *
588
+ * When streaming, fallbacks will only be called on failures during the initial
589
+ * stream creation. Errors that occur after a stream starts will not fallback
590
+ * to the next Runnable.
571
591
  */
572
592
  export declare class RunnableWithFallbacks<RunInput, RunOutput> extends Runnable<RunInput, RunOutput> {
573
593
  static lc_name(): string;
@@ -581,6 +601,7 @@ export declare class RunnableWithFallbacks<RunInput, RunOutput> extends Runnable
581
601
  });
582
602
  runnables(): Generator<Runnable<RunInput, RunOutput, RunnableConfig>, void, unknown>;
583
603
  invoke(input: RunInput, options?: Partial<RunnableConfig>): Promise<RunOutput>;
604
+ _streamIterator(input: RunInput, options?: Partial<RunnableConfig> | undefined): AsyncGenerator<RunOutput>;
584
605
  batch(inputs: RunInput[], options?: Partial<RunnableConfig> | Partial<RunnableConfig>[], batchOptions?: RunnableBatchOptions & {
585
606
  returnExceptions?: false;
586
607
  }): Promise<RunOutput[]>;
@@ -104,10 +104,11 @@ export class Runnable extends Serializable {
104
104
  * @returns A new RunnableWithFallbacks.
105
105
  */
106
106
  withFallbacks(fields) {
107
+ const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks;
107
108
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
108
109
  return new RunnableWithFallbacks({
109
110
  runnable: this,
110
- fallbacks: fields.fallbacks,
111
+ fallbacks,
111
112
  });
112
113
  }
113
114
  _getOptionsList(options, length = 0) {
@@ -1657,6 +1658,22 @@ export class RunnableParallel extends RunnableMap {
1657
1658
  }
1658
1659
  /**
1659
1660
  * A Runnable that can fallback to other Runnables if it fails.
1661
+ * External APIs (e.g., APIs for a language model) may at times experience
1662
+ * degraded performance or even downtime.
1663
+ *
1664
+ * In these cases, it can be useful to have a fallback Runnable that can be
1665
+ * used in place of the original Runnable (e.g., fallback to another LLM provider).
1666
+ *
1667
+ * Fallbacks can be defined at the level of a single Runnable, or at the level
1668
+ * of a chain of Runnables. Fallbacks are tried in order until one succeeds or
1669
+ * all fail.
1670
+ *
1671
+ * While you can instantiate a `RunnableWithFallbacks` directly, it is usually
1672
+ * more convenient to use the `withFallbacks` method on an existing Runnable.
1673
+ *
1674
+ * When streaming, fallbacks will only be called on failures during the initial
1675
+ * stream creation. Errors that occur after a stream starts will not fallback
1676
+ * to the next Runnable.
1660
1677
  */
1661
1678
  export class RunnableWithFallbacks extends Runnable {
1662
1679
  static lc_name() {
@@ -1722,6 +1739,51 @@ export class RunnableWithFallbacks extends Runnable {
1722
1739
  await runManager?.handleChainError(firstError);
1723
1740
  throw firstError;
1724
1741
  }
1742
+ async *_streamIterator(input, options) {
1743
+ const config = ensureConfig(options);
1744
+ const callbackManager_ = await getCallbackManagerForConfig(options);
1745
+ const { runId, ...otherConfigFields } = config;
1746
+ const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherConfigFields?.runName);
1747
+ let firstError;
1748
+ let stream;
1749
+ for (const runnable of this.runnables()) {
1750
+ config?.signal?.throwIfAborted();
1751
+ const childConfig = patchConfig(otherConfigFields, {
1752
+ callbacks: runManager?.getChild(),
1753
+ });
1754
+ try {
1755
+ stream = await runnable.stream(input, childConfig);
1756
+ break;
1757
+ }
1758
+ catch (e) {
1759
+ if (firstError === undefined) {
1760
+ firstError = e;
1761
+ }
1762
+ }
1763
+ }
1764
+ if (stream === undefined) {
1765
+ const error = firstError ?? new Error("No error stored at end of fallback.");
1766
+ await runManager?.handleChainError(error);
1767
+ throw error;
1768
+ }
1769
+ let output;
1770
+ try {
1771
+ for await (const chunk of stream) {
1772
+ yield chunk;
1773
+ try {
1774
+ output = output === undefined ? output : concat(output, chunk);
1775
+ }
1776
+ catch (e) {
1777
+ output = undefined;
1778
+ }
1779
+ }
1780
+ }
1781
+ catch (e) {
1782
+ await runManager?.handleChainError(e);
1783
+ throw e;
1784
+ }
1785
+ await runManager?.handleChainEnd(_coerceToDict(output, "output"));
1786
+ }
1725
1787
  async batch(inputs, options, batchOptions) {
1726
1788
  if (batchOptions?.returnExceptions) {
1727
1789
  throw new Error("Not implemented.");
@@ -257,12 +257,17 @@ class RemoteRunnable extends base_js_1.Runnable {
257
257
  writable: true,
258
258
  value: void 0
259
259
  });
260
+ // Wrap the default fetch call due to issues with illegal invocations
261
+ // from the browser:
262
+ // https://stackoverflow.com/questions/69876859/why-does-bind-fix-failed-to-execute-fetch-on-window-illegal-invocation-err
260
263
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
261
264
  Object.defineProperty(this, "fetchImplementation", {
262
265
  enumerable: true,
263
266
  configurable: true,
264
267
  writable: true,
265
- value: fetch
268
+ value: (...args) =>
269
+ // @ts-expect-error Broad typing to support a range of fetch implementations
270
+ fetch(...args)
266
271
  });
267
272
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
268
273
  Object.defineProperty(this, "fetchRequestOptions", {
@@ -254,12 +254,17 @@ export class RemoteRunnable extends Runnable {
254
254
  writable: true,
255
255
  value: void 0
256
256
  });
257
+ // Wrap the default fetch call due to issues with illegal invocations
258
+ // from the browser:
259
+ // https://stackoverflow.com/questions/69876859/why-does-bind-fix-failed-to-execute-fetch-on-window-illegal-invocation-err
257
260
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
258
261
  Object.defineProperty(this, "fetchImplementation", {
259
262
  enumerable: true,
260
263
  configurable: true,
261
264
  writable: true,
262
- value: fetch
265
+ value: (...args) =>
266
+ // @ts-expect-error Broad typing to support a range of fetch implementations
267
+ fetch(...args)
263
268
  });
264
269
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
265
270
  Object.defineProperty(this, "fetchRequestOptions", {
@@ -5,6 +5,7 @@ async function raceWithSignal(promise, signal) {
5
5
  if (signal === undefined) {
6
6
  return promise;
7
7
  }
8
+ let listener;
8
9
  return Promise.race([
9
10
  promise.catch((err) => {
10
11
  if (!signal?.aborted) {
@@ -15,14 +16,15 @@ async function raceWithSignal(promise, signal) {
15
16
  }
16
17
  }),
17
18
  new Promise((_, reject) => {
18
- signal.addEventListener("abort", () => {
19
+ listener = () => {
19
20
  reject(new Error("Aborted"));
20
- });
21
+ };
22
+ signal.addEventListener("abort", listener);
21
23
  // Must be here inside the promise to avoid a race condition
22
24
  if (signal.aborted) {
23
25
  reject(new Error("Aborted"));
24
26
  }
25
27
  }),
26
- ]);
28
+ ]).finally(() => signal.removeEventListener("abort", listener));
27
29
  }
28
30
  exports.raceWithSignal = raceWithSignal;
@@ -2,6 +2,7 @@ export async function raceWithSignal(promise, signal) {
2
2
  if (signal === undefined) {
3
3
  return promise;
4
4
  }
5
+ let listener;
5
6
  return Promise.race([
6
7
  promise.catch((err) => {
7
8
  if (!signal?.aborted) {
@@ -12,13 +13,14 @@ export async function raceWithSignal(promise, signal) {
12
13
  }
13
14
  }),
14
15
  new Promise((_, reject) => {
15
- signal.addEventListener("abort", () => {
16
+ listener = () => {
16
17
  reject(new Error("Aborted"));
17
- });
18
+ };
19
+ signal.addEventListener("abort", listener);
18
20
  // Must be here inside the promise to avoid a race condition
19
21
  if (signal.aborted) {
20
22
  reject(new Error("Aborted"));
21
23
  }
22
24
  }),
23
- ]);
25
+ ]).finally(() => signal.removeEventListener("abort", listener));
24
26
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langchain/core",
3
- "version": "0.2.22",
3
+ "version": "0.2.24",
4
4
  "description": "Core LangChain.js abstractions and schemas",
5
5
  "type": "module",
6
6
  "engines": {