@langchain/langgraph 0.0.11 → 0.0.13

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 (134) hide show
  1. package/dist/channels/any_value.cjs +57 -0
  2. package/dist/channels/any_value.d.ts +16 -0
  3. package/dist/channels/any_value.js +53 -0
  4. package/dist/channels/base.cjs +19 -28
  5. package/dist/channels/base.d.ts +13 -19
  6. package/dist/channels/base.js +17 -24
  7. package/dist/channels/binop.cjs +4 -3
  8. package/dist/channels/binop.d.ts +1 -1
  9. package/dist/channels/binop.js +3 -2
  10. package/dist/channels/dynamic_barrier_value.cjs +88 -0
  11. package/dist/channels/dynamic_barrier_value.d.ts +26 -0
  12. package/dist/channels/dynamic_barrier_value.js +84 -0
  13. package/dist/channels/ephemeral_value.cjs +64 -0
  14. package/dist/channels/ephemeral_value.d.ts +14 -0
  15. package/dist/channels/ephemeral_value.js +60 -0
  16. package/dist/channels/index.cjs +1 -3
  17. package/dist/channels/index.d.ts +1 -1
  18. package/dist/channels/index.js +1 -1
  19. package/dist/channels/last_value.cjs +11 -5
  20. package/dist/channels/last_value.d.ts +5 -1
  21. package/dist/channels/last_value.js +9 -3
  22. package/dist/channels/named_barrier_value.cjs +71 -0
  23. package/dist/channels/named_barrier_value.d.ts +18 -0
  24. package/dist/channels/named_barrier_value.js +66 -0
  25. package/dist/channels/topic.cjs +5 -3
  26. package/dist/channels/topic.d.ts +3 -3
  27. package/dist/channels/topic.js +5 -3
  28. package/dist/checkpoint/base.cjs +30 -12
  29. package/dist/checkpoint/base.d.ts +39 -22
  30. package/dist/checkpoint/base.js +28 -11
  31. package/dist/checkpoint/id.cjs +40 -0
  32. package/dist/checkpoint/id.d.ts +2 -0
  33. package/dist/checkpoint/id.js +35 -0
  34. package/dist/checkpoint/index.cjs +2 -2
  35. package/dist/checkpoint/index.d.ts +2 -2
  36. package/dist/checkpoint/index.js +2 -2
  37. package/dist/checkpoint/memory.cjs +63 -49
  38. package/dist/checkpoint/memory.d.ts +7 -10
  39. package/dist/checkpoint/memory.js +62 -47
  40. package/dist/checkpoint/sqlite.cjs +170 -0
  41. package/dist/checkpoint/sqlite.d.ts +14 -0
  42. package/dist/checkpoint/sqlite.js +163 -0
  43. package/dist/constants.cjs +3 -1
  44. package/dist/constants.d.ts +2 -0
  45. package/dist/constants.js +2 -0
  46. package/dist/errors.cjs +31 -0
  47. package/dist/errors.d.ts +12 -0
  48. package/dist/errors.js +24 -0
  49. package/dist/graph/graph.cjs +234 -96
  50. package/dist/graph/graph.d.ts +52 -23
  51. package/dist/graph/graph.js +233 -97
  52. package/dist/graph/index.cjs +2 -2
  53. package/dist/graph/index.d.ts +2 -2
  54. package/dist/graph/index.js +2 -2
  55. package/dist/graph/message.cjs +4 -3
  56. package/dist/graph/message.d.ts +4 -1
  57. package/dist/graph/message.js +4 -3
  58. package/dist/graph/state.cjs +237 -102
  59. package/dist/graph/state.d.ts +41 -18
  60. package/dist/graph/state.js +238 -104
  61. package/dist/index.cjs +6 -2
  62. package/dist/index.d.ts +3 -2
  63. package/dist/index.js +2 -1
  64. package/dist/prebuilt/agent_executor.cjs +22 -36
  65. package/dist/prebuilt/agent_executor.d.ts +7 -10
  66. package/dist/prebuilt/agent_executor.js +23 -37
  67. package/dist/prebuilt/chat_agent_executor.cjs +13 -13
  68. package/dist/prebuilt/chat_agent_executor.d.ts +3 -1
  69. package/dist/prebuilt/chat_agent_executor.js +15 -15
  70. package/dist/prebuilt/index.cjs +4 -1
  71. package/dist/prebuilt/index.d.ts +1 -0
  72. package/dist/prebuilt/index.js +1 -0
  73. package/dist/prebuilt/tool_node.cjs +59 -0
  74. package/dist/prebuilt/tool_node.d.ts +17 -0
  75. package/dist/prebuilt/tool_node.js +54 -0
  76. package/dist/pregel/debug.cjs +6 -8
  77. package/dist/pregel/debug.d.ts +2 -2
  78. package/dist/pregel/debug.js +5 -7
  79. package/dist/pregel/index.cjs +406 -236
  80. package/dist/pregel/index.d.ts +77 -41
  81. package/dist/pregel/index.js +408 -241
  82. package/dist/pregel/io.cjs +117 -30
  83. package/dist/pregel/io.d.ts +11 -3
  84. package/dist/pregel/io.js +111 -28
  85. package/dist/pregel/read.cjs +126 -46
  86. package/dist/pregel/read.d.ts +27 -18
  87. package/dist/pregel/read.js +125 -45
  88. package/dist/pregel/types.cjs +2 -0
  89. package/dist/pregel/types.d.ts +32 -0
  90. package/dist/pregel/types.js +1 -0
  91. package/dist/pregel/validate.cjs +58 -51
  92. package/dist/pregel/validate.d.ts +14 -13
  93. package/dist/pregel/validate.js +56 -50
  94. package/dist/pregel/write.cjs +46 -30
  95. package/dist/pregel/write.d.ts +18 -8
  96. package/dist/pregel/write.js +45 -29
  97. package/dist/serde/base.cjs +2 -0
  98. package/dist/serde/base.d.ts +4 -0
  99. package/dist/serde/base.js +1 -0
  100. package/dist/setup/async_local_storage.cjs +2 -2
  101. package/dist/setup/async_local_storage.js +1 -1
  102. package/dist/tests/channels.test.d.ts +1 -0
  103. package/dist/tests/channels.test.js +151 -0
  104. package/dist/tests/chatbot.int.test.d.ts +1 -0
  105. package/dist/tests/chatbot.int.test.js +61 -0
  106. package/dist/tests/checkpoints.test.d.ts +1 -0
  107. package/dist/tests/checkpoints.test.js +190 -0
  108. package/dist/tests/graph.test.d.ts +1 -0
  109. package/dist/tests/graph.test.js +15 -0
  110. package/dist/tests/prebuilt.int.test.d.ts +1 -0
  111. package/dist/tests/prebuilt.int.test.js +101 -0
  112. package/dist/tests/prebuilt.test.d.ts +1 -0
  113. package/dist/tests/prebuilt.test.js +195 -0
  114. package/dist/tests/pregel.io.test.d.ts +1 -0
  115. package/dist/tests/pregel.io.test.js +332 -0
  116. package/dist/tests/pregel.read.test.d.ts +1 -0
  117. package/dist/tests/pregel.read.test.js +109 -0
  118. package/dist/tests/pregel.test.d.ts +1 -0
  119. package/dist/tests/pregel.test.js +1879 -0
  120. package/dist/tests/pregel.validate.test.d.ts +1 -0
  121. package/dist/tests/pregel.validate.test.js +198 -0
  122. package/dist/tests/pregel.write.test.d.ts +1 -0
  123. package/dist/tests/pregel.write.test.js +44 -0
  124. package/dist/tests/tracing.int.test.d.ts +1 -0
  125. package/dist/tests/tracing.int.test.js +449 -0
  126. package/dist/tests/utils.d.ts +22 -0
  127. package/dist/tests/utils.js +76 -0
  128. package/dist/utils.cjs +74 -0
  129. package/dist/utils.d.ts +18 -0
  130. package/dist/utils.js +70 -0
  131. package/package.json +12 -8
  132. package/dist/pregel/reserved.cjs +0 -6
  133. package/dist/pregel/reserved.d.ts +0 -3
  134. package/dist/pregel/reserved.js +0 -3
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Pregel = exports.Channel = exports.GraphRecursionError = void 0;
3
+ exports._prepareNextTasks = exports._applyWrites = exports._localRead = exports._shouldInterrupt = exports.Pregel = exports.Channel = void 0;
4
4
  /* eslint-disable no-param-reassign */
5
5
  const runnables_1 = require("@langchain/core/runnables");
6
6
  const stream_1 = require("@langchain/core/utils/stream");
@@ -8,80 +8,67 @@ const base_js_1 = require("../channels/base.cjs");
8
8
  const base_js_2 = require("../checkpoint/base.cjs");
9
9
  const read_js_1 = require("./read.cjs");
10
10
  const validate_js_1 = require("./validate.cjs");
11
- const reserved_js_1 = require("./reserved.cjs");
12
11
  const io_js_1 = require("./io.cjs");
13
12
  const write_js_1 = require("./write.cjs");
14
13
  const constants_js_1 = require("../constants.cjs");
15
14
  const async_local_storage_js_1 = require("../setup/async_local_storage.cjs");
16
- const DEFAULT_RECURSION_LIMIT = 25;
17
- class GraphRecursionError extends Error {
18
- constructor(message) {
19
- super(message);
20
- this.name = "GraphRecursionError";
21
- }
22
- }
23
- exports.GraphRecursionError = GraphRecursionError;
24
- function _coerceWriteValue(value) {
25
- if (!runnables_1.Runnable.isRunnable(value) && typeof value !== "function") {
26
- return (0, runnables_1._coerceToRunnable)(() => value);
27
- }
28
- return (0, runnables_1._coerceToRunnable)(value);
29
- }
15
+ const errors_js_1 = require("../errors.cjs");
16
+ const DEFAULT_LOOP_LIMIT = 25;
30
17
  function isString(value) {
31
18
  return typeof value === "string";
32
19
  }
33
20
  class Channel {
34
21
  static subscribeTo(channels, options) {
35
- const { key, when, tags } = options ?? {};
22
+ const { key, tags } = options ?? {};
36
23
  if (Array.isArray(channels) && key !== undefined) {
37
24
  throw new Error("Can't specify a key when subscribing to multiple channels");
38
25
  }
39
- let channelMappingOrString;
26
+ let channelMappingOrArray;
40
27
  if (isString(channels)) {
41
28
  if (key) {
42
- channelMappingOrString = { [key]: channels };
29
+ channelMappingOrArray = { [key]: channels };
43
30
  }
44
31
  else {
45
- channelMappingOrString = channels;
32
+ channelMappingOrArray = [channels];
46
33
  }
47
34
  }
48
35
  else {
49
- channelMappingOrString = Object.fromEntries(channels.map((chan) => [chan, chan]));
36
+ channelMappingOrArray = Object.fromEntries(channels.map((chan) => [chan, chan]));
50
37
  }
51
38
  const triggers = Array.isArray(channels) ? channels : [channels];
52
- return new read_js_1.ChannelInvoke({
53
- channels: channelMappingOrString,
39
+ return new read_js_1.PregelNode({
40
+ channels: channelMappingOrArray,
54
41
  triggers,
55
- when,
56
42
  tags,
57
43
  });
58
44
  }
59
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
60
- static writeTo(...args) {
61
- // const channelPairs: Array<[string, WriteValue<RunInput, RunOutput>]> =
62
- // channels.map((c) => [c, undefined]);
63
- // return new ChannelWrite<RunInput, RunOutput>(channelPairs);
64
- const channelPairs = [];
65
- if (args.length === 1 && typeof args[0] === "object") {
66
- // Handle the case where named arguments are passed as an object
67
- const additionalArgs = args[0];
68
- Object.entries(additionalArgs).forEach(([key, value]) => {
69
- channelPairs.push([key, _coerceWriteValue(value)]);
45
+ static writeTo(channels, kwargs) {
46
+ const channelWriteEntries = [];
47
+ for (const channel of channels) {
48
+ channelWriteEntries.push({
49
+ channel,
50
+ value: write_js_1.PASSTHROUGH,
51
+ skipNone: false,
70
52
  });
71
53
  }
72
- else {
73
- args.forEach((channel) => {
74
- if (typeof channel === "string") {
75
- channelPairs.push([channel, undefined]);
76
- }
77
- else if (typeof channel === "object") {
78
- Object.entries(channel).forEach(([key, value]) => {
79
- channelPairs.push([key, _coerceWriteValue(value)]);
80
- });
81
- }
82
- });
54
+ for (const [key, value] of Object.entries(kwargs ?? {})) {
55
+ if (runnables_1.Runnable.isRunnable(value) || typeof value === "function") {
56
+ channelWriteEntries.push({
57
+ channel: key,
58
+ value: write_js_1.PASSTHROUGH,
59
+ skipNone: true,
60
+ mapper: (0, runnables_1._coerceToRunnable)(value),
61
+ });
62
+ }
63
+ else {
64
+ channelWriteEntries.push({
65
+ channel: key,
66
+ value,
67
+ skipNone: false,
68
+ });
69
+ }
83
70
  }
84
- return new write_js_1.ChannelWrite(channelPairs);
71
+ return new write_js_1.ChannelWrite(channelWriteEntries);
85
72
  }
86
73
  }
87
74
  exports.Channel = Channel;
@@ -98,43 +85,55 @@ class Pregel extends runnables_1.Runnable {
98
85
  writable: true,
99
86
  value: ["langgraph", "pregel"]
100
87
  });
88
+ Object.defineProperty(this, "nodes", {
89
+ enumerable: true,
90
+ configurable: true,
91
+ writable: true,
92
+ value: void 0
93
+ });
101
94
  Object.defineProperty(this, "channels", {
102
95
  enumerable: true,
103
96
  configurable: true,
104
97
  writable: true,
105
- value: {}
98
+ value: void 0
106
99
  });
107
- Object.defineProperty(this, "output", {
100
+ Object.defineProperty(this, "inputs", {
108
101
  enumerable: true,
109
102
  configurable: true,
110
103
  writable: true,
111
- value: "output"
104
+ value: void 0
112
105
  });
113
- Object.defineProperty(this, "input", {
106
+ Object.defineProperty(this, "outputs", {
114
107
  enumerable: true,
115
108
  configurable: true,
116
109
  writable: true,
117
- value: "input"
110
+ value: void 0
118
111
  });
119
- Object.defineProperty(this, "hidden", {
112
+ Object.defineProperty(this, "autoValidate", {
120
113
  enumerable: true,
121
114
  configurable: true,
122
115
  writable: true,
123
- value: []
116
+ value: true
124
117
  });
125
- Object.defineProperty(this, "debug", {
118
+ Object.defineProperty(this, "streamMode", {
126
119
  enumerable: true,
127
120
  configurable: true,
128
121
  writable: true,
129
- value: false
122
+ value: "values"
130
123
  });
131
- Object.defineProperty(this, "nodes", {
124
+ Object.defineProperty(this, "streamChannels", {
132
125
  enumerable: true,
133
126
  configurable: true,
134
127
  writable: true,
135
128
  value: void 0
136
129
  });
137
- Object.defineProperty(this, "checkpointer", {
130
+ Object.defineProperty(this, "interruptAfter", {
131
+ enumerable: true,
132
+ configurable: true,
133
+ writable: true,
134
+ value: void 0
135
+ });
136
+ Object.defineProperty(this, "interruptBefore", {
138
137
  enumerable: true,
139
138
  configurable: true,
140
139
  writable: true,
@@ -146,135 +145,263 @@ class Pregel extends runnables_1.Runnable {
146
145
  writable: true,
147
146
  value: void 0
148
147
  });
149
- Object.defineProperty(this, "interrupt", {
148
+ Object.defineProperty(this, "debug", {
150
149
  enumerable: true,
151
150
  configurable: true,
152
151
  writable: true,
153
- value: []
152
+ value: false
153
+ });
154
+ Object.defineProperty(this, "checkpointer", {
155
+ enumerable: true,
156
+ configurable: true,
157
+ writable: true,
158
+ value: void 0
154
159
  });
155
160
  // Initialize global async local storage instance for tracing
156
161
  (0, async_local_storage_js_1.initializeAsyncLocalStorageSingleton)();
157
- this.channels = fields.channels ?? this.channels;
158
- this.output = fields.output ?? this.output;
159
- this.input = fields.input ?? this.input;
160
- this.hidden = fields.hidden ?? this.hidden;
161
- this.debug = fields.debug ?? this.debug;
162
162
  this.nodes = fields.nodes;
163
+ this.channels = fields.channels;
164
+ this.autoValidate = fields.autoValidate ?? this.autoValidate;
165
+ this.streamMode = fields.streamMode ?? this.streamMode;
166
+ this.outputs = fields.outputs;
167
+ this.streamChannels = fields.streamChannels ?? this.streamChannels;
168
+ this.interruptAfter = fields.interruptAfter;
169
+ this.interruptBefore = fields.interruptBefore;
170
+ this.inputs = fields.inputs;
171
+ this.stepTimeout = fields.stepTimeout ?? this.stepTimeout;
172
+ this.debug = fields.debug ?? this.debug;
163
173
  this.checkpointer = fields.checkpointer;
164
- this.stepTimeout = fields.stepTimeout;
165
- this.interrupt = fields.interrupt ?? this.interrupt;
166
174
  // Bind the method to the instance
167
175
  this._transform = this._transform.bind(this);
176
+ if (this.autoValidate) {
177
+ this.validate();
178
+ }
179
+ }
180
+ validate() {
168
181
  (0, validate_js_1.validateGraph)({
169
182
  nodes: this.nodes,
170
183
  channels: this.channels,
171
- output: this.output,
172
- input: this.input,
173
- hidden: this.hidden,
174
- interrupt: this.interrupt,
184
+ outputChannels: this.outputs,
185
+ inputChannels: this.inputs,
186
+ streamChannels: this.streamChannels,
187
+ interruptAfterNodes: this.interruptAfter,
188
+ interruptBeforeNodes: this.interruptBefore,
175
189
  });
190
+ return this;
176
191
  }
177
- async *_transform(input, runManager, config = {}) {
178
- // assign defaults
179
- let outputKeys = [];
180
- if (Array.isArray(config.outputKeys) ||
181
- typeof config.outputKeys === "string") {
182
- outputKeys = config.outputKeys;
192
+ get streamChannelsList() {
193
+ if (Array.isArray(this.streamChannels)) {
194
+ return this.streamChannels;
195
+ }
196
+ else if (this.streamChannels) {
197
+ return [this.streamChannels];
183
198
  }
184
199
  else {
185
- for (const chan in this.channels) {
186
- if (!this.hidden.includes(chan)) {
187
- outputKeys.push(chan);
188
- }
189
- }
200
+ return Object.keys(this.channels);
190
201
  }
191
- // copy nodes to ignore mutations during execution
192
- const processes = { ...this.nodes };
193
- // get checkpoint, or create an empty one
194
- let checkpoint;
195
- if (this.checkpointer) {
196
- checkpoint = this.checkpointer.get(config);
197
- }
198
- checkpoint = checkpoint ?? (0, base_js_2.emptyCheckpoint)();
199
- // create channels from checkpoint
200
- const channels = (0, base_js_1.emptyChannels)(this.channels, checkpoint);
201
- // map inputs to channel updates
202
- const thisInput = this.input;
203
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
204
- const inputPendingWrites = [];
205
- for await (const c of input) {
206
- for (const value of (0, io_js_1.mapInput)(thisInput, c)) {
207
- inputPendingWrites.push(value);
208
- }
202
+ }
203
+ get streamChannelsAsIs() {
204
+ if (this.streamChannels) {
205
+ return this.streamChannels;
206
+ }
207
+ else {
208
+ return Object.keys(this.channels);
209
+ }
210
+ }
211
+ _defaults(config) {
212
+ const { debug, streamMode, inputKeys, outputKeys, interruptAfter, interruptBefore, ...rest } = config;
213
+ const defaultDebug = debug !== undefined ? debug : this.debug;
214
+ let defaultOutputKeys = outputKeys;
215
+ if (defaultOutputKeys === undefined) {
216
+ defaultOutputKeys = this.streamChannelsAsIs;
217
+ }
218
+ else {
219
+ (0, validate_js_1.validateKeys)(defaultOutputKeys, this.channels);
220
+ }
221
+ let defaultInputKeys = inputKeys;
222
+ if (defaultInputKeys === undefined) {
223
+ defaultInputKeys = this.inputs;
209
224
  }
210
- _applyWrites(checkpoint, channels, inputPendingWrites, config, 0);
211
- const read = (chan) => _readChannel(channels, chan);
212
- // Similarly to Bulk Synchronous Parallel / Pregel model
213
- // computation proceeds in steps, while there are channel updates
214
- // channel updates from step N are only visible in step N+1
215
- // channels are guaranteed to be immutable for the duration of the step,
216
- // with channel updates applied only at the transition between steps
217
- const recursionLimit = config.recursionLimit ?? DEFAULT_RECURSION_LIMIT;
218
- for (let step = 0; step < recursionLimit + 1; step += 1) {
219
- const nextTasks = _prepareNextTasks(checkpoint, processes, channels);
220
- // if no more tasks, we're done
221
- if (nextTasks.length === 0) {
222
- break;
225
+ else {
226
+ (0, validate_js_1.validateKeys)(defaultInputKeys, this.channels);
227
+ }
228
+ const defaultInterruptBefore = interruptBefore ?? this.interruptBefore ?? [];
229
+ const defaultInterruptAfter = interruptAfter ?? this.interruptAfter ?? [];
230
+ let defaultStreamMode;
231
+ if (streamMode !== undefined) {
232
+ defaultStreamMode = streamMode;
233
+ }
234
+ else {
235
+ defaultStreamMode = this.streamMode;
236
+ }
237
+ if (config.configurable !== undefined &&
238
+ config.configurable[constants_js_1.CONFIG_KEY_READ] !== undefined) {
239
+ defaultStreamMode = "values";
240
+ }
241
+ return [
242
+ defaultDebug,
243
+ defaultStreamMode,
244
+ defaultInputKeys,
245
+ defaultOutputKeys,
246
+ rest,
247
+ defaultInterruptBefore,
248
+ defaultInterruptAfter,
249
+ ];
250
+ }
251
+ async *_transform(input, runManager, config = {}) {
252
+ const bg = [];
253
+ try {
254
+ if (config.recursionLimit && config.recursionLimit < 1) {
255
+ throw new errors_js_1.GraphValueError(`Recursion limit must be greater than 0, got ${config.recursionLimit}`);
223
256
  }
224
- else if (step === config.recursionLimit) {
225
- throw new GraphRecursionError(`Recursion limit of ${config.recursionLimit} reached without hitting a stop condition. You can increase the limit by setting the "recursionLimit" config key.`);
257
+ if (this.checkpointer && !config.configurable) {
258
+ throw new errors_js_1.GraphValueError(`Checkpointer requires one or more of the following 'configurable' keys: thread_id, checkpoint_id`);
226
259
  }
227
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
228
- const pendingWrites = [];
229
- const tasksWithConfig = nextTasks.map(([proc, input, name]) => [
230
- proc,
231
- input,
232
- (0, runnables_1.patchConfig)(config, {
233
- callbacks: runManager?.getChild(`graph:step:${step}`),
234
- runName: name,
235
- configurable: {
236
- ...config.configurable,
237
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
238
- [constants_js_1.CONFIG_KEY_SEND]: (items) => pendingWrites.push(...items),
239
- [constants_js_1.CONFIG_KEY_READ]: read,
240
- },
241
- }),
242
- ]);
243
- // execute tasks, and wait for one to fail or all to finish.
244
- // each task is independent from all other concurrent tasks
245
- const tasks = tasksWithConfig.map(([proc, input, updatedConfig]) => () => proc.invoke(input, updatedConfig));
246
- await executeTasks(tasks, this.stepTimeout);
247
- // apply writes to channels
248
- _applyWrites(checkpoint, channels, pendingWrites, config, step + 1);
249
- // yield current value and checkpoint view
250
- const stepOutput = (0, io_js_1.mapOutput)(outputKeys, pendingWrites, channels);
251
- if (stepOutput) {
252
- yield stepOutput;
253
- if (typeof outputKeys !== "string") {
254
- _applyWritesFromView(checkpoint, channels, stepOutput);
260
+ // assign defaults
261
+ const [debug, streamMode, inputKeys, outputKeys, restConfig, interruptBefore, interruptAfter,] = this._defaults(config);
262
+ // copy nodes to ignore mutations during execution
263
+ const processes = { ...this.nodes };
264
+ // get checkpoint, or create an empty one
265
+ const saved = this.checkpointer
266
+ ? await this.checkpointer.getTuple(config)
267
+ : null;
268
+ let checkpoint = saved ? saved.checkpoint : (0, base_js_2.emptyCheckpoint)();
269
+ let checkpointConfig = saved ? saved.config : config;
270
+ let start = (saved?.metadata?.step ?? -2) + 1;
271
+ // create channels from checkpoint
272
+ const channels = (0, base_js_1.emptyChannels)(this.channels, checkpoint);
273
+ // map inputs to channel updates
274
+ const inputPendingWrites = [];
275
+ for await (const c of input) {
276
+ for (const value of (0, io_js_1.mapInput)(inputKeys, c)) {
277
+ inputPendingWrites.push(value);
278
+ }
279
+ }
280
+ if (inputPendingWrites.length) {
281
+ // discard any unfinished tasks from previous checkpoint
282
+ const discarded = _prepareNextTasks(checkpoint, processes, channels, true);
283
+ checkpoint = discarded[0]; // eslint-disable-line prefer-destructuring
284
+ // apply input writes
285
+ _applyWrites(checkpoint, channels, inputPendingWrites);
286
+ // save input checkpoint
287
+ if (this.checkpointer) {
288
+ checkpoint = (0, base_js_1.createCheckpoint)(checkpoint, channels, start);
289
+ bg.push(this.checkpointer.put(checkpointConfig, checkpoint, {
290
+ source: "input",
291
+ step: start,
292
+ writes: Object.fromEntries(inputPendingWrites),
293
+ }));
294
+ checkpointConfig = {
295
+ configurable: {
296
+ ...checkpointConfig.configurable,
297
+ checkpoint_id: checkpoint.id,
298
+ },
299
+ };
255
300
  }
301
+ // increment start to 0
302
+ start += 1;
256
303
  }
257
- // save end of step checkpoint
258
- if (this.checkpointer &&
259
- this.checkpointer.at === "end_of_step" /* CheckpointAt.END_OF_STEP */) {
260
- checkpoint = await (0, base_js_1.createCheckpoint)(checkpoint, channels);
261
- this.checkpointer.put(config, checkpoint);
304
+ else {
305
+ checkpoint = (0, base_js_2.copyCheckpoint)(checkpoint);
306
+ for (const k of this.streamChannelsList) {
307
+ const version = checkpoint.channel_versions[k];
308
+ checkpoint.versions_seen[constants_js_1.INTERRUPT][k] = version;
309
+ }
262
310
  }
263
- // interrupt if any channel written to is in interrupt list
264
- if (pendingWrites.some(([chan]) => this.interrupt?.some((i) => i === chan))) {
265
- break;
311
+ // Similarly to Bulk Synchronous Parallel / Pregel model
312
+ // computation proceeds in steps, while there are channel updates
313
+ // channel updates from step N are only visible in step N+1
314
+ // channels are guaranteed to be immutable for the duration of the step,
315
+ // with channel updates applied only at the transition between steps
316
+ const stop = start + (config.recursionLimit ?? DEFAULT_LOOP_LIMIT);
317
+ for (let step = start; step < stop + 1; step += 1) {
318
+ const [nextCheckpoint, nextTasks] = _prepareNextTasks(checkpoint, processes, channels, true);
319
+ // if no more tasks, we're done
320
+ if (nextTasks.length === 0 && step === start) {
321
+ throw new errors_js_1.GraphValueError(`No tasks to run in graph.`);
322
+ }
323
+ else if (nextTasks.length === 0) {
324
+ break;
325
+ }
326
+ else if (step === stop) {
327
+ throw new errors_js_1.GraphRecursionError(`Recursion limit of ${config.recursionLimit} reached without hitting a stop condition. You can increase the limit by setting the "recursionLimit" config key.`);
328
+ }
329
+ // before execution, check if we should interrupt
330
+ if (_shouldInterrupt(checkpoint, interruptBefore, this.streamChannelsList, nextTasks)) {
331
+ break;
332
+ }
333
+ else {
334
+ checkpoint = nextCheckpoint;
335
+ }
336
+ if (debug) {
337
+ console.log(nextTasks);
338
+ }
339
+ const tasksWithConfig = nextTasks.map(
340
+ // eslint-disable-next-line no-loop-func
341
+ (task) => [
342
+ task.proc,
343
+ task.input,
344
+ (0, runnables_1.patchConfig)(restConfig, {
345
+ callbacks: runManager?.getChild(`graph:step:${step}`),
346
+ runName: task.name,
347
+ configurable: {
348
+ ...config.configurable,
349
+ [constants_js_1.CONFIG_KEY_SEND]: (items) => task.writes.push(...items),
350
+ [constants_js_1.CONFIG_KEY_READ]: _localRead.bind(undefined, checkpoint, channels, task.writes),
351
+ },
352
+ }),
353
+ ]);
354
+ // execute tasks, and wait for one to fail or all to finish.
355
+ // each task is independent from all other concurrent tasks
356
+ const tasks = tasksWithConfig.map(([proc, input, updatedConfig]) => () => proc.invoke(input, updatedConfig));
357
+ await executeTasks(tasks, this.stepTimeout);
358
+ // combine pending writes from all tasks
359
+ const pendingWrites = [];
360
+ for (const task of nextTasks) {
361
+ pendingWrites.push(...task.writes);
362
+ }
363
+ // apply writes to channels
364
+ _applyWrites(checkpoint, channels, pendingWrites);
365
+ // yield current value and checkpoint view
366
+ if (streamMode === "values") {
367
+ yield* (0, io_js_1.mapOutputValues)(outputKeys, pendingWrites, channels);
368
+ }
369
+ else if (streamMode === "updates") {
370
+ yield* (0, io_js_1.mapOutputUpdates)(outputKeys, nextTasks);
371
+ }
372
+ // save end of step checkpoint
373
+ if (this.checkpointer) {
374
+ checkpoint = (0, base_js_1.createCheckpoint)(checkpoint, channels, step);
375
+ bg.push(this.checkpointer.put(checkpointConfig, checkpoint, {
376
+ source: "loop",
377
+ step,
378
+ writes: (0, io_js_1.single)(streamMode === "values"
379
+ ? (0, io_js_1.mapOutputValues)(outputKeys, pendingWrites, channels)
380
+ : (0, io_js_1.mapOutputUpdates)(outputKeys, nextTasks)),
381
+ }));
382
+ checkpointConfig = {
383
+ configurable: {
384
+ ...checkpointConfig.configurable,
385
+ checkpoint_id: checkpoint.id,
386
+ },
387
+ };
388
+ }
389
+ if (_shouldInterrupt(checkpoint, interruptAfter, this.streamChannelsList, nextTasks)) {
390
+ break;
391
+ }
266
392
  }
267
393
  }
268
- // save end of run checkpoint
269
- if (this.checkpointer && this.checkpointer.at === "end_of_run" /* CheckpointAt.END_OF_RUN */) {
270
- checkpoint = await (0, base_js_1.createCheckpoint)(checkpoint, channels);
271
- this.checkpointer.put(config, checkpoint);
394
+ finally {
395
+ await Promise.all(bg);
272
396
  }
273
397
  }
274
398
  async invoke(input, options) {
275
399
  const config = (0, runnables_1.ensureConfig)(options);
276
400
  if (!config?.outputKeys) {
277
- config.outputKeys = this.output;
401
+ config.outputKeys = this.outputs;
402
+ }
403
+ if (!config?.streamMode) {
404
+ config.streamMode = "values";
278
405
  }
279
406
  let latest;
280
407
  for await (const chunk of await this.stream(input, config)) {
@@ -321,30 +448,33 @@ async function executeTasks(tasks, stepTimeout) {
321
448
  }
322
449
  }
323
450
  }
324
- function _readChannel(channels, chan) {
325
- try {
326
- return channels[chan].get();
327
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
451
+ function _shouldInterrupt(checkpoint, interruptNodes, snapshotChannels, tasks) {
452
+ const seen = checkpoint.versions_seen[constants_js_1.INTERRUPT];
453
+ const anySnapshotChannelUpdated = snapshotChannels.some((chan) => checkpoint.channel_versions[chan] > seen?.[chan]);
454
+ const anyTaskNodeInInterruptNodes = tasks.some((task) => interruptNodes === "*"
455
+ ? !task.config?.tags?.includes(constants_js_1.TAG_HIDDEN)
456
+ : interruptNodes.includes(task.name));
457
+ return anySnapshotChannelUpdated && anyTaskNodeInInterruptNodes;
458
+ }
459
+ exports._shouldInterrupt = _shouldInterrupt;
460
+ function _localRead(checkpoint, channels, writes, select, fresh = false) {
461
+ if (fresh) {
462
+ const newCheckpoint = (0, base_js_1.createCheckpoint)(checkpoint, channels, -1);
463
+ // create a new copy of channels
464
+ const newChannels = (0, base_js_1.emptyChannels)(channels, newCheckpoint);
465
+ // Note: _applyWrites contains side effects
466
+ _applyWrites((0, base_js_2.copyCheckpoint)(newCheckpoint), newChannels, writes);
467
+ return (0, io_js_1.readChannels)(newChannels, select);
328
468
  }
329
- catch (e) {
330
- if (e.name === base_js_1.EmptyChannelError.name) {
331
- return null;
332
- }
333
- throw e;
469
+ else {
470
+ return (0, io_js_1.readChannels)(channels, select);
334
471
  }
335
472
  }
336
- function _applyWrites(checkpoint, channels,
337
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
338
- pendingWrites, config, forStep) {
339
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
473
+ exports._localRead = _localRead;
474
+ function _applyWrites(checkpoint, channels, pendingWrites) {
340
475
  const pendingWritesByChannel = {};
341
476
  // Group writes by channel
342
477
  for (const [chan, val] of pendingWrites) {
343
- for (const c in reserved_js_1.ReservedChannelsMap) {
344
- if (chan === c) {
345
- throw new Error(`Can't write to reserved channel ${chan}`);
346
- }
347
- }
348
478
  if (chan in pendingWritesByChannel) {
349
479
  pendingWritesByChannel[chan].push(val);
350
480
  }
@@ -352,104 +482,144 @@ pendingWrites, config, forStep) {
352
482
  pendingWritesByChannel[chan] = [val];
353
483
  }
354
484
  }
355
- // Update reserved channels
356
- pendingWritesByChannel[reserved_js_1.ReservedChannelsMap.isLastStep] = [
357
- forStep + 1 === config.recursionLimit,
358
- ];
485
+ // find the highest version of all channels
486
+ let maxVersion = 0;
487
+ if (Object.keys(checkpoint.channel_versions).length > 0) {
488
+ maxVersion = Math.max(...Object.values(checkpoint.channel_versions));
489
+ }
359
490
  const updatedChannels = new Set();
360
491
  // Apply writes to channels
361
- for (const chan in pendingWritesByChannel) {
362
- if (chan in pendingWritesByChannel) {
363
- const vals = pendingWritesByChannel[chan];
364
- if (chan in channels) {
492
+ for (const [chan, vals] of Object.entries(pendingWritesByChannel)) {
493
+ if (chan in channels) {
494
+ // side effect: update channels
495
+ try {
365
496
  channels[chan].update(vals);
366
- if (checkpoint.channelVersions[chan] === undefined) {
367
- checkpoint.channelVersions[chan] = 1;
368
- }
369
- else {
370
- checkpoint.channelVersions[chan] += 1;
371
- }
372
- updatedChannels.add(chan);
497
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
373
498
  }
374
- else {
375
- console.warn(`Skipping write for channel ${chan} which has no readers`);
499
+ catch (e) {
500
+ if (e.name === errors_js_1.InvalidUpdateError.name) {
501
+ throw new errors_js_1.InvalidUpdateError(`Invalid update for channel ${chan}. Values: ${vals}`);
502
+ }
376
503
  }
504
+ // side effect: update checkpoint channel versions
505
+ checkpoint.channel_versions[chan] = maxVersion + 1;
506
+ updatedChannels.add(chan);
507
+ }
508
+ else {
509
+ console.warn(`Skipping write for channel ${chan} which has no readers`);
377
510
  }
378
511
  }
379
512
  // Channels that weren't updated in this step are notified of a new step
380
513
  for (const chan in channels) {
381
514
  if (!updatedChannels.has(chan)) {
515
+ // side effect: update channels
382
516
  channels[chan].update([]);
383
517
  }
384
518
  }
385
519
  }
386
- function _applyWritesFromView(checkpoint, channels, values) {
387
- for (const [chan, val] of Object.entries(values)) {
388
- if (val === _readChannel(channels, chan)) {
389
- continue;
390
- }
391
- if (channels[chan].lc_graph_name === "LastValue") {
392
- throw new Error(`Can't modify channel ${chan} with LastValue`);
393
- }
394
- checkpoint.channelVersions[chan] += 1;
395
- channels[chan].update([values[chan]]);
396
- }
397
- }
398
- function _prepareNextTasks(checkpoint, processes, channels) {
520
+ exports._applyWrites = _applyWrites;
521
+ function _prepareNextTasks(checkpoint, processes, channels, forExecution) {
522
+ const newCheckpoint = (0, base_js_2.copyCheckpoint)(checkpoint);
399
523
  const tasks = [];
524
+ const taskDescriptions = [];
400
525
  // Check if any processes should be run in next step
401
526
  // If so, prepare the values to be passed to them
402
527
  for (const [name, proc] of Object.entries(processes)) {
403
- let seen = checkpoint.versionsSeen[name];
528
+ let seen = newCheckpoint.versions_seen[name];
404
529
  if (!seen) {
405
- checkpoint.versionsSeen[name] = {};
406
- seen = checkpoint.versionsSeen[name];
530
+ newCheckpoint.versions_seen[name] = {};
531
+ seen = newCheckpoint.versions_seen[name];
407
532
  }
408
533
  // If any of the channels read by this process were updated
409
- if (proc.triggers.some((chan) => checkpoint.channelVersions[chan] > (seen[chan] ?? 0))) {
410
- // If all channels subscribed by this process have been initialized
534
+ if (proc.triggers
535
+ .filter((chan) => {
411
536
  try {
412
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
413
- let val = {};
414
- if (typeof proc.channels === "string") {
415
- val[proc.channels] = _readChannel(channels, proc.channels);
537
+ (0, io_js_1.readChannel)(channels, chan, false);
538
+ return true;
539
+ }
540
+ catch (e) {
541
+ return false;
542
+ }
543
+ })
544
+ .some((chan) => newCheckpoint.channel_versions[chan] > (seen[chan] ?? 0))) {
545
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
546
+ let val;
547
+ // If all trigger channels subscribed by this process are not empty
548
+ // then invoke the process with the values of all non-empty channels
549
+ if (Array.isArray(proc.channels)) {
550
+ let emptyChannels = 0;
551
+ for (const chan of proc.channels) {
552
+ try {
553
+ val = (0, io_js_1.readChannel)(channels, chan, false);
554
+ break;
555
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
556
+ }
557
+ catch (e) {
558
+ if (e.name === errors_js_1.EmptyChannelError.name) {
559
+ emptyChannels += 1;
560
+ continue;
561
+ }
562
+ else {
563
+ throw e;
564
+ }
565
+ }
416
566
  }
417
- else {
567
+ if (emptyChannels === proc.channels.length) {
568
+ continue;
569
+ }
570
+ }
571
+ else if (typeof proc.channels === "object") {
572
+ val = {};
573
+ try {
418
574
  for (const [k, chan] of Object.entries(proc.channels)) {
419
- val[k] = _readChannel(channels, chan);
575
+ val[k] = (0, io_js_1.readChannel)(channels, chan, !proc.triggers.includes(chan));
420
576
  }
577
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
421
578
  }
422
- // Processes that subscribe to a single keyless channel get
423
- // the value directly, instead of a dict
424
- if (typeof proc.channels === "string") {
425
- val = val[proc.channels];
426
- }
427
- else if (Object.keys(proc.channels).length === 1 &&
428
- proc.channels[Object.keys(proc.channels)[0]] === undefined) {
429
- val = val[Object.keys(proc.channels)[0]];
579
+ catch (e) {
580
+ if (e.name === errors_js_1.EmptyChannelError.name) {
581
+ continue;
582
+ }
583
+ else {
584
+ throw e;
585
+ }
430
586
  }
587
+ }
588
+ else {
589
+ throw new Error(`Invalid channels type, expected list or dict, got ${proc.channels}`);
590
+ }
591
+ // If the process has a mapper, apply it to the value
592
+ if (proc.mapper !== undefined) {
593
+ val = proc.mapper(val);
594
+ }
595
+ if (forExecution) {
431
596
  // Update seen versions
432
597
  proc.triggers.forEach((chan) => {
433
- const version = checkpoint.channelVersions[chan];
598
+ const version = newCheckpoint.channel_versions[chan];
434
599
  if (version !== undefined) {
600
+ // side effect: updates newCheckpoint
435
601
  seen[chan] = version;
436
602
  }
437
603
  });
438
- // skip if condition is not met
439
- if (proc.when === undefined || proc.when(val)) {
440
- tasks.push([proc, val, name]);
604
+ const node = proc.getNode();
605
+ if (node !== undefined) {
606
+ tasks.push({
607
+ name,
608
+ input: val,
609
+ proc: node,
610
+ writes: [],
611
+ config: proc.config,
612
+ });
441
613
  }
442
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
443
614
  }
444
- catch (error) {
445
- if (error.name === base_js_1.EmptyChannelError.name) {
446
- continue;
447
- }
448
- else {
449
- throw error;
450
- }
615
+ else {
616
+ taskDescriptions.push({
617
+ name,
618
+ input: val,
619
+ });
451
620
  }
452
621
  }
453
622
  }
454
- return tasks;
623
+ return [newCheckpoint, forExecution ? tasks : taskDescriptions];
455
624
  }
625
+ exports._prepareNextTasks = _prepareNextTasks;