@langchain/langgraph 0.2.32 → 0.2.33

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.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports._isCommand = exports.Command = exports._isSend = exports.Send = exports._isSendInterface = exports.CHECKPOINT_NAMESPACE_END = exports.CHECKPOINT_NAMESPACE_SEPARATOR = exports.RESERVED = exports.NULL_TASK_ID = exports.TASK_NAMESPACE = exports.PULL = exports.PUSH = exports.TASKS = exports.SELF = exports.TAG_NOSTREAM = exports.TAG_HIDDEN = exports.RECURSION_LIMIT_DEFAULT = exports.RUNTIME_PLACEHOLDER = exports.RESUME = exports.INTERRUPT = exports.CONFIG_KEY_CHECKPOINT_MAP = exports.CONFIG_KEY_CHECKPOINT_NS = exports.CONFIG_KEY_SCRATCHPAD = exports.CONFIG_KEY_WRITES = exports.CONFIG_KEY_RESUME_VALUE = exports.CONFIG_KEY_STREAM = exports.CONFIG_KEY_TASK_ID = exports.CONFIG_KEY_RESUMING = exports.CONFIG_KEY_CHECKPOINTER = exports.CONFIG_KEY_READ = exports.CONFIG_KEY_SEND = exports.ERROR = exports.INPUT = exports.MISSING = void 0;
3
+ exports.isCommand = exports.Command = exports._isSend = exports.Send = exports._isSendInterface = exports.CHECKPOINT_NAMESPACE_END = exports.CHECKPOINT_NAMESPACE_SEPARATOR = exports.RESERVED = exports.NULL_TASK_ID = exports.TASK_NAMESPACE = exports.PULL = exports.PUSH = exports.TASKS = exports.SELF = exports.TAG_NOSTREAM = exports.TAG_HIDDEN = exports.RECURSION_LIMIT_DEFAULT = exports.RUNTIME_PLACEHOLDER = exports.RESUME = exports.INTERRUPT = exports.CONFIG_KEY_CHECKPOINT_MAP = exports.CONFIG_KEY_CHECKPOINT_NS = exports.CONFIG_KEY_SCRATCHPAD = exports.CONFIG_KEY_WRITES = exports.CONFIG_KEY_RESUME_VALUE = exports.CONFIG_KEY_STREAM = exports.CONFIG_KEY_TASK_ID = exports.CONFIG_KEY_RESUMING = exports.CONFIG_KEY_CHECKPOINTER = exports.CONFIG_KEY_READ = exports.CONFIG_KEY_SEND = exports.ERROR = exports.INPUT = exports.MISSING = void 0;
4
4
  exports.MISSING = Symbol.for("__missing__");
5
5
  exports.INPUT = "__input__";
6
6
  exports.ERROR = "__error__";
@@ -126,6 +126,65 @@ function _isSend(x) {
126
126
  exports._isSend = _isSend;
127
127
  /**
128
128
  * One or more commands to update the graph's state and send messages to nodes.
129
+ * Can be used to combine routing logic with state updates in lieu of conditional edges
130
+ *
131
+ * @example
132
+ * ```ts
133
+ * import { Annotation, Command } from "@langchain/langgraph";
134
+ *
135
+ * // Define graph state
136
+ * const StateAnnotation = Annotation.Root({
137
+ * foo: Annotation<string>,
138
+ * });
139
+ *
140
+ * // Define the nodes
141
+ * const nodeA = async (_state: typeof StateAnnotation.State) => {
142
+ * console.log("Called A");
143
+ * // this is a replacement for a real conditional edge function
144
+ * const goto = Math.random() > .5 ? "nodeB" : "nodeC";
145
+ * // note how Command allows you to BOTH update the graph state AND route to the next node
146
+ * return new Command({
147
+ * // this is the state update
148
+ * update: {
149
+ * foo: "a",
150
+ * },
151
+ * // this is a replacement for an edge
152
+ * goto,
153
+ * });
154
+ * };
155
+ *
156
+ * // Nodes B and C are unchanged
157
+ * const nodeB = async (state: typeof StateAnnotation.State) => {
158
+ * console.log("Called B");
159
+ * return {
160
+ * foo: state.foo + "|b",
161
+ * };
162
+ * }
163
+ *
164
+ * const nodeC = async (state: typeof StateAnnotation.State) => {
165
+ * console.log("Called C");
166
+ * return {
167
+ * foo: state.foo + "|c",
168
+ * };
169
+ * }
170
+ *
171
+ * import { StateGraph } from "@langchain/langgraph";
172
+
173
+ * // NOTE: there are no edges between nodes A, B and C!
174
+ * const graph = new StateGraph(StateAnnotation)
175
+ * .addNode("nodeA", nodeA, {
176
+ * ends: ["nodeB", "nodeC"],
177
+ * })
178
+ * .addNode("nodeB", nodeB)
179
+ * .addNode("nodeC", nodeC)
180
+ * .addEdge("__start__", "nodeA")
181
+ * .compile();
182
+ *
183
+ * await graph.invoke({ foo: "" });
184
+ *
185
+ * // Randomly oscillates between
186
+ * // { foo: 'a|c' } and { foo: 'a|b' }
187
+ * ```
129
188
  */
130
189
  class Command {
131
190
  constructor(args) {
@@ -135,11 +194,11 @@ class Command {
135
194
  writable: true,
136
195
  value: "Command"
137
196
  });
138
- Object.defineProperty(this, "resume", {
197
+ Object.defineProperty(this, "lc_direct_tool_output", {
139
198
  enumerable: true,
140
199
  configurable: true,
141
200
  writable: true,
142
- value: void 0
201
+ value: true
143
202
  });
144
203
  Object.defineProperty(this, "graph", {
145
204
  enumerable: true,
@@ -149,6 +208,12 @@ class Command {
149
208
  });
150
209
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
151
210
  Object.defineProperty(this, "update", {
211
+ enumerable: true,
212
+ configurable: true,
213
+ writable: true,
214
+ value: []
215
+ });
216
+ Object.defineProperty(this, "resume", {
152
217
  enumerable: true,
153
218
  configurable: true,
154
219
  writable: true,
@@ -167,6 +232,20 @@ class Command {
167
232
  this.goto = Array.isArray(args.goto) ? args.goto : [args.goto];
168
233
  }
169
234
  }
235
+ _updateAsTuples() {
236
+ if (this.update &&
237
+ typeof this.update === "object" &&
238
+ !Array.isArray(this.update)) {
239
+ return Object.entries(this.update);
240
+ }
241
+ else if (Array.isArray(this.update) &&
242
+ this.update.every((t) => Array.isArray(t) && t.length === 2 && typeof t[0] === "string")) {
243
+ return this.update;
244
+ }
245
+ else {
246
+ return [["__root__", this.update]];
247
+ }
248
+ }
170
249
  }
171
250
  exports.Command = Command;
172
251
  Object.defineProperty(Command, "PARENT", {
@@ -175,7 +254,7 @@ Object.defineProperty(Command, "PARENT", {
175
254
  writable: true,
176
255
  value: "__parent__"
177
256
  });
178
- function _isCommand(x) {
257
+ function isCommand(x) {
179
258
  return typeof x === "object" && !!x && x.lg_name === "Command";
180
259
  }
181
- exports._isCommand = _isCommand;
260
+ exports.isCommand = isCommand;
@@ -117,14 +117,75 @@ export type CommandParams<R> = {
117
117
  };
118
118
  /**
119
119
  * One or more commands to update the graph's state and send messages to nodes.
120
+ * Can be used to combine routing logic with state updates in lieu of conditional edges
121
+ *
122
+ * @example
123
+ * ```ts
124
+ * import { Annotation, Command } from "@langchain/langgraph";
125
+ *
126
+ * // Define graph state
127
+ * const StateAnnotation = Annotation.Root({
128
+ * foo: Annotation<string>,
129
+ * });
130
+ *
131
+ * // Define the nodes
132
+ * const nodeA = async (_state: typeof StateAnnotation.State) => {
133
+ * console.log("Called A");
134
+ * // this is a replacement for a real conditional edge function
135
+ * const goto = Math.random() > .5 ? "nodeB" : "nodeC";
136
+ * // note how Command allows you to BOTH update the graph state AND route to the next node
137
+ * return new Command({
138
+ * // this is the state update
139
+ * update: {
140
+ * foo: "a",
141
+ * },
142
+ * // this is a replacement for an edge
143
+ * goto,
144
+ * });
145
+ * };
146
+ *
147
+ * // Nodes B and C are unchanged
148
+ * const nodeB = async (state: typeof StateAnnotation.State) => {
149
+ * console.log("Called B");
150
+ * return {
151
+ * foo: state.foo + "|b",
152
+ * };
153
+ * }
154
+ *
155
+ * const nodeC = async (state: typeof StateAnnotation.State) => {
156
+ * console.log("Called C");
157
+ * return {
158
+ * foo: state.foo + "|c",
159
+ * };
160
+ * }
161
+ *
162
+ * import { StateGraph } from "@langchain/langgraph";
163
+
164
+ * // NOTE: there are no edges between nodes A, B and C!
165
+ * const graph = new StateGraph(StateAnnotation)
166
+ * .addNode("nodeA", nodeA, {
167
+ * ends: ["nodeB", "nodeC"],
168
+ * })
169
+ * .addNode("nodeB", nodeB)
170
+ * .addNode("nodeC", nodeC)
171
+ * .addEdge("__start__", "nodeA")
172
+ * .compile();
173
+ *
174
+ * await graph.invoke({ foo: "" });
175
+ *
176
+ * // Randomly oscillates between
177
+ * // { foo: 'a|c' } and { foo: 'a|b' }
178
+ * ```
120
179
  */
121
180
  export declare class Command<R = unknown> {
122
181
  lg_name: string;
123
- resume?: R;
182
+ lc_direct_tool_output: boolean;
124
183
  graph?: string;
125
- update?: Record<string, any>;
184
+ update?: Record<string, any> | [string, any][];
185
+ resume?: R;
126
186
  goto: string | Send | (string | Send)[];
127
187
  static PARENT: string;
128
188
  constructor(args: CommandParams<R>);
189
+ _updateAsTuples(): [string, unknown][];
129
190
  }
130
- export declare function _isCommand(x: unknown): x is Command;
191
+ export declare function isCommand(x: unknown): x is Command;
package/dist/constants.js CHANGED
@@ -120,6 +120,65 @@ export function _isSend(x) {
120
120
  }
121
121
  /**
122
122
  * One or more commands to update the graph's state and send messages to nodes.
123
+ * Can be used to combine routing logic with state updates in lieu of conditional edges
124
+ *
125
+ * @example
126
+ * ```ts
127
+ * import { Annotation, Command } from "@langchain/langgraph";
128
+ *
129
+ * // Define graph state
130
+ * const StateAnnotation = Annotation.Root({
131
+ * foo: Annotation<string>,
132
+ * });
133
+ *
134
+ * // Define the nodes
135
+ * const nodeA = async (_state: typeof StateAnnotation.State) => {
136
+ * console.log("Called A");
137
+ * // this is a replacement for a real conditional edge function
138
+ * const goto = Math.random() > .5 ? "nodeB" : "nodeC";
139
+ * // note how Command allows you to BOTH update the graph state AND route to the next node
140
+ * return new Command({
141
+ * // this is the state update
142
+ * update: {
143
+ * foo: "a",
144
+ * },
145
+ * // this is a replacement for an edge
146
+ * goto,
147
+ * });
148
+ * };
149
+ *
150
+ * // Nodes B and C are unchanged
151
+ * const nodeB = async (state: typeof StateAnnotation.State) => {
152
+ * console.log("Called B");
153
+ * return {
154
+ * foo: state.foo + "|b",
155
+ * };
156
+ * }
157
+ *
158
+ * const nodeC = async (state: typeof StateAnnotation.State) => {
159
+ * console.log("Called C");
160
+ * return {
161
+ * foo: state.foo + "|c",
162
+ * };
163
+ * }
164
+ *
165
+ * import { StateGraph } from "@langchain/langgraph";
166
+
167
+ * // NOTE: there are no edges between nodes A, B and C!
168
+ * const graph = new StateGraph(StateAnnotation)
169
+ * .addNode("nodeA", nodeA, {
170
+ * ends: ["nodeB", "nodeC"],
171
+ * })
172
+ * .addNode("nodeB", nodeB)
173
+ * .addNode("nodeC", nodeC)
174
+ * .addEdge("__start__", "nodeA")
175
+ * .compile();
176
+ *
177
+ * await graph.invoke({ foo: "" });
178
+ *
179
+ * // Randomly oscillates between
180
+ * // { foo: 'a|c' } and { foo: 'a|b' }
181
+ * ```
123
182
  */
124
183
  export class Command {
125
184
  constructor(args) {
@@ -129,11 +188,11 @@ export class Command {
129
188
  writable: true,
130
189
  value: "Command"
131
190
  });
132
- Object.defineProperty(this, "resume", {
191
+ Object.defineProperty(this, "lc_direct_tool_output", {
133
192
  enumerable: true,
134
193
  configurable: true,
135
194
  writable: true,
136
- value: void 0
195
+ value: true
137
196
  });
138
197
  Object.defineProperty(this, "graph", {
139
198
  enumerable: true,
@@ -143,6 +202,12 @@ export class Command {
143
202
  });
144
203
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
145
204
  Object.defineProperty(this, "update", {
205
+ enumerable: true,
206
+ configurable: true,
207
+ writable: true,
208
+ value: []
209
+ });
210
+ Object.defineProperty(this, "resume", {
146
211
  enumerable: true,
147
212
  configurable: true,
148
213
  writable: true,
@@ -161,6 +226,20 @@ export class Command {
161
226
  this.goto = Array.isArray(args.goto) ? args.goto : [args.goto];
162
227
  }
163
228
  }
229
+ _updateAsTuples() {
230
+ if (this.update &&
231
+ typeof this.update === "object" &&
232
+ !Array.isArray(this.update)) {
233
+ return Object.entries(this.update);
234
+ }
235
+ else if (Array.isArray(this.update) &&
236
+ this.update.every((t) => Array.isArray(t) && t.length === 2 && typeof t[0] === "string")) {
237
+ return this.update;
238
+ }
239
+ else {
240
+ return [["__root__", this.update]];
241
+ }
242
+ }
164
243
  }
165
244
  Object.defineProperty(Command, "PARENT", {
166
245
  enumerable: true,
@@ -168,6 +247,6 @@ Object.defineProperty(Command, "PARENT", {
168
247
  writable: true,
169
248
  value: "__parent__"
170
249
  });
171
- export function _isCommand(x) {
250
+ export function isCommand(x) {
172
251
  return typeof x === "object" && !!x && x.lg_name === "Command";
173
252
  }
package/dist/errors.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getSubgraphsSeenSet = exports.RemoteException = exports.MultipleSubgraphsError = exports.InvalidUpdateError = exports.EmptyChannelError = exports.EmptyInputError = exports.isGraphInterrupt = exports.isGraphBubbleUp = exports.isParentCommand = exports.ParentCommand = exports.NodeInterrupt = exports.GraphInterrupt = exports.GraphValueError = exports.GraphRecursionError = exports.GraphBubbleUp = exports.BaseLangGraphError = void 0;
3
+ exports.getSubgraphsSeenSet = exports.RemoteException = exports.UnreachableNodeError = exports.MultipleSubgraphsError = exports.InvalidUpdateError = exports.EmptyChannelError = exports.EmptyInputError = exports.isGraphInterrupt = exports.isGraphBubbleUp = exports.isParentCommand = exports.ParentCommand = exports.NodeInterrupt = exports.GraphInterrupt = exports.GraphValueError = exports.GraphRecursionError = exports.GraphBubbleUp = exports.BaseLangGraphError = void 0;
4
4
  // TODO: Merge with base LangChain error class when we drop support for core@0.2.0
5
5
  class BaseLangGraphError extends Error {
6
6
  constructor(message, fields) {
@@ -153,6 +153,16 @@ class MultipleSubgraphsError extends BaseLangGraphError {
153
153
  }
154
154
  }
155
155
  exports.MultipleSubgraphsError = MultipleSubgraphsError;
156
+ class UnreachableNodeError extends BaseLangGraphError {
157
+ constructor(message, fields) {
158
+ super(message, fields);
159
+ this.name = "UnreachableNodeError";
160
+ }
161
+ static get unminifiable_name() {
162
+ return "UnreachableNodeError";
163
+ }
164
+ }
165
+ exports.UnreachableNodeError = UnreachableNodeError;
156
166
  /**
157
167
  * Exception raised when an error occurs in the remote graph.
158
168
  */
package/dist/errors.d.ts CHANGED
@@ -51,6 +51,10 @@ export declare class MultipleSubgraphsError extends BaseLangGraphError {
51
51
  constructor(message?: string, fields?: BaseLangGraphErrorFields);
52
52
  static get unminifiable_name(): string;
53
53
  }
54
+ export declare class UnreachableNodeError extends BaseLangGraphError {
55
+ constructor(message?: string, fields?: BaseLangGraphErrorFields);
56
+ static get unminifiable_name(): string;
57
+ }
54
58
  /**
55
59
  * Exception raised when an error occurs in the remote graph.
56
60
  */
package/dist/errors.js CHANGED
@@ -136,6 +136,15 @@ export class MultipleSubgraphsError extends BaseLangGraphError {
136
136
  return "MultipleSubgraphError";
137
137
  }
138
138
  }
139
+ export class UnreachableNodeError extends BaseLangGraphError {
140
+ constructor(message, fields) {
141
+ super(message, fields);
142
+ this.name = "UnreachableNodeError";
143
+ }
144
+ static get unminifiable_name() {
145
+ return "UnreachableNodeError";
146
+ }
147
+ }
139
148
  /**
140
149
  * Exception raised when an error occurs in the remote graph.
141
150
  */
@@ -299,7 +299,15 @@ class Graph {
299
299
  // validate targets
300
300
  for (const node of Object.keys(this.nodes)) {
301
301
  if (!allTargets.has(node)) {
302
- throw new Error(`Node \`${node}\` is not reachable`);
302
+ throw new errors_js_1.UnreachableNodeError([
303
+ `Node \`${node}\` is not reachable.`,
304
+ "",
305
+ "If you are returning Command objects from your node,",
306
+ 'make sure you are passing names of potential destination nodes as an "ends" array',
307
+ 'into ".addNode(..., { ends: ["node1", "node2"] })".',
308
+ ].join("\n"), {
309
+ lc_error_code: "UNREACHABLE_NODE",
310
+ });
303
311
  }
304
312
  }
305
313
  for (const target of allTargets) {
@@ -9,7 +9,7 @@ import { EphemeralValue } from "../channels/ephemeral_value.js";
9
9
  import { ChannelWrite, PASSTHROUGH } from "../pregel/write.js";
10
10
  import { _isSend, CHECKPOINT_NAMESPACE_END, CHECKPOINT_NAMESPACE_SEPARATOR, TAG_HIDDEN, } from "../constants.js";
11
11
  import { gatherIterator, gatherIteratorSync, RunnableCallable, } from "../utils.js";
12
- import { InvalidUpdateError, NodeInterrupt } from "../errors.js";
12
+ import { InvalidUpdateError, NodeInterrupt, UnreachableNodeError, } from "../errors.js";
13
13
  import { isPregelLike } from "../pregel/utils/subgraph.js";
14
14
  /** Special reserved node name denoting the start of a graph. */
15
15
  export const START = "__start__";
@@ -295,7 +295,15 @@ export class Graph {
295
295
  // validate targets
296
296
  for (const node of Object.keys(this.nodes)) {
297
297
  if (!allTargets.has(node)) {
298
- throw new Error(`Node \`${node}\` is not reachable`);
298
+ throw new UnreachableNodeError([
299
+ `Node \`${node}\` is not reachable.`,
300
+ "",
301
+ "If you are returning Command objects from your node,",
302
+ 'make sure you are passing names of potential destination nodes as an "ends" array',
303
+ 'into ".addNode(..., { ends: ["node1", "node2"] })".',
304
+ ].join("\n"), {
305
+ lc_error_code: "UNREACHABLE_NODE",
306
+ });
299
307
  }
300
308
  }
301
309
  for (const target of allTargets) {
@@ -347,59 +347,101 @@ function _getChannels(schema) {
347
347
  */
348
348
  class CompiledStateGraph extends graph_js_1.CompiledGraph {
349
349
  attachNode(key, node) {
350
- const stateKeys = Object.keys(this.builder.channels);
350
+ let outputKeys;
351
+ if (key === graph_js_1.START) {
352
+ // Get input schema keys excluding managed values
353
+ outputKeys = Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition))
354
+ .filter(([_, v]) => !(0, base_js_2.isConfiguredManagedValue)(v))
355
+ .map(([k]) => k);
356
+ }
357
+ else {
358
+ outputKeys = Object.keys(this.builder.channels);
359
+ }
360
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
351
361
  function _getRoot(input) {
352
- if ((0, constants_js_1._isCommand)(input)) {
362
+ if ((0, constants_js_1.isCommand)(input)) {
353
363
  if (input.graph === constants_js_1.Command.PARENT) {
354
- return write_js_1.SKIP_WRITE;
364
+ return null;
365
+ }
366
+ return input._updateAsTuples();
367
+ }
368
+ else if (Array.isArray(input) &&
369
+ input.length > 0 &&
370
+ input.some((i) => (0, constants_js_1.isCommand)(i))) {
371
+ const updates = [];
372
+ for (const i of input) {
373
+ if ((0, constants_js_1.isCommand)(i)) {
374
+ if (i.graph === constants_js_1.Command.PARENT) {
375
+ continue;
376
+ }
377
+ updates.push(...i._updateAsTuples());
378
+ }
379
+ else {
380
+ updates.push([ROOT, i]);
381
+ }
355
382
  }
356
- return input.update;
383
+ return updates;
357
384
  }
358
- return input;
385
+ else if (input != null) {
386
+ return [[ROOT, input]];
387
+ }
388
+ return null;
359
389
  }
360
390
  // to avoid name collision below
361
391
  const nodeKey = key;
362
- function getStateKey(key, input) {
392
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
393
+ function _getUpdates(input) {
363
394
  if (!input) {
364
- return write_js_1.SKIP_WRITE;
395
+ return null;
365
396
  }
366
- else if ((0, constants_js_1._isCommand)(input)) {
397
+ else if ((0, constants_js_1.isCommand)(input)) {
367
398
  if (input.graph === constants_js_1.Command.PARENT) {
368
- return write_js_1.SKIP_WRITE;
399
+ return null;
369
400
  }
370
- return getStateKey(key, input.update);
401
+ return input._updateAsTuples();
371
402
  }
372
- else if (typeof input !== "object" || Array.isArray(input)) {
403
+ else if (Array.isArray(input) &&
404
+ input.length > 0 &&
405
+ input.some(constants_js_1.isCommand)) {
406
+ const updates = [];
407
+ for (const item of input) {
408
+ if ((0, constants_js_1.isCommand)(item)) {
409
+ if (item.graph === constants_js_1.Command.PARENT) {
410
+ continue;
411
+ }
412
+ updates.push(...item._updateAsTuples());
413
+ }
414
+ else {
415
+ const itemUpdates = _getUpdates(item);
416
+ if (itemUpdates) {
417
+ updates.push(...(itemUpdates ?? []));
418
+ }
419
+ }
420
+ }
421
+ return updates;
422
+ }
423
+ else if (typeof input === "object" && !Array.isArray(input)) {
424
+ return Object.entries(input).filter(([k]) => outputKeys.includes(k));
425
+ }
426
+ else {
373
427
  const typeofInput = Array.isArray(input) ? "array" : typeof input;
374
428
  throw new errors_js_1.InvalidUpdateError(`Expected node "${nodeKey.toString()}" to return an object, received ${typeofInput}`, {
375
429
  lc_error_code: "INVALID_GRAPH_NODE_RETURN_VALUE",
376
430
  });
377
431
  }
378
- else {
379
- return key in input ? input[key] : write_js_1.SKIP_WRITE;
380
- }
381
432
  }
382
- // state updaters
383
- const stateWriteEntries = stateKeys.map((key) => key === ROOT
384
- ? {
385
- channel: key,
433
+ const stateWriteEntries = [
434
+ {
386
435
  value: write_js_1.PASSTHROUGH,
387
- skipNone: true,
388
436
  mapper: new utils_js_1.RunnableCallable({
389
- func: _getRoot,
437
+ func: outputKeys.length && outputKeys[0] === ROOT
438
+ ? _getRoot
439
+ : _getUpdates,
390
440
  trace: false,
391
441
  recurse: false,
392
442
  }),
393
- }
394
- : {
395
- channel: key,
396
- value: write_js_1.PASSTHROUGH,
397
- mapper: new utils_js_1.RunnableCallable({
398
- func: getStateKey.bind(null, key),
399
- trace: false,
400
- recurse: false,
401
- }),
402
- });
443
+ },
444
+ ];
403
445
  // add node and output channel
404
446
  if (key === graph_js_1.START) {
405
447
  this.nodes[key] = new read_js_1.PregelNode({
@@ -541,7 +583,7 @@ function _controlBranch(value) {
541
583
  if ((0, constants_js_1._isSend)(value)) {
542
584
  return [value];
543
585
  }
544
- if (!(0, constants_js_1._isCommand)(value)) {
586
+ if (!(0, constants_js_1.isCommand)(value)) {
545
587
  return [];
546
588
  }
547
589
  if (value.graph === constants_js_1.Command.PARENT) {
@@ -2,12 +2,12 @@
2
2
  import { _coerceToRunnable, Runnable, } from "@langchain/core/runnables";
3
3
  import { isBaseChannel } from "../channels/base.js";
4
4
  import { END, CompiledGraph, Graph, START, Branch, } from "./graph.js";
5
- import { ChannelWrite, PASSTHROUGH, SKIP_WRITE, } from "../pregel/write.js";
5
+ import { ChannelWrite, PASSTHROUGH, } from "../pregel/write.js";
6
6
  import { ChannelRead, PregelNode } from "../pregel/read.js";
7
7
  import { NamedBarrierValue } from "../channels/named_barrier_value.js";
8
8
  import { EphemeralValue } from "../channels/ephemeral_value.js";
9
9
  import { RunnableCallable } from "../utils.js";
10
- import { _isCommand, _isSend, CHECKPOINT_NAMESPACE_END, CHECKPOINT_NAMESPACE_SEPARATOR, Command, SELF, TAG_HIDDEN, } from "../constants.js";
10
+ import { isCommand, _isSend, CHECKPOINT_NAMESPACE_END, CHECKPOINT_NAMESPACE_SEPARATOR, Command, SELF, TAG_HIDDEN, } from "../constants.js";
11
11
  import { InvalidUpdateError, ParentCommand } from "../errors.js";
12
12
  import { getChannel, } from "./annotation.js";
13
13
  import { isConfiguredManagedValue } from "../managed/base.js";
@@ -343,59 +343,101 @@ function _getChannels(schema) {
343
343
  */
344
344
  export class CompiledStateGraph extends CompiledGraph {
345
345
  attachNode(key, node) {
346
- const stateKeys = Object.keys(this.builder.channels);
346
+ let outputKeys;
347
+ if (key === START) {
348
+ // Get input schema keys excluding managed values
349
+ outputKeys = Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition))
350
+ .filter(([_, v]) => !isConfiguredManagedValue(v))
351
+ .map(([k]) => k);
352
+ }
353
+ else {
354
+ outputKeys = Object.keys(this.builder.channels);
355
+ }
356
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
347
357
  function _getRoot(input) {
348
- if (_isCommand(input)) {
358
+ if (isCommand(input)) {
349
359
  if (input.graph === Command.PARENT) {
350
- return SKIP_WRITE;
360
+ return null;
361
+ }
362
+ return input._updateAsTuples();
363
+ }
364
+ else if (Array.isArray(input) &&
365
+ input.length > 0 &&
366
+ input.some((i) => isCommand(i))) {
367
+ const updates = [];
368
+ for (const i of input) {
369
+ if (isCommand(i)) {
370
+ if (i.graph === Command.PARENT) {
371
+ continue;
372
+ }
373
+ updates.push(...i._updateAsTuples());
374
+ }
375
+ else {
376
+ updates.push([ROOT, i]);
377
+ }
351
378
  }
352
- return input.update;
379
+ return updates;
353
380
  }
354
- return input;
381
+ else if (input != null) {
382
+ return [[ROOT, input]];
383
+ }
384
+ return null;
355
385
  }
356
386
  // to avoid name collision below
357
387
  const nodeKey = key;
358
- function getStateKey(key, input) {
388
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
389
+ function _getUpdates(input) {
359
390
  if (!input) {
360
- return SKIP_WRITE;
391
+ return null;
361
392
  }
362
- else if (_isCommand(input)) {
393
+ else if (isCommand(input)) {
363
394
  if (input.graph === Command.PARENT) {
364
- return SKIP_WRITE;
395
+ return null;
365
396
  }
366
- return getStateKey(key, input.update);
397
+ return input._updateAsTuples();
367
398
  }
368
- else if (typeof input !== "object" || Array.isArray(input)) {
399
+ else if (Array.isArray(input) &&
400
+ input.length > 0 &&
401
+ input.some(isCommand)) {
402
+ const updates = [];
403
+ for (const item of input) {
404
+ if (isCommand(item)) {
405
+ if (item.graph === Command.PARENT) {
406
+ continue;
407
+ }
408
+ updates.push(...item._updateAsTuples());
409
+ }
410
+ else {
411
+ const itemUpdates = _getUpdates(item);
412
+ if (itemUpdates) {
413
+ updates.push(...(itemUpdates ?? []));
414
+ }
415
+ }
416
+ }
417
+ return updates;
418
+ }
419
+ else if (typeof input === "object" && !Array.isArray(input)) {
420
+ return Object.entries(input).filter(([k]) => outputKeys.includes(k));
421
+ }
422
+ else {
369
423
  const typeofInput = Array.isArray(input) ? "array" : typeof input;
370
424
  throw new InvalidUpdateError(`Expected node "${nodeKey.toString()}" to return an object, received ${typeofInput}`, {
371
425
  lc_error_code: "INVALID_GRAPH_NODE_RETURN_VALUE",
372
426
  });
373
427
  }
374
- else {
375
- return key in input ? input[key] : SKIP_WRITE;
376
- }
377
428
  }
378
- // state updaters
379
- const stateWriteEntries = stateKeys.map((key) => key === ROOT
380
- ? {
381
- channel: key,
429
+ const stateWriteEntries = [
430
+ {
382
431
  value: PASSTHROUGH,
383
- skipNone: true,
384
432
  mapper: new RunnableCallable({
385
- func: _getRoot,
433
+ func: outputKeys.length && outputKeys[0] === ROOT
434
+ ? _getRoot
435
+ : _getUpdates,
386
436
  trace: false,
387
437
  recurse: false,
388
438
  }),
389
- }
390
- : {
391
- channel: key,
392
- value: PASSTHROUGH,
393
- mapper: new RunnableCallable({
394
- func: getStateKey.bind(null, key),
395
- trace: false,
396
- recurse: false,
397
- }),
398
- });
439
+ },
440
+ ];
399
441
  // add node and output channel
400
442
  if (key === START) {
401
443
  this.nodes[key] = new PregelNode({
@@ -536,7 +578,7 @@ function _controlBranch(value) {
536
578
  if (_isSend(value)) {
537
579
  return [value];
538
580
  }
539
- if (!_isCommand(value)) {
581
+ if (!isCommand(value)) {
540
582
  return [];
541
583
  }
542
584
  if (value.graph === Command.PARENT) {
@@ -108,7 +108,7 @@ function _getModelPreprocessingRunnable(stateModifier, messageModifier) {
108
108
  * ```
109
109
  */
110
110
  function createReactAgent(params) {
111
- const { llm, tools, messageModifier, stateModifier, checkpointSaver, interruptBefore, interruptAfter, store, } = params;
111
+ const { llm, tools, messageModifier, stateModifier, stateSchema, checkpointSaver, interruptBefore, interruptAfter, store, } = params;
112
112
  let toolClasses;
113
113
  if (!Array.isArray(tools)) {
114
114
  toolClasses = tools.tools;
@@ -138,7 +138,7 @@ function createReactAgent(params) {
138
138
  // TODO: Auto-promote streaming.
139
139
  return { messages: [await modelRunnable.invoke(state, config)] };
140
140
  };
141
- const workflow = new index_js_1.StateGraph(messages_annotation_js_1.MessagesAnnotation)
141
+ const workflow = new index_js_1.StateGraph(stateSchema ?? messages_annotation_js_1.MessagesAnnotation)
142
142
  .addNode("agent", callModel)
143
143
  .addNode("tools", new tool_node_js_1.ToolNode(toolClasses))
144
144
  .addEdge(index_js_1.START, "agent")
@@ -3,7 +3,7 @@ import { BaseMessage, BaseMessageLike, SystemMessage } from "@langchain/core/mes
3
3
  import { Runnable, RunnableToolLike } from "@langchain/core/runnables";
4
4
  import { StructuredToolInterface } from "@langchain/core/tools";
5
5
  import { All, BaseCheckpointSaver, BaseStore } from "@langchain/langgraph-checkpoint";
6
- import { START, CompiledStateGraph } from "../graph/index.js";
6
+ import { START, CompiledStateGraph, AnnotationRoot } from "../graph/index.js";
7
7
  import { MessagesAnnotation } from "../graph/messages_annotation.js";
8
8
  import { ToolNode } from "./tool_node.js";
9
9
  import { LangGraphRunnableConfig } from "../pregel/runnable_types.js";
@@ -14,11 +14,11 @@ export type N = typeof START | "agent" | "tools";
14
14
  export type StateModifier = SystemMessage | string | ((state: typeof MessagesAnnotation.State, config: LangGraphRunnableConfig) => BaseMessageLike[]) | ((state: typeof MessagesAnnotation.State, config: LangGraphRunnableConfig) => Promise<BaseMessageLike[]>) | Runnable;
15
15
  /** @deprecated Use StateModifier instead. */
16
16
  export type MessageModifier = SystemMessage | string | ((messages: BaseMessage[]) => BaseMessage[]) | ((messages: BaseMessage[]) => Promise<BaseMessage[]>) | Runnable;
17
- export type CreateReactAgentParams = {
17
+ export type CreateReactAgentParams<A extends AnnotationRoot<any> = AnnotationRoot<any>> = {
18
18
  /** The chat model that can utilize OpenAI-style tool calling. */
19
19
  llm: BaseChatModel;
20
20
  /** A list of tools or a ToolNode. */
21
- tools: ToolNode<typeof MessagesAnnotation.State> | (StructuredToolInterface | RunnableToolLike)[];
21
+ tools: ToolNode | (StructuredToolInterface | RunnableToolLike)[];
22
22
  /**
23
23
  * @deprecated
24
24
  * Use stateModifier instead. stateModifier works the same as
@@ -73,6 +73,7 @@ export type CreateReactAgentParams = {
73
73
  * - Runnable: This runnable should take in full graph state and the output is then passed to the language model.
74
74
  */
75
75
  stateModifier?: StateModifier;
76
+ stateSchema?: A;
76
77
  /** An optional checkpoint saver to persist the agent's state. */
77
78
  checkpointSaver?: BaseCheckpointSaver;
78
79
  /** An optional list of node names to interrupt before running. */
@@ -123,4 +124,4 @@ export type CreateReactAgentParams = {
123
124
  * // Returns the messages in the state at each step of execution
124
125
  * ```
125
126
  */
126
- export declare function createReactAgent(params: CreateReactAgentParams): CompiledStateGraph<(typeof MessagesAnnotation)["State"], (typeof MessagesAnnotation)["Update"], typeof START | "agent" | "tools">;
127
+ export declare function createReactAgent<A extends AnnotationRoot<any> = AnnotationRoot<any>>(params: CreateReactAgentParams<A>): CompiledStateGraph<(typeof MessagesAnnotation)["State"], (typeof MessagesAnnotation)["Update"], typeof START | "agent" | "tools", typeof MessagesAnnotation.spec & A["spec"], typeof MessagesAnnotation.spec & A["spec"]>;
@@ -1,6 +1,6 @@
1
1
  import { isAIMessage, isBaseMessage, SystemMessage, } from "@langchain/core/messages";
2
2
  import { Runnable, RunnableLambda, } from "@langchain/core/runnables";
3
- import { END, START, StateGraph } from "../graph/index.js";
3
+ import { END, START, StateGraph, } from "../graph/index.js";
4
4
  import { MessagesAnnotation } from "../graph/messages_annotation.js";
5
5
  import { ToolNode } from "./tool_node.js";
6
6
  function _convertMessageModifierToStateModifier(messageModifier) {
@@ -105,7 +105,7 @@ function _getModelPreprocessingRunnable(stateModifier, messageModifier) {
105
105
  * ```
106
106
  */
107
107
  export function createReactAgent(params) {
108
- const { llm, tools, messageModifier, stateModifier, checkpointSaver, interruptBefore, interruptAfter, store, } = params;
108
+ const { llm, tools, messageModifier, stateModifier, stateSchema, checkpointSaver, interruptBefore, interruptAfter, store, } = params;
109
109
  let toolClasses;
110
110
  if (!Array.isArray(tools)) {
111
111
  toolClasses = tools.tools;
@@ -135,7 +135,7 @@ export function createReactAgent(params) {
135
135
  // TODO: Auto-promote streaming.
136
136
  return { messages: [await modelRunnable.invoke(state, config)] };
137
137
  };
138
- const workflow = new StateGraph(MessagesAnnotation)
138
+ const workflow = new StateGraph(stateSchema ?? MessagesAnnotation)
139
139
  .addNode("agent", callModel)
140
140
  .addNode("tools", new ToolNode(toolClasses))
141
141
  .addEdge(START, "agent")
@@ -5,6 +5,7 @@ const messages_1 = require("@langchain/core/messages");
5
5
  const utils_js_1 = require("../utils.cjs");
6
6
  const graph_js_1 = require("../graph/graph.cjs");
7
7
  const errors_js_1 = require("../errors.cjs");
8
+ const constants_js_1 = require("../constants.cjs");
8
9
  /**
9
10
  * A node that runs the tools requested in the last AIMessage. It can be used
10
11
  * either in StateGraph with a "messages" key or in MessageGraph. If multiple
@@ -163,7 +164,8 @@ class ToolNode extends utils_js_1.RunnableCallable {
163
164
  throw new Error(`Tool "${call.name}" not found.`);
164
165
  }
165
166
  const output = await tool.invoke({ ...call, type: "tool_call" }, config);
166
- if ((0, messages_1.isBaseMessage)(output) && output._getType() === "tool") {
167
+ if (((0, messages_1.isBaseMessage)(output) && output._getType() === "tool") ||
168
+ (0, constants_js_1.isCommand)(output)) {
167
169
  return output;
168
170
  }
169
171
  else {
@@ -192,7 +194,18 @@ class ToolNode extends utils_js_1.RunnableCallable {
192
194
  });
193
195
  }
194
196
  }) ?? []);
195
- return (Array.isArray(input) ? outputs : { messages: outputs });
197
+ // Preserve existing behavior for non-command tool outputs for backwards compatibility
198
+ if (!outputs.some(constants_js_1.isCommand)) {
199
+ return (Array.isArray(input) ? outputs : { messages: outputs });
200
+ }
201
+ // Handle mixed Command and non-Command outputs
202
+ const combinedOutputs = outputs.map((output) => {
203
+ if ((0, constants_js_1.isCommand)(output)) {
204
+ return output;
205
+ }
206
+ return Array.isArray(input) ? [output] : { messages: [output] };
207
+ });
208
+ return combinedOutputs;
196
209
  }
197
210
  }
198
211
  exports.ToolNode = ToolNode;
@@ -2,6 +2,7 @@ import { ToolMessage, isBaseMessage, } from "@langchain/core/messages";
2
2
  import { RunnableCallable } from "../utils.js";
3
3
  import { END } from "../graph/graph.js";
4
4
  import { isGraphInterrupt } from "../errors.js";
5
+ import { isCommand } from "../constants.js";
5
6
  /**
6
7
  * A node that runs the tools requested in the last AIMessage. It can be used
7
8
  * either in StateGraph with a "messages" key or in MessageGraph. If multiple
@@ -160,7 +161,8 @@ export class ToolNode extends RunnableCallable {
160
161
  throw new Error(`Tool "${call.name}" not found.`);
161
162
  }
162
163
  const output = await tool.invoke({ ...call, type: "tool_call" }, config);
163
- if (isBaseMessage(output) && output._getType() === "tool") {
164
+ if ((isBaseMessage(output) && output._getType() === "tool") ||
165
+ isCommand(output)) {
164
166
  return output;
165
167
  }
166
168
  else {
@@ -189,7 +191,18 @@ export class ToolNode extends RunnableCallable {
189
191
  });
190
192
  }
191
193
  }) ?? []);
192
- return (Array.isArray(input) ? outputs : { messages: outputs });
194
+ // Preserve existing behavior for non-command tool outputs for backwards compatibility
195
+ if (!outputs.some(isCommand)) {
196
+ return (Array.isArray(input) ? outputs : { messages: outputs });
197
+ }
198
+ // Handle mixed Command and non-Command outputs
199
+ const combinedOutputs = outputs.map((output) => {
200
+ if (isCommand(output)) {
201
+ return output;
202
+ }
203
+ return Array.isArray(input) ? [output] : { messages: [output] };
204
+ });
205
+ return combinedOutputs;
193
206
  }
194
207
  }
195
208
  export function toolsCondition(state) {
@@ -587,8 +587,8 @@ class PregelLoop {
587
587
  const isResuming = Object.keys(this.checkpoint.channel_versions).length !== 0 &&
588
588
  (this.config.configurable?.[constants_js_1.CONFIG_KEY_RESUMING] !== undefined ||
589
589
  this.input === null ||
590
- (0, constants_js_1._isCommand)(this.input));
591
- if ((0, constants_js_1._isCommand)(this.input)) {
590
+ (0, constants_js_1.isCommand)(this.input));
591
+ if ((0, constants_js_1.isCommand)(this.input)) {
592
592
  const writes = {};
593
593
  // group writes by task id
594
594
  for (const [tid, key, value] of (0, io_js_1.mapCommand)(this.input, this.checkpointPendingWrites)) {
@@ -1,7 +1,7 @@
1
1
  import { IterableReadableStream } from "@langchain/core/utils/stream";
2
2
  import { copyCheckpoint, emptyCheckpoint, AsyncBatchedStore, WRITES_IDX_MAP, } from "@langchain/langgraph-checkpoint";
3
3
  import { createCheckpoint, emptyChannels, } from "../channels/base.js";
4
- import { _isCommand, CHECKPOINT_NAMESPACE_SEPARATOR, CONFIG_KEY_CHECKPOINT_MAP, CONFIG_KEY_READ, CONFIG_KEY_RESUMING, CONFIG_KEY_STREAM, ERROR, INPUT, INTERRUPT, NULL_TASK_ID, RESUME, TAG_HIDDEN, } from "../constants.js";
4
+ import { isCommand, CHECKPOINT_NAMESPACE_SEPARATOR, CONFIG_KEY_CHECKPOINT_MAP, CONFIG_KEY_READ, CONFIG_KEY_RESUMING, CONFIG_KEY_STREAM, ERROR, INPUT, INTERRUPT, NULL_TASK_ID, RESUME, TAG_HIDDEN, } from "../constants.js";
5
5
  import { _applyWrites, _prepareNextTasks, increment, shouldInterrupt, } from "./algo.js";
6
6
  import { gatherIterator, gatherIteratorSync, prefixGenerator, } from "../utils.js";
7
7
  import { mapCommand, mapInput, mapOutputUpdates, mapOutputValues, readChannels, } from "./io.js";
@@ -583,8 +583,8 @@ export class PregelLoop {
583
583
  const isResuming = Object.keys(this.checkpoint.channel_versions).length !== 0 &&
584
584
  (this.config.configurable?.[CONFIG_KEY_RESUMING] !== undefined ||
585
585
  this.input === null ||
586
- _isCommand(this.input));
587
- if (_isCommand(this.input)) {
586
+ isCommand(this.input));
587
+ if (isCommand(this.input)) {
588
588
  const writes = {};
589
589
  // group writes by task id
590
590
  for (const [tid, key, value] of mapCommand(this.input, this.checkpointPendingWrites)) {
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ChannelWrite = exports.PASSTHROUGH = exports.SKIP_WRITE = void 0;
4
+ const runnables_1 = require("@langchain/core/runnables");
4
5
  const constants_js_1 = require("../constants.cjs");
5
6
  const utils_js_1 = require("../utils.cjs");
6
7
  const errors_js_1 = require("../errors.cjs");
@@ -29,7 +30,13 @@ class ChannelWrite extends utils_js_1.RunnableCallable {
29
30
  constructor(writes, tags) {
30
31
  const name = `ChannelWrite<${writes
31
32
  .map((packet) => {
32
- return (0, constants_js_1._isSend)(packet) ? packet.node : packet.channel;
33
+ if ((0, constants_js_1._isSend)(packet)) {
34
+ return packet.node;
35
+ }
36
+ else if ("channel" in packet) {
37
+ return packet.channel;
38
+ }
39
+ return "...";
33
40
  })
34
41
  .join(",")}>`;
35
42
  super({
@@ -48,7 +55,13 @@ class ChannelWrite extends utils_js_1.RunnableCallable {
48
55
  }
49
56
  async _write(input, config) {
50
57
  const writes = this.writes.map((write) => {
51
- if (_isChannelWriteEntry(write) && _isPassthrough(write.value)) {
58
+ if (_isChannelWriteTupleEntry(write) && _isPassthrough(write.value)) {
59
+ return {
60
+ mapper: write.mapper,
61
+ value: input,
62
+ };
63
+ }
64
+ else if (_isChannelWriteEntry(write) && _isPassthrough(write.value)) {
52
65
  return {
53
66
  channel: write.channel,
54
67
  value: input,
@@ -65,36 +78,52 @@ class ChannelWrite extends utils_js_1.RunnableCallable {
65
78
  }
66
79
  // TODO: Support requireAtLeastOneOf
67
80
  static async doWrite(config, writes) {
68
- const sends = writes.filter(constants_js_1._isSend).map((packet) => {
69
- return [constants_js_1.TASKS, packet];
70
- });
71
- const entries = writes.filter((write) => {
72
- return !(0, constants_js_1._isSend)(write);
73
- });
74
- const invalidEntry = entries.find((write) => {
75
- return write.channel === constants_js_1.TASKS;
76
- });
77
- if (invalidEntry) {
78
- throw new errors_js_1.InvalidUpdateError(`Cannot write to the reserved channel ${constants_js_1.TASKS}`);
81
+ // validate
82
+ for (const w of writes) {
83
+ if (_isChannelWriteEntry(w)) {
84
+ if (w.channel === constants_js_1.TASKS) {
85
+ throw new errors_js_1.InvalidUpdateError("Cannot write to the reserved channel TASKS");
86
+ }
87
+ if (_isPassthrough(w.value)) {
88
+ throw new errors_js_1.InvalidUpdateError("PASSTHROUGH value must be replaced");
89
+ }
90
+ }
91
+ if (_isChannelWriteTupleEntry(w)) {
92
+ if (_isPassthrough(w.value)) {
93
+ throw new errors_js_1.InvalidUpdateError("PASSTHROUGH value must be replaced");
94
+ }
95
+ }
96
+ }
97
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
98
+ const writeEntries = [];
99
+ for (const w of writes) {
100
+ if ((0, constants_js_1._isSend)(w)) {
101
+ writeEntries.push([constants_js_1.TASKS, w]);
102
+ }
103
+ else if (_isChannelWriteTupleEntry(w)) {
104
+ const mappedResult = await w.mapper.invoke(w.value, config);
105
+ if (mappedResult != null && mappedResult.length > 0) {
106
+ writeEntries.push(...mappedResult);
107
+ }
108
+ }
109
+ else if (_isChannelWriteEntry(w)) {
110
+ const mappedValue = w.mapper !== undefined
111
+ ? await w.mapper.invoke(w.value, config)
112
+ : w.value;
113
+ if (_isSkipWrite(mappedValue)) {
114
+ continue;
115
+ }
116
+ if (w.skipNone && mappedValue === undefined) {
117
+ continue;
118
+ }
119
+ writeEntries.push([w.channel, mappedValue]);
120
+ }
121
+ else {
122
+ throw new Error(`Invalid write entry: ${JSON.stringify(w)}`);
123
+ }
79
124
  }
80
- const values = await Promise.all(entries.map(async (write) => {
81
- const mappedValue = write.mapper
82
- ? await write.mapper.invoke(write.value, config)
83
- : write.value;
84
- return {
85
- ...write,
86
- value: mappedValue,
87
- };
88
- })).then((writes) => {
89
- return writes
90
- .filter((write) => !write.skipNone || write.value !== null)
91
- .map((write) => {
92
- return [write.channel, write.value];
93
- });
94
- });
95
125
  const write = config.configurable?.[constants_js_1.CONFIG_KEY_SEND];
96
- const filtered = values.filter(([_, value]) => !_isSkipWrite(value));
97
- write([...sends, ...filtered]);
126
+ write(writeEntries);
98
127
  }
99
128
  static isWriter(runnable) {
100
129
  return (
@@ -110,3 +139,8 @@ exports.ChannelWrite = ChannelWrite;
110
139
  function _isChannelWriteEntry(x) {
111
140
  return (x !== undefined && typeof x.channel === "string");
112
141
  }
142
+ function _isChannelWriteTupleEntry(x) {
143
+ return (x !== undefined &&
144
+ !_isChannelWriteEntry(x) &&
145
+ runnables_1.Runnable.isRunnable(x.mapper));
146
+ }
@@ -12,10 +12,10 @@ export declare const PASSTHROUGH: {
12
12
  * or None to skip writing.
13
13
  */
14
14
  export declare class ChannelWrite<RunInput = any> extends RunnableCallable {
15
- writes: Array<ChannelWriteEntry | Send>;
16
- constructor(writes: Array<ChannelWriteEntry | Send>, tags?: string[]);
15
+ writes: Array<ChannelWriteEntry | ChannelWriteTupleEntry | Send>;
16
+ constructor(writes: Array<ChannelWriteEntry | ChannelWriteTupleEntry | Send>, tags?: string[]);
17
17
  _write(input: unknown, config: RunnableConfig): Promise<unknown>;
18
- static doWrite(config: RunnableConfig, writes: (ChannelWriteEntry | Send)[]): Promise<void>;
18
+ static doWrite(config: RunnableConfig, writes: (ChannelWriteEntry | ChannelWriteTupleEntry | Send)[]): Promise<void>;
19
19
  static isWriter(runnable: RunnableLike): runnable is ChannelWrite;
20
20
  static registerWriter<T extends Runnable>(runnable: T): T;
21
21
  }
@@ -25,3 +25,7 @@ export interface ChannelWriteEntry {
25
25
  skipNone?: boolean;
26
26
  mapper?: Runnable;
27
27
  }
28
+ export interface ChannelWriteTupleEntry {
29
+ value: unknown;
30
+ mapper: Runnable<any, [string, any][]>;
31
+ }
@@ -1,3 +1,4 @@
1
+ import { Runnable, } from "@langchain/core/runnables";
1
2
  import { _isSend, CONFIG_KEY_SEND, TASKS } from "../constants.js";
2
3
  import { RunnableCallable } from "../utils.js";
3
4
  import { InvalidUpdateError } from "../errors.js";
@@ -26,7 +27,13 @@ export class ChannelWrite extends RunnableCallable {
26
27
  constructor(writes, tags) {
27
28
  const name = `ChannelWrite<${writes
28
29
  .map((packet) => {
29
- return _isSend(packet) ? packet.node : packet.channel;
30
+ if (_isSend(packet)) {
31
+ return packet.node;
32
+ }
33
+ else if ("channel" in packet) {
34
+ return packet.channel;
35
+ }
36
+ return "...";
30
37
  })
31
38
  .join(",")}>`;
32
39
  super({
@@ -45,7 +52,13 @@ export class ChannelWrite extends RunnableCallable {
45
52
  }
46
53
  async _write(input, config) {
47
54
  const writes = this.writes.map((write) => {
48
- if (_isChannelWriteEntry(write) && _isPassthrough(write.value)) {
55
+ if (_isChannelWriteTupleEntry(write) && _isPassthrough(write.value)) {
56
+ return {
57
+ mapper: write.mapper,
58
+ value: input,
59
+ };
60
+ }
61
+ else if (_isChannelWriteEntry(write) && _isPassthrough(write.value)) {
49
62
  return {
50
63
  channel: write.channel,
51
64
  value: input,
@@ -62,36 +75,52 @@ export class ChannelWrite extends RunnableCallable {
62
75
  }
63
76
  // TODO: Support requireAtLeastOneOf
64
77
  static async doWrite(config, writes) {
65
- const sends = writes.filter(_isSend).map((packet) => {
66
- return [TASKS, packet];
67
- });
68
- const entries = writes.filter((write) => {
69
- return !_isSend(write);
70
- });
71
- const invalidEntry = entries.find((write) => {
72
- return write.channel === TASKS;
73
- });
74
- if (invalidEntry) {
75
- throw new InvalidUpdateError(`Cannot write to the reserved channel ${TASKS}`);
78
+ // validate
79
+ for (const w of writes) {
80
+ if (_isChannelWriteEntry(w)) {
81
+ if (w.channel === TASKS) {
82
+ throw new InvalidUpdateError("Cannot write to the reserved channel TASKS");
83
+ }
84
+ if (_isPassthrough(w.value)) {
85
+ throw new InvalidUpdateError("PASSTHROUGH value must be replaced");
86
+ }
87
+ }
88
+ if (_isChannelWriteTupleEntry(w)) {
89
+ if (_isPassthrough(w.value)) {
90
+ throw new InvalidUpdateError("PASSTHROUGH value must be replaced");
91
+ }
92
+ }
93
+ }
94
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
95
+ const writeEntries = [];
96
+ for (const w of writes) {
97
+ if (_isSend(w)) {
98
+ writeEntries.push([TASKS, w]);
99
+ }
100
+ else if (_isChannelWriteTupleEntry(w)) {
101
+ const mappedResult = await w.mapper.invoke(w.value, config);
102
+ if (mappedResult != null && mappedResult.length > 0) {
103
+ writeEntries.push(...mappedResult);
104
+ }
105
+ }
106
+ else if (_isChannelWriteEntry(w)) {
107
+ const mappedValue = w.mapper !== undefined
108
+ ? await w.mapper.invoke(w.value, config)
109
+ : w.value;
110
+ if (_isSkipWrite(mappedValue)) {
111
+ continue;
112
+ }
113
+ if (w.skipNone && mappedValue === undefined) {
114
+ continue;
115
+ }
116
+ writeEntries.push([w.channel, mappedValue]);
117
+ }
118
+ else {
119
+ throw new Error(`Invalid write entry: ${JSON.stringify(w)}`);
120
+ }
76
121
  }
77
- const values = await Promise.all(entries.map(async (write) => {
78
- const mappedValue = write.mapper
79
- ? await write.mapper.invoke(write.value, config)
80
- : write.value;
81
- return {
82
- ...write,
83
- value: mappedValue,
84
- };
85
- })).then((writes) => {
86
- return writes
87
- .filter((write) => !write.skipNone || write.value !== null)
88
- .map((write) => {
89
- return [write.channel, write.value];
90
- });
91
- });
92
122
  const write = config.configurable?.[CONFIG_KEY_SEND];
93
- const filtered = values.filter(([_, value]) => !_isSkipWrite(value));
94
- write([...sends, ...filtered]);
123
+ write(writeEntries);
95
124
  }
96
125
  static isWriter(runnable) {
97
126
  return (
@@ -106,3 +135,8 @@ export class ChannelWrite extends RunnableCallable {
106
135
  function _isChannelWriteEntry(x) {
107
136
  return (x !== undefined && typeof x.channel === "string");
108
137
  }
138
+ function _isChannelWriteTupleEntry(x) {
139
+ return (x !== undefined &&
140
+ !_isChannelWriteEntry(x) &&
141
+ Runnable.isRunnable(x.mapper));
142
+ }
package/dist/web.cjs CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.MessagesAnnotation = exports.InMemoryStore = exports.AsyncBatchedStore = exports.BaseStore = exports.BaseCheckpointSaver = exports.emptyCheckpoint = exports.copyCheckpoint = exports.MemorySaver = exports.interrupt = exports.Command = exports.Send = exports.BinaryOperatorAggregate = exports.BaseChannel = exports.Annotation = exports.messagesStateReducer = exports.MessageGraph = exports.CompiledStateGraph = exports.StateGraph = exports.START = exports.Graph = exports.END = void 0;
17
+ exports.MessagesAnnotation = exports.InMemoryStore = exports.AsyncBatchedStore = exports.BaseStore = exports.BaseCheckpointSaver = exports.emptyCheckpoint = exports.copyCheckpoint = exports.MemorySaver = exports.interrupt = exports.isCommand = exports.Command = exports.Send = exports.BinaryOperatorAggregate = exports.BaseChannel = exports.Annotation = exports.messagesStateReducer = exports.MessageGraph = exports.CompiledStateGraph = exports.StateGraph = exports.START = exports.Graph = exports.END = void 0;
18
18
  var index_js_1 = require("./graph/index.cjs");
19
19
  Object.defineProperty(exports, "END", { enumerable: true, get: function () { return index_js_1.END; } });
20
20
  Object.defineProperty(exports, "Graph", { enumerable: true, get: function () { return index_js_1.Graph; } });
@@ -31,6 +31,7 @@ Object.defineProperty(exports, "BinaryOperatorAggregate", { enumerable: true, ge
31
31
  var constants_js_1 = require("./constants.cjs");
32
32
  Object.defineProperty(exports, "Send", { enumerable: true, get: function () { return constants_js_1.Send; } });
33
33
  Object.defineProperty(exports, "Command", { enumerable: true, get: function () { return constants_js_1.Command; } });
34
+ Object.defineProperty(exports, "isCommand", { enumerable: true, get: function () { return constants_js_1.isCommand; } });
34
35
  var interrupt_js_1 = require("./interrupt.cjs");
35
36
  Object.defineProperty(exports, "interrupt", { enumerable: true, get: function () { return interrupt_js_1.interrupt; } });
36
37
  var langgraph_checkpoint_1 = require("@langchain/langgraph-checkpoint");
package/dist/web.d.ts CHANGED
@@ -4,7 +4,7 @@ export * from "./errors.js";
4
4
  export { BaseChannel, type BinaryOperator, BinaryOperatorAggregate, type AnyValue, type WaitForNames, type DynamicBarrierValue, type LastValue, type NamedBarrierValue, type Topic, } from "./channels/index.js";
5
5
  export { type AnnotationRoot as _INTERNAL_ANNOTATION_ROOT } from "./graph/index.js";
6
6
  export { type RetryPolicy } from "./pregel/utils/index.js";
7
- export { Send, Command, type CommandParams, type Interrupt, } from "./constants.js";
7
+ export { Send, Command, type CommandParams, isCommand, type Interrupt, } from "./constants.js";
8
8
  export { interrupt } from "./interrupt.js";
9
9
  export { MemorySaver, type Checkpoint, type CheckpointMetadata, type CheckpointTuple, copyCheckpoint, emptyCheckpoint, BaseCheckpointSaver, type Item, type GetOperation, type SearchOperation, type PutOperation, type Operation, type OperationResults, BaseStore, AsyncBatchedStore, InMemoryStore, type NameSpacePath, type NamespaceMatchType, type MatchCondition, type ListNamespacesOperation, } from "@langchain/langgraph-checkpoint";
10
10
  export * from "./managed/index.js";
package/dist/web.js CHANGED
@@ -1,7 +1,7 @@
1
1
  export { END, Graph, START, StateGraph, CompiledStateGraph, MessageGraph, messagesStateReducer, Annotation, } from "./graph/index.js";
2
2
  export * from "./errors.js";
3
3
  export { BaseChannel, BinaryOperatorAggregate, } from "./channels/index.js";
4
- export { Send, Command, } from "./constants.js";
4
+ export { Send, Command, isCommand, } from "./constants.js";
5
5
  export { interrupt } from "./interrupt.js";
6
6
  export { MemorySaver, copyCheckpoint, emptyCheckpoint, BaseCheckpointSaver, BaseStore, AsyncBatchedStore, InMemoryStore, } from "@langchain/langgraph-checkpoint";
7
7
  export * from "./managed/index.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langchain/langgraph",
3
- "version": "0.2.32",
3
+ "version": "0.2.33",
4
4
  "description": "LangGraph",
5
5
  "type": "module",
6
6
  "engines": {
@@ -43,7 +43,7 @@
43
43
  "@jest/globals": "^29.5.0",
44
44
  "@langchain/anthropic": "^0.3.5",
45
45
  "@langchain/community": "^0.3.9",
46
- "@langchain/core": "^0.3.22",
46
+ "@langchain/core": "^0.3.23",
47
47
  "@langchain/langgraph-checkpoint-postgres": "workspace:*",
48
48
  "@langchain/langgraph-checkpoint-sqlite": "workspace:*",
49
49
  "@langchain/openai": "^0.3.11",