@langchain/langgraph 0.2.41 → 0.2.43-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 (86) hide show
  1. package/README.md +237 -154
  2. package/dist/channels/any_value.cjs +10 -10
  3. package/dist/channels/any_value.d.ts +1 -1
  4. package/dist/channels/any_value.js +10 -10
  5. package/dist/channels/ephemeral_value.cjs +10 -9
  6. package/dist/channels/ephemeral_value.d.ts +1 -1
  7. package/dist/channels/ephemeral_value.js +10 -9
  8. package/dist/channels/last_value.cjs +8 -7
  9. package/dist/channels/last_value.d.ts +1 -1
  10. package/dist/channels/last_value.js +8 -7
  11. package/dist/constants.cjs +33 -6
  12. package/dist/constants.d.ts +17 -2
  13. package/dist/constants.js +32 -5
  14. package/dist/errors.d.ts +3 -3
  15. package/dist/func/index.cjs +272 -0
  16. package/dist/func/index.d.ts +310 -0
  17. package/dist/func/index.js +267 -0
  18. package/dist/func/types.cjs +15 -0
  19. package/dist/func/types.d.ts +59 -0
  20. package/dist/func/types.js +11 -0
  21. package/dist/graph/graph.cjs +31 -35
  22. package/dist/graph/graph.d.ts +1 -5
  23. package/dist/graph/graph.js +1 -5
  24. package/dist/graph/index.cjs +1 -3
  25. package/dist/graph/index.d.ts +1 -1
  26. package/dist/graph/index.js +1 -1
  27. package/dist/graph/message.d.ts +1 -1
  28. package/dist/graph/state.cjs +17 -17
  29. package/dist/graph/state.d.ts +2 -1
  30. package/dist/graph/state.js +2 -2
  31. package/dist/index.cjs +8 -0
  32. package/dist/index.d.ts +3 -0
  33. package/dist/index.js +3 -0
  34. package/dist/interrupt.cjs +21 -34
  35. package/dist/interrupt.d.ts +1 -1
  36. package/dist/interrupt.js +22 -35
  37. package/dist/prebuilt/agent_executor.cjs +3 -3
  38. package/dist/prebuilt/agent_executor.d.ts +1 -1
  39. package/dist/prebuilt/agent_executor.js +1 -1
  40. package/dist/prebuilt/chat_agent_executor.cjs +3 -3
  41. package/dist/prebuilt/chat_agent_executor.d.ts +1 -1
  42. package/dist/prebuilt/chat_agent_executor.js +1 -1
  43. package/dist/prebuilt/react_agent_executor.cjs +33 -8
  44. package/dist/prebuilt/react_agent_executor.d.ts +4 -1
  45. package/dist/prebuilt/react_agent_executor.js +31 -6
  46. package/dist/prebuilt/tool_node.cjs +1 -2
  47. package/dist/prebuilt/tool_node.d.ts +1 -1
  48. package/dist/prebuilt/tool_node.js +1 -2
  49. package/dist/pregel/algo.cjs +121 -12
  50. package/dist/pregel/algo.d.ts +8 -6
  51. package/dist/pregel/algo.js +122 -13
  52. package/dist/pregel/call.cjs +77 -0
  53. package/dist/pregel/call.d.ts +15 -0
  54. package/dist/pregel/call.js +71 -0
  55. package/dist/pregel/index.cjs +59 -96
  56. package/dist/pregel/index.d.ts +1 -10
  57. package/dist/pregel/index.js +61 -98
  58. package/dist/pregel/io.cjs +6 -1
  59. package/dist/pregel/io.js +7 -2
  60. package/dist/pregel/loop.cjs +109 -75
  61. package/dist/pregel/loop.d.ts +17 -23
  62. package/dist/pregel/loop.js +110 -75
  63. package/dist/pregel/messages.d.ts +1 -1
  64. package/dist/pregel/retry.cjs +22 -50
  65. package/dist/pregel/retry.d.ts +6 -6
  66. package/dist/pregel/retry.js +22 -50
  67. package/dist/pregel/runner.cjs +275 -0
  68. package/dist/pregel/runner.d.ts +64 -0
  69. package/dist/pregel/runner.js +271 -0
  70. package/dist/pregel/stream.cjs +71 -0
  71. package/dist/pregel/stream.d.ts +17 -0
  72. package/dist/pregel/stream.js +67 -0
  73. package/dist/pregel/types.cjs +54 -0
  74. package/dist/pregel/types.d.ts +78 -6
  75. package/dist/pregel/types.js +51 -1
  76. package/dist/pregel/utils/config.cjs +26 -1
  77. package/dist/pregel/utils/config.d.ts +14 -0
  78. package/dist/pregel/utils/config.js +22 -0
  79. package/dist/pregel/write.d.ts +1 -1
  80. package/dist/utils.cjs +15 -1
  81. package/dist/utils.d.ts +3 -1
  82. package/dist/utils.js +12 -0
  83. package/dist/web.cjs +7 -5
  84. package/dist/web.d.ts +4 -4
  85. package/dist/web.js +3 -3
  86. package/package.json +8 -8
@@ -3,9 +3,11 @@ import { mergeConfigs, patchConfig, } from "@langchain/core/runnables";
3
3
  import { copyCheckpoint, uuid5, maxChannelVersion, } from "@langchain/langgraph-checkpoint";
4
4
  import { createCheckpoint, emptyChannels, isBaseChannel, } from "../channels/base.js";
5
5
  import { readChannel, readChannels } from "./io.js";
6
- import { _isSend, _isSendInterface, CONFIG_KEY_CHECKPOINT_MAP, CHECKPOINT_NAMESPACE_SEPARATOR, CONFIG_KEY_CHECKPOINTER, CONFIG_KEY_READ, CONFIG_KEY_TASK_ID, CONFIG_KEY_SEND, INTERRUPT, RESERVED, TAG_HIDDEN, TASKS, CHECKPOINT_NAMESPACE_END, PUSH, PULL, RESUME, NULL_TASK_ID, CONFIG_KEY_SCRATCHPAD, CONFIG_KEY_WRITES, } from "../constants.js";
6
+ import { _isSend, _isSendInterface, CONFIG_KEY_CHECKPOINT_MAP, CHECKPOINT_NAMESPACE_SEPARATOR, CONFIG_KEY_CHECKPOINTER, CONFIG_KEY_READ, CONFIG_KEY_TASK_ID, CONFIG_KEY_SEND, INTERRUPT, RESERVED, TAG_HIDDEN, TASKS, CHECKPOINT_NAMESPACE_END, PUSH, PULL, RESUME, NULL_TASK_ID, CONFIG_KEY_SCRATCHPAD, RETURN, ERROR, NO_WRITES, CONFIG_KEY_PREVIOUS_STATE, PREVIOUS, } from "../constants.js";
7
+ import { isCall, } from "./types.js";
7
8
  import { EmptyChannelError, InvalidUpdateError } from "../errors.js";
8
9
  import { getNullChannelVersion } from "./utils/index.js";
10
+ import { getRunnableForFunc } from "./call.js";
9
11
  export const increment = (current) => {
10
12
  return current !== undefined ? current + 1 : 1;
11
13
  };
@@ -73,7 +75,7 @@ commit, processes, managed,
73
75
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
74
76
  writes) {
75
77
  for (const [chan, value] of writes) {
76
- if (chan === TASKS) {
78
+ if (chan === TASKS && value != null) {
77
79
  if (!_isSend(value)) {
78
80
  throw new InvalidUpdateError(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(value)}`);
79
81
  }
@@ -86,7 +88,14 @@ writes) {
86
88
  }
87
89
  commit(writes);
88
90
  }
89
- const IGNORE = new Set([PUSH, RESUME, INTERRUPT]);
91
+ const IGNORE = new Set([
92
+ NO_WRITES,
93
+ PUSH,
94
+ RESUME,
95
+ INTERRUPT,
96
+ RETURN,
97
+ ERROR,
98
+ ]);
90
99
  export function _applyWrites(checkpoint, channels, tasks,
91
100
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
92
101
  getNextVersion) {
@@ -251,7 +260,84 @@ export function _prepareSingleTask(taskPath, checkpoint, pendingWrites, processe
251
260
  const { step, checkpointer, manager } = extra;
252
261
  const configurable = config.configurable ?? {};
253
262
  const parentNamespace = configurable.checkpoint_ns ?? "";
254
- if (taskPath[0] === PUSH) {
263
+ if (taskPath[0] === PUSH && isCall(taskPath[taskPath.length - 1])) {
264
+ const call = taskPath[taskPath.length - 1];
265
+ const proc = getRunnableForFunc(call.name, call.func);
266
+ const triggers = [PUSH];
267
+ const checkpointNamespace = parentNamespace === ""
268
+ ? call.name
269
+ : `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${call.name}`;
270
+ const id = uuid5(JSON.stringify([
271
+ checkpointNamespace,
272
+ step.toString(),
273
+ call.name,
274
+ PUSH,
275
+ taskPath[1],
276
+ taskPath[2],
277
+ ]), checkpoint.id);
278
+ const taskCheckpointNamespace = `${checkpointNamespace}${CHECKPOINT_NAMESPACE_END}${id}`;
279
+ const metadata = {
280
+ langgraph_step: step,
281
+ langgraph_node: call.name,
282
+ langgraph_triggers: triggers,
283
+ langgraph_path: taskPath.slice(0, 3),
284
+ langgraph_checkpoint_ns: taskCheckpointNamespace,
285
+ };
286
+ if (forExecution) {
287
+ const writes = [];
288
+ const task = {
289
+ name: call.name,
290
+ input: call.input,
291
+ proc,
292
+ writes,
293
+ config: patchConfig(mergeConfigs(config, {
294
+ metadata,
295
+ store: extra.store ?? config.store,
296
+ }), {
297
+ runName: call.name,
298
+ callbacks: manager?.getChild(`graph:step:${step}`),
299
+ configurable: {
300
+ [CONFIG_KEY_TASK_ID]: id,
301
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
302
+ [CONFIG_KEY_SEND]: (writes_) => _localWrite(step, (items) => writes.push(...items), processes, managed, writes_),
303
+ [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(step, checkpoint, channels, managed, {
304
+ name: call.name,
305
+ writes: writes,
306
+ triggers,
307
+ path: taskPath.slice(0, 3),
308
+ }, select_, fresh_),
309
+ [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable[CONFIG_KEY_CHECKPOINTER],
310
+ [CONFIG_KEY_CHECKPOINT_MAP]: {
311
+ ...configurable[CONFIG_KEY_CHECKPOINT_MAP],
312
+ [parentNamespace]: checkpoint.id,
313
+ },
314
+ [CONFIG_KEY_SCRATCHPAD]: _scratchpad([
315
+ ...(pendingWrites || []),
316
+ ...(configurable[CONFIG_KEY_SCRATCHPAD]?.resume || []).map((v) => [id, RESUME, v]),
317
+ ], id),
318
+ [CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS],
319
+ checkpoint_id: undefined,
320
+ checkpoint_ns: taskCheckpointNamespace,
321
+ },
322
+ }),
323
+ triggers,
324
+ retry_policy: call.retry,
325
+ id,
326
+ path: taskPath.slice(0, 3),
327
+ writers: [],
328
+ };
329
+ return task;
330
+ }
331
+ else {
332
+ return {
333
+ id,
334
+ name: call.name,
335
+ interrupts: [],
336
+ path: taskPath.slice(0, 3),
337
+ };
338
+ }
339
+ }
340
+ else if (taskPath[0] === PUSH) {
255
341
  const index = typeof taskPath[1] === "number"
256
342
  ? taskPath[1]
257
343
  : parseInt(taskPath[1], 10);
@@ -323,11 +409,15 @@ export function _prepareSingleTask(taskPath, checkpoint, pendingWrites, processe
323
409
  ...configurable[CONFIG_KEY_CHECKPOINT_MAP],
324
410
  [parentNamespace]: checkpoint.id,
325
411
  },
326
- [CONFIG_KEY_WRITES]: [
412
+ [CONFIG_KEY_SCRATCHPAD]: _scratchpad([
327
413
  ...(pendingWrites || []),
328
- ...(configurable[CONFIG_KEY_WRITES] || []),
329
- ].filter((w) => w[0] === NULL_TASK_ID || w[0] === taskId),
330
- [CONFIG_KEY_SCRATCHPAD]: {},
414
+ ...(configurable[CONFIG_KEY_SCRATCHPAD]?.resume || []).map((v) => [
415
+ taskId,
416
+ RESUME,
417
+ v,
418
+ ]),
419
+ ], taskId),
420
+ [CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS],
331
421
  checkpoint_id: undefined,
332
422
  checkpoint_ns: taskCheckpointNamespace,
333
423
  },
@@ -341,7 +431,12 @@ export function _prepareSingleTask(taskPath, checkpoint, pendingWrites, processe
341
431
  }
342
432
  }
343
433
  else {
344
- return { id: taskId, name: packet.node, interrupts: [], path: taskPath };
434
+ return {
435
+ id: taskId,
436
+ name: packet.node,
437
+ interrupts: [],
438
+ path: taskPath,
439
+ };
345
440
  }
346
441
  }
347
442
  else if (taskPath[0] === PULL) {
@@ -429,11 +524,15 @@ export function _prepareSingleTask(taskPath, checkpoint, pendingWrites, processe
429
524
  ...configurable[CONFIG_KEY_CHECKPOINT_MAP],
430
525
  [parentNamespace]: checkpoint.id,
431
526
  },
432
- [CONFIG_KEY_WRITES]: [
527
+ [CONFIG_KEY_SCRATCHPAD]: _scratchpad([
433
528
  ...(pendingWrites || []),
434
- ...(configurable[CONFIG_KEY_WRITES] || []),
435
- ].filter((w) => w[0] === NULL_TASK_ID || w[0] === taskId),
436
- [CONFIG_KEY_SCRATCHPAD]: {},
529
+ ...(configurable[CONFIG_KEY_SCRATCHPAD]?.resume || []).map((v) => [
530
+ taskId,
531
+ RESUME,
532
+ v,
533
+ ]),
534
+ ], taskId),
535
+ [CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS],
437
536
  checkpoint_id: undefined,
438
537
  checkpoint_ns: taskCheckpointNamespace,
439
538
  },
@@ -523,3 +622,13 @@ function _procInput(step, proc, managed, channels, forExecution) {
523
622
  }
524
623
  return val;
525
624
  }
625
+ function _scratchpad(pendingWrites, taskId) {
626
+ return {
627
+ callCounter: 0,
628
+ interruptCounter: -1,
629
+ resume: pendingWrites
630
+ .filter(([writeTaskId, chan]) => writeTaskId === taskId && chan === RESUME)
631
+ .flatMap(([_writeTaskId, _chan, resume]) => resume),
632
+ nullResume: pendingWrites.find(([writeTaskId, chan]) => writeTaskId === NULL_TASK_ID && chan === RESUME)?.[2],
633
+ };
634
+ }
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.call = exports.getRunnableForEntrypoint = exports.getRunnableForFunc = void 0;
4
+ const runnables_1 = require("@langchain/core/runnables");
5
+ const singletons_1 = require("@langchain/core/singletons");
6
+ const constants_js_1 = require("../constants.cjs");
7
+ const write_js_1 = require("./write.cjs");
8
+ const utils_js_1 = require("../utils.cjs");
9
+ const types_js_1 = require("../func/types.cjs");
10
+ /**
11
+ * Wraps a user function in a Runnable that writes the returned value to the RETURN channel.
12
+ */
13
+ function getRunnableForFunc(name, func) {
14
+ const run = new utils_js_1.RunnableCallable({
15
+ func: (input) => func(...input),
16
+ name,
17
+ trace: false,
18
+ recurse: false,
19
+ });
20
+ return new runnables_1.RunnableSequence({
21
+ name,
22
+ first: run,
23
+ last: new write_js_1.ChannelWrite([{ channel: constants_js_1.RETURN, value: write_js_1.PASSTHROUGH }], [constants_js_1.TAG_HIDDEN]),
24
+ });
25
+ }
26
+ exports.getRunnableForFunc = getRunnableForFunc;
27
+ function getRunnableForEntrypoint(name, func) {
28
+ const run = new utils_js_1.RunnableCallable({
29
+ func: (input, config) => {
30
+ return func(input, config);
31
+ },
32
+ name,
33
+ trace: false,
34
+ recurse: false,
35
+ });
36
+ return new runnables_1.RunnableSequence({
37
+ name,
38
+ first: run,
39
+ middle: [
40
+ new write_js_1.ChannelWrite([
41
+ {
42
+ channel: constants_js_1.END,
43
+ value: write_js_1.PASSTHROUGH,
44
+ mapper: new utils_js_1.RunnableCallable({
45
+ func: (value) => ((0, types_js_1.isEntrypointFinal)(value) ? value.value : value),
46
+ }),
47
+ },
48
+ ], [constants_js_1.TAG_HIDDEN]),
49
+ new write_js_1.ChannelWrite([
50
+ {
51
+ channel: constants_js_1.PREVIOUS,
52
+ value: write_js_1.PASSTHROUGH,
53
+ mapper: new utils_js_1.RunnableCallable({
54
+ func: (value) => {
55
+ return (0, types_js_1.isEntrypointFinal)(value) ? value.save : value;
56
+ },
57
+ }),
58
+ },
59
+ ]),
60
+ ],
61
+ last: new utils_js_1.RunnableCallable({
62
+ func: (final) => (0, types_js_1.isEntrypointFinal)(final) ? final.value : final,
63
+ }),
64
+ });
65
+ }
66
+ exports.getRunnableForEntrypoint = getRunnableForEntrypoint;
67
+ function call({ func, name, retry }, ...args) {
68
+ const config = singletons_1.AsyncLocalStorageProviderSingleton.getRunnableConfig();
69
+ if (typeof config.configurable?.[constants_js_1.CONFIG_KEY_CALL] === "function") {
70
+ return config.configurable[constants_js_1.CONFIG_KEY_CALL](func, name, args, {
71
+ retry,
72
+ callbacks: config.callbacks,
73
+ });
74
+ }
75
+ throw new Error("Async local storage not initialized. Please call initializeAsyncLocalStorageSingleton() before using this function.");
76
+ }
77
+ exports.call = call;
@@ -0,0 +1,15 @@
1
+ import { Runnable } from "@langchain/core/runnables";
2
+ import { RetryPolicy } from "./utils/index.js";
3
+ import { EntrypointFunc, EntrypointReturnT, TaskFunc } from "../func/types.js";
4
+ import { LangGraphRunnableConfig } from "./runnable_types.js";
5
+ /**
6
+ * Wraps a user function in a Runnable that writes the returned value to the RETURN channel.
7
+ */
8
+ export declare function getRunnableForFunc<ArgsT extends unknown[], OutputT>(name: string, func: TaskFunc<ArgsT, OutputT>): Runnable<ArgsT, OutputT, LangGraphRunnableConfig>;
9
+ export declare function getRunnableForEntrypoint<InputT, OutputT>(name: string, func: EntrypointFunc<InputT, OutputT>): Runnable<InputT, EntrypointReturnT<OutputT>, LangGraphRunnableConfig>;
10
+ export type CallWrapperOptions<ArgsT extends unknown[], OutputT> = {
11
+ func: TaskFunc<ArgsT, OutputT>;
12
+ name: string;
13
+ retry?: RetryPolicy;
14
+ };
15
+ export declare function call<ArgsT extends unknown[], OutputT>({ func, name, retry }: CallWrapperOptions<ArgsT, OutputT>, ...args: ArgsT): Promise<OutputT>;
@@ -0,0 +1,71 @@
1
+ import { RunnableSequence, } from "@langchain/core/runnables";
2
+ import { AsyncLocalStorageProviderSingleton } from "@langchain/core/singletons";
3
+ import { CONFIG_KEY_CALL, END, PREVIOUS, RETURN, TAG_HIDDEN, } from "../constants.js";
4
+ import { ChannelWrite, PASSTHROUGH } from "./write.js";
5
+ import { RunnableCallable } from "../utils.js";
6
+ import { isEntrypointFinal, } from "../func/types.js";
7
+ /**
8
+ * Wraps a user function in a Runnable that writes the returned value to the RETURN channel.
9
+ */
10
+ export function getRunnableForFunc(name, func) {
11
+ const run = new RunnableCallable({
12
+ func: (input) => func(...input),
13
+ name,
14
+ trace: false,
15
+ recurse: false,
16
+ });
17
+ return new RunnableSequence({
18
+ name,
19
+ first: run,
20
+ last: new ChannelWrite([{ channel: RETURN, value: PASSTHROUGH }], [TAG_HIDDEN]),
21
+ });
22
+ }
23
+ export function getRunnableForEntrypoint(name, func) {
24
+ const run = new RunnableCallable({
25
+ func: (input, config) => {
26
+ return func(input, config);
27
+ },
28
+ name,
29
+ trace: false,
30
+ recurse: false,
31
+ });
32
+ return new RunnableSequence({
33
+ name,
34
+ first: run,
35
+ middle: [
36
+ new ChannelWrite([
37
+ {
38
+ channel: END,
39
+ value: PASSTHROUGH,
40
+ mapper: new RunnableCallable({
41
+ func: (value) => (isEntrypointFinal(value) ? value.value : value),
42
+ }),
43
+ },
44
+ ], [TAG_HIDDEN]),
45
+ new ChannelWrite([
46
+ {
47
+ channel: PREVIOUS,
48
+ value: PASSTHROUGH,
49
+ mapper: new RunnableCallable({
50
+ func: (value) => {
51
+ return isEntrypointFinal(value) ? value.save : value;
52
+ },
53
+ }),
54
+ },
55
+ ]),
56
+ ],
57
+ last: new RunnableCallable({
58
+ func: (final) => isEntrypointFinal(final) ? final.value : final,
59
+ }),
60
+ });
61
+ }
62
+ export function call({ func, name, retry }, ...args) {
63
+ const config = AsyncLocalStorageProviderSingleton.getRunnableConfig();
64
+ if (typeof config.configurable?.[CONFIG_KEY_CALL] === "function") {
65
+ return config.configurable[CONFIG_KEY_CALL](func, name, args, {
66
+ retry,
67
+ callbacks: config.callbacks,
68
+ });
69
+ }
70
+ throw new Error("Async local storage not initialized. Please call initializeAsyncLocalStorageSingleton() before using this function.");
71
+ }
@@ -16,11 +16,12 @@ const algo_js_1 = require("./algo.cjs");
16
16
  const index_js_1 = require("./utils/index.cjs");
17
17
  const subgraph_js_1 = require("./utils/subgraph.cjs");
18
18
  const loop_js_1 = require("./loop.cjs");
19
- const retry_js_1 = require("./retry.cjs");
20
19
  const base_js_2 = require("../managed/base.cjs");
21
20
  const utils_js_1 = require("../utils.cjs");
22
21
  const config_js_1 = require("./utils/config.cjs");
23
22
  const messages_js_1 = require("./messages.cjs");
23
+ const runner_js_1 = require("./runner.cjs");
24
+ const stream_js_1 = require("./stream.cjs");
24
25
  function isString(value) {
25
26
  return typeof value === "string";
26
27
  }
@@ -824,92 +825,6 @@ class Pregel extends runnables_1.Runnable {
824
825
  managed,
825
826
  };
826
827
  }
827
- async _runLoop(params) {
828
- const { loop, interruptAfter, interruptBefore, runManager, debug, config } = params;
829
- let tickError;
830
- try {
831
- while (await loop.tick({
832
- inputKeys: this.inputChannels,
833
- interruptAfter,
834
- interruptBefore,
835
- manager: runManager,
836
- })) {
837
- if (debug) {
838
- (0, debug_js_1.printStepCheckpoint)(loop.checkpointMetadata.step, loop.channels, this.streamChannelsList);
839
- }
840
- if (debug) {
841
- (0, debug_js_1.printStepTasks)(loop.step, Object.values(loop.tasks));
842
- }
843
- // execute tasks, and wait for one to fail or all to finish.
844
- // each task is independent from all other concurrent tasks
845
- // yield updates/debug output as each task finishes
846
- const taskStream = (0, retry_js_1.executeTasksWithRetry)(Object.values(loop.tasks).filter((task) => task.writes.length === 0), {
847
- stepTimeout: this.stepTimeout,
848
- signal: config.signal,
849
- retryPolicy: this.retryPolicy,
850
- });
851
- let graphInterrupt;
852
- for await (const { task, error } of taskStream) {
853
- if (error !== undefined) {
854
- if ((0, errors_js_1.isGraphBubbleUp)(error)) {
855
- if (loop.isNested) {
856
- throw error;
857
- }
858
- if ((0, errors_js_1.isGraphInterrupt)(error)) {
859
- graphInterrupt = error;
860
- if (error.interrupts.length) {
861
- const interrupts = error.interrupts.map((interrupt) => [constants_js_1.INTERRUPT, interrupt]);
862
- const resumes = task.writes.filter((w) => w[0] === constants_js_1.RESUME);
863
- if (resumes.length) {
864
- interrupts.push(...resumes);
865
- }
866
- loop.putWrites(task.id, interrupts);
867
- }
868
- }
869
- }
870
- else {
871
- loop.putWrites(task.id, [
872
- [constants_js_1.ERROR, { message: error.message, name: error.name }],
873
- ]);
874
- throw error;
875
- }
876
- }
877
- else {
878
- loop.putWrites(task.id, task.writes);
879
- }
880
- }
881
- if (debug) {
882
- (0, debug_js_1.printStepWrites)(loop.step, Object.values(loop.tasks)
883
- .map((task) => task.writes)
884
- .flat(), this.streamChannelsList);
885
- }
886
- if (graphInterrupt !== undefined) {
887
- throw graphInterrupt;
888
- }
889
- }
890
- if (loop.status === "out_of_steps") {
891
- throw new errors_js_1.GraphRecursionError([
892
- `Recursion limit of ${config.recursionLimit} reached`,
893
- "without hitting a stop condition. You can increase the",
894
- `limit by setting the "recursionLimit" config key.`,
895
- ].join(" "), {
896
- lc_error_code: "GRAPH_RECURSION_LIMIT",
897
- });
898
- }
899
- }
900
- catch (e) {
901
- tickError = e;
902
- const suppress = await loop.finishAndHandleError(tickError);
903
- if (!suppress) {
904
- throw e;
905
- }
906
- }
907
- finally {
908
- if (tickError === undefined) {
909
- await loop.finishAndHandleError();
910
- }
911
- }
912
- }
913
828
  async *_streamIterator(input, options) {
914
829
  const streamSubgraphs = options?.subgraphs;
915
830
  const inputConfig = (0, config_js_1.ensureLangGraphConfig)(this.config, options);
@@ -925,7 +840,7 @@ class Pregel extends runnables_1.Runnable {
925
840
  const { runId, ...restConfig } = inputConfig;
926
841
  // assign defaults
927
842
  const [debug, streamMode, , outputKeys, config, interruptBefore, interruptAfter, checkpointer, store, streamModeSingle,] = this._defaults(restConfig);
928
- const stream = new loop_js_1.IterableReadableWritableStream({
843
+ const stream = new stream_js_1.IterableReadableWritableStream({
929
844
  modes: new Set(streamMode),
930
845
  });
931
846
  // set up messages stream mode
@@ -974,6 +889,14 @@ class Pregel extends runnables_1.Runnable {
974
889
  streamKeys: this.streamChannelsAsIs,
975
890
  store,
976
891
  stream,
892
+ interruptAfter,
893
+ interruptBefore,
894
+ manager: runManager,
895
+ debug: this.debug,
896
+ });
897
+ const runner = new runner_js_1.PregelRunner({
898
+ loop,
899
+ nodeFinished: config.configurable?.nodeFinished,
977
900
  });
978
901
  if (options?.subgraphs) {
979
902
  loop.config.configurable = {
@@ -981,14 +904,7 @@ class Pregel extends runnables_1.Runnable {
981
904
  [constants_js_1.CONFIG_KEY_STREAM]: loop.stream,
982
905
  };
983
906
  }
984
- await this._runLoop({
985
- loop,
986
- interruptAfter,
987
- interruptBefore,
988
- runManager,
989
- debug,
990
- config,
991
- });
907
+ await this._runLoop({ loop, runner, debug, config });
992
908
  }
993
909
  catch (e) {
994
910
  loopError = e;
@@ -1086,5 +1002,52 @@ class Pregel extends runnables_1.Runnable {
1086
1002
  }
1087
1003
  return chunks;
1088
1004
  }
1005
+ async _runLoop(params) {
1006
+ const { loop, runner, debug, config } = params;
1007
+ let tickError;
1008
+ try {
1009
+ while (await loop.tick({
1010
+ inputKeys: this.inputChannels,
1011
+ })) {
1012
+ if (debug) {
1013
+ (0, debug_js_1.printStepCheckpoint)(loop.checkpointMetadata.step, loop.channels, this.streamChannelsList);
1014
+ }
1015
+ if (debug) {
1016
+ (0, debug_js_1.printStepTasks)(loop.step, Object.values(loop.tasks));
1017
+ }
1018
+ await runner.tick({
1019
+ timeout: this.stepTimeout,
1020
+ retryPolicy: this.retryPolicy,
1021
+ onStepWrite: (step, writes) => {
1022
+ if (debug) {
1023
+ (0, debug_js_1.printStepWrites)(step, writes, this.streamChannelsList);
1024
+ }
1025
+ },
1026
+ signal: config.signal,
1027
+ });
1028
+ }
1029
+ if (loop.status === "out_of_steps") {
1030
+ throw new errors_js_1.GraphRecursionError([
1031
+ `Recursion limit of ${config.recursionLimit} reached`,
1032
+ "without hitting a stop condition. You can increase the",
1033
+ `limit by setting the "recursionLimit" config key.`,
1034
+ ].join(" "), {
1035
+ lc_error_code: "GRAPH_RECURSION_LIMIT",
1036
+ });
1037
+ }
1038
+ }
1039
+ catch (e) {
1040
+ tickError = e;
1041
+ const suppress = await loop.finishAndHandleError(tickError);
1042
+ if (!suppress) {
1043
+ throw e;
1044
+ }
1045
+ }
1046
+ finally {
1047
+ if (tickError === undefined) {
1048
+ await loop.finishAndHandleError();
1049
+ }
1050
+ }
1051
+ }
1089
1052
  }
1090
1053
  exports.Pregel = Pregel;
@@ -1,6 +1,5 @@
1
1
  import { Runnable, RunnableConfig, RunnableFunc } from "@langchain/core/runnables";
2
2
  import { IterableReadableStream } from "@langchain/core/utils/stream";
3
- import type { CallbackManagerForChainRun } from "@langchain/core/callbacks/manager";
4
3
  import { All, BaseCheckpointSaver, BaseStore, CheckpointListOptions, CheckpointTuple } from "@langchain/langgraph-checkpoint";
5
4
  import { BaseChannel } from "../channels/base.js";
6
5
  import { PregelNode } from "./read.js";
@@ -9,7 +8,6 @@ import { Command } from "../constants.js";
9
8
  import { PregelInterface, PregelParams, StateSnapshot, StreamMode, PregelInputType, PregelOutputType, PregelOptions } from "./types.js";
10
9
  import { StrRecord } from "./algo.js";
11
10
  import { RetryPolicy } from "./utils/index.js";
12
- import { PregelLoop } from "./loop.js";
13
11
  import { ManagedValueMapping, type ManagedValueSpec } from "../managed/base.js";
14
12
  import { LangGraphRunnableConfig } from "./runnable_types.js";
15
13
  type WriteValue = Runnable | RunnableFunc<unknown, unknown> | unknown;
@@ -112,14 +110,6 @@ export declare class Pregel<Nn extends StrRecord<string, PregelNode>, Cc extends
112
110
  channelSpecs: Record<string, BaseChannel<unknown, unknown, unknown>>;
113
111
  managed: ManagedValueMapping;
114
112
  }>;
115
- _runLoop(params: {
116
- loop: PregelLoop;
117
- interruptAfter: string[] | "*";
118
- interruptBefore: string[] | "*";
119
- runManager?: CallbackManagerForChainRun;
120
- debug: boolean;
121
- config: LangGraphRunnableConfig;
122
- }): Promise<void>;
123
113
  _streamIterator(input: PregelInputType | Command, options?: Partial<PregelOptions<Nn, Cc>>): AsyncGenerator<PregelOutputType>;
124
114
  /**
125
115
  * Run the graph with a single input and config.
@@ -137,4 +127,5 @@ export declare class Pregel<Nn extends StrRecord<string, PregelNode>, Cc extends
137
127
  * @param options.debug Whether to print debug information during execution.
138
128
  */
139
129
  invoke(input: InputType | Command | null, options?: Partial<PregelOptions<Nn, Cc, ConfigurableFieldType>>): Promise<OutputType>;
130
+ private _runLoop;
140
131
  }