@langchain/langgraph 1.3.7 → 1.4.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.
- package/dist/channels/base.cjs +78 -2
- package/dist/channels/base.cjs.map +1 -1
- package/dist/channels/base.d.cts +35 -2
- package/dist/channels/base.d.cts.map +1 -1
- package/dist/channels/base.d.ts +35 -2
- package/dist/channels/base.d.ts.map +1 -1
- package/dist/channels/base.js +77 -4
- package/dist/channels/base.js.map +1 -1
- package/dist/channels/delta.cjs +136 -0
- package/dist/channels/delta.cjs.map +1 -0
- package/dist/channels/delta.d.cts +99 -0
- package/dist/channels/delta.d.cts.map +1 -0
- package/dist/channels/delta.d.ts +99 -0
- package/dist/channels/delta.d.ts.map +1 -0
- package/dist/channels/delta.js +136 -0
- package/dist/channels/delta.js.map +1 -0
- package/dist/channels/index.cjs +5 -0
- package/dist/channels/index.d.cts +3 -2
- package/dist/channels/index.d.ts +3 -2
- package/dist/channels/index.js +3 -2
- package/dist/constants.cjs +62 -4
- package/dist/constants.cjs.map +1 -1
- package/dist/constants.d.cts +33 -2
- package/dist/constants.d.cts.map +1 -1
- package/dist/constants.d.ts +33 -2
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +59 -5
- package/dist/constants.js.map +1 -1
- package/dist/errors.cjs +128 -0
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts +86 -1
- package/dist/errors.d.cts.map +1 -1
- package/dist/errors.d.ts +86 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +123 -1
- package/dist/errors.js.map +1 -1
- package/dist/func/index.cjs +9 -2
- package/dist/func/index.cjs.map +1 -1
- package/dist/func/index.d.cts +14 -0
- package/dist/func/index.d.cts.map +1 -1
- package/dist/func/index.d.ts +14 -0
- package/dist/func/index.d.ts.map +1 -1
- package/dist/func/index.js +9 -2
- package/dist/func/index.js.map +1 -1
- package/dist/graph/graph.cjs +44 -7
- package/dist/graph/graph.cjs.map +1 -1
- package/dist/graph/graph.d.cts +24 -2
- package/dist/graph/graph.d.cts.map +1 -1
- package/dist/graph/graph.d.ts +24 -2
- package/dist/graph/graph.d.ts.map +1 -1
- package/dist/graph/graph.js +44 -7
- package/dist/graph/graph.js.map +1 -1
- package/dist/graph/index.d.ts +3 -3
- package/dist/graph/messages_reducer.cjs +55 -0
- package/dist/graph/messages_reducer.cjs.map +1 -1
- package/dist/graph/messages_reducer.d.cts +28 -1
- package/dist/graph/messages_reducer.d.cts.map +1 -1
- package/dist/graph/messages_reducer.d.ts +28 -1
- package/dist/graph/messages_reducer.d.ts.map +1 -1
- package/dist/graph/messages_reducer.js +56 -2
- package/dist/graph/messages_reducer.js.map +1 -1
- package/dist/graph/state.cjs +174 -7
- package/dist/graph/state.cjs.map +1 -1
- package/dist/graph/state.d.cts +193 -17
- package/dist/graph/state.d.cts.map +1 -1
- package/dist/graph/state.d.ts +193 -17
- package/dist/graph/state.d.ts.map +1 -1
- package/dist/graph/state.js +175 -8
- package/dist/graph/state.js.map +1 -1
- package/dist/graph/zod/schema.cjs +5 -0
- package/dist/graph/zod/schema.cjs.map +1 -1
- package/dist/graph/zod/schema.d.cts.map +1 -1
- package/dist/graph/zod/schema.d.ts.map +1 -1
- package/dist/graph/zod/schema.js +5 -0
- package/dist/graph/zod/schema.js.map +1 -1
- package/dist/index.cjs +11 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -8
- package/dist/index.d.ts +11 -8
- package/dist/index.js +5 -3
- package/dist/index.js.map +1 -1
- package/dist/prebuilt/react_agent_executor.d.cts +1 -1
- package/dist/pregel/algo.cjs +182 -21
- package/dist/pregel/algo.cjs.map +1 -1
- package/dist/pregel/algo.d.cts +1 -1
- package/dist/pregel/algo.d.cts.map +1 -1
- package/dist/pregel/algo.d.ts +1 -1
- package/dist/pregel/algo.d.ts.map +1 -1
- package/dist/pregel/algo.js +185 -25
- package/dist/pregel/algo.js.map +1 -1
- package/dist/pregel/call.cjs +2 -1
- package/dist/pregel/call.cjs.map +1 -1
- package/dist/pregel/call.js +2 -1
- package/dist/pregel/call.js.map +1 -1
- package/dist/pregel/index.cjs +15 -3
- package/dist/pregel/index.cjs.map +1 -1
- package/dist/pregel/index.d.cts.map +1 -1
- package/dist/pregel/index.d.ts.map +1 -1
- package/dist/pregel/index.js +17 -5
- package/dist/pregel/index.js.map +1 -1
- package/dist/pregel/loop.cjs +362 -41
- package/dist/pregel/loop.cjs.map +1 -1
- package/dist/pregel/loop.js +365 -44
- package/dist/pregel/loop.js.map +1 -1
- package/dist/pregel/messages-v2.cjs +1 -1
- package/dist/pregel/messages-v2.js +1 -1
- package/dist/pregel/messages.cjs +1 -1
- package/dist/pregel/messages.js +1 -1
- package/dist/pregel/read.cjs +15 -5
- package/dist/pregel/read.cjs.map +1 -1
- package/dist/pregel/read.d.cts +9 -0
- package/dist/pregel/read.d.cts.map +1 -1
- package/dist/pregel/read.d.ts +9 -0
- package/dist/pregel/read.d.ts.map +1 -1
- package/dist/pregel/read.js +15 -5
- package/dist/pregel/read.js.map +1 -1
- package/dist/pregel/remote-run-stream.cjs +107 -0
- package/dist/pregel/remote-run-stream.cjs.map +1 -0
- package/dist/pregel/remote-run-stream.d.cts +33 -0
- package/dist/pregel/remote-run-stream.d.cts.map +1 -0
- package/dist/pregel/remote-run-stream.d.ts +33 -0
- package/dist/pregel/remote-run-stream.d.ts.map +1 -0
- package/dist/pregel/remote-run-stream.js +107 -0
- package/dist/pregel/remote-run-stream.js.map +1 -0
- package/dist/pregel/remote.cjs +61 -1
- package/dist/pregel/remote.cjs.map +1 -1
- package/dist/pregel/remote.d.cts +17 -0
- package/dist/pregel/remote.d.cts.map +1 -1
- package/dist/pregel/remote.d.ts +17 -0
- package/dist/pregel/remote.d.ts.map +1 -1
- package/dist/pregel/remote.js +61 -1
- package/dist/pregel/remote.js.map +1 -1
- package/dist/pregel/replay.cjs +62 -0
- package/dist/pregel/replay.cjs.map +1 -0
- package/dist/pregel/replay.js +62 -0
- package/dist/pregel/replay.js.map +1 -0
- package/dist/pregel/retry.cjs +8 -6
- package/dist/pregel/retry.cjs.map +1 -1
- package/dist/pregel/retry.js +8 -6
- package/dist/pregel/retry.js.map +1 -1
- package/dist/pregel/runnable_types.d.cts +20 -0
- package/dist/pregel/runnable_types.d.cts.map +1 -1
- package/dist/pregel/runnable_types.d.ts +20 -0
- package/dist/pregel/runnable_types.d.ts.map +1 -1
- package/dist/pregel/runner.cjs +48 -7
- package/dist/pregel/runner.cjs.map +1 -1
- package/dist/pregel/runner.js +50 -9
- package/dist/pregel/runner.js.map +1 -1
- package/dist/pregel/runtime.cjs +64 -0
- package/dist/pregel/runtime.cjs.map +1 -0
- package/dist/pregel/runtime.d.cts +57 -0
- package/dist/pregel/runtime.d.cts.map +1 -0
- package/dist/pregel/runtime.d.ts +57 -0
- package/dist/pregel/runtime.d.ts.map +1 -0
- package/dist/pregel/runtime.js +64 -0
- package/dist/pregel/runtime.js.map +1 -0
- package/dist/pregel/stream.cjs +2 -0
- package/dist/pregel/stream.cjs.map +1 -1
- package/dist/pregel/stream.js +2 -0
- package/dist/pregel/stream.js.map +1 -1
- package/dist/pregel/timeout.cjs +216 -0
- package/dist/pregel/timeout.cjs.map +1 -0
- package/dist/pregel/timeout.js +216 -0
- package/dist/pregel/timeout.js.map +1 -0
- package/dist/pregel/types.cjs +3 -1
- package/dist/pregel/types.cjs.map +1 -1
- package/dist/pregel/types.d.cts +13 -0
- package/dist/pregel/types.d.cts.map +1 -1
- package/dist/pregel/types.d.ts +14 -1
- package/dist/pregel/types.d.ts.map +1 -1
- package/dist/pregel/types.js +3 -1
- package/dist/pregel/types.js.map +1 -1
- package/dist/pregel/utils/config.cjs +3 -1
- package/dist/pregel/utils/config.cjs.map +1 -1
- package/dist/pregel/utils/config.d.cts.map +1 -1
- package/dist/pregel/utils/config.d.ts.map +1 -1
- package/dist/pregel/utils/config.js +3 -1
- package/dist/pregel/utils/config.js.map +1 -1
- package/dist/pregel/utils/index.cjs +1 -0
- package/dist/pregel/utils/index.cjs.map +1 -1
- package/dist/pregel/utils/index.d.cts +6 -1
- package/dist/pregel/utils/index.d.cts.map +1 -1
- package/dist/pregel/utils/index.d.ts +6 -1
- package/dist/pregel/utils/index.d.ts.map +1 -1
- package/dist/pregel/utils/index.js +1 -0
- package/dist/pregel/utils/index.js.map +1 -1
- package/dist/pregel/utils/timeout.cjs +34 -0
- package/dist/pregel/utils/timeout.cjs.map +1 -0
- package/dist/pregel/utils/timeout.d.cts +45 -0
- package/dist/pregel/utils/timeout.d.cts.map +1 -0
- package/dist/pregel/utils/timeout.d.ts +45 -0
- package/dist/pregel/utils/timeout.d.ts.map +1 -0
- package/dist/pregel/utils/timeout.js +34 -0
- package/dist/pregel/utils/timeout.js.map +1 -0
- package/dist/web.cjs +11 -0
- package/dist/web.d.cts +11 -8
- package/dist/web.d.ts +11 -8
- package/dist/web.js +5 -3
- package/package.json +5 -5
package/dist/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import { Command, Interrupt } from \"./constants.js\";\n\n// When editing, make sure to update the index found here:\n// https://langchain-ai.github.io/langgraphjs/troubleshooting/errors/\nexport type BaseLangGraphErrorFields = {\n lc_error_code?:\n | \"GRAPH_RECURSION_LIMIT\"\n | \"INVALID_CONCURRENT_GRAPH_UPDATE\"\n | \"INVALID_GRAPH_NODE_RETURN_VALUE\"\n | \"MISSING_CHECKPOINTER\"\n | \"MULTIPLE_SUBGRAPHS\"\n | \"UNREACHABLE_NODE\";\n};\n\n// TODO: Merge with base LangChain error class when we drop support for core@0.2.0\n/** @category Errors */\nexport class BaseLangGraphError extends Error {\n lc_error_code?: string;\n\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n let finalMessage = message ?? \"\";\n if (fields?.lc_error_code) {\n finalMessage = `${finalMessage}\\n\\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${fields.lc_error_code}/\\n`;\n }\n super(finalMessage);\n this.lc_error_code = fields?.lc_error_code;\n }\n}\n\nexport class GraphBubbleUp extends BaseLangGraphError {\n get is_bubble_up() {\n return true;\n }\n}\n\nexport class GraphRecursionError extends BaseLangGraphError {\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n super(message, fields);\n this.name = \"GraphRecursionError\";\n }\n\n static get unminifiable_name() {\n return \"GraphRecursionError\";\n }\n}\n\nexport class GraphValueError extends BaseLangGraphError {\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n super(message, fields);\n this.name = \"GraphValueError\";\n }\n\n static get unminifiable_name() {\n return \"GraphValueError\";\n }\n}\n\nexport class GraphInterrupt extends GraphBubbleUp {\n interrupts: Interrupt[];\n\n constructor(interrupts?: Interrupt[], fields?: BaseLangGraphErrorFields) {\n super(JSON.stringify(interrupts, null, 2), fields);\n this.name = \"GraphInterrupt\";\n this.interrupts = interrupts ?? [];\n }\n\n static get unminifiable_name() {\n return \"GraphInterrupt\";\n }\n}\n\n/** Raised by a node to interrupt execution. */\nexport class NodeInterrupt extends GraphInterrupt {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(message: any, fields?: BaseLangGraphErrorFields) {\n super([{ value: message }], fields);\n this.name = \"NodeInterrupt\";\n }\n\n static get unminifiable_name() {\n return \"NodeInterrupt\";\n }\n}\n\nexport class ParentCommand extends GraphBubbleUp {\n command: Command;\n\n constructor(command: Command) {\n super();\n this.name = \"ParentCommand\";\n this.command = command;\n }\n\n static get unminifiable_name() {\n return \"ParentCommand\";\n }\n}\n\nexport function isParentCommand(e?: unknown): e is ParentCommand {\n return (\n e !== undefined &&\n (e as ParentCommand).name === ParentCommand.unminifiable_name\n );\n}\n\nexport function isGraphBubbleUp(e?: unknown): e is GraphBubbleUp {\n return e !== undefined && (e as GraphBubbleUp).is_bubble_up === true;\n}\n\nexport function isGraphInterrupt(e?: unknown): e is GraphInterrupt {\n return (\n e !== undefined &&\n [\n GraphInterrupt.unminifiable_name,\n NodeInterrupt.unminifiable_name,\n ].includes((e as Error).name)\n );\n}\n\nexport class EmptyInputError extends BaseLangGraphError {\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n super(message, fields);\n this.name = \"EmptyInputError\";\n }\n\n static get unminifiable_name() {\n return \"EmptyInputError\";\n }\n}\n\nexport class EmptyChannelError extends BaseLangGraphError {\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n super(message, fields);\n this.name = \"EmptyChannelError\";\n }\n\n static get unminifiable_name() {\n return \"EmptyChannelError\";\n }\n}\n\nexport class InvalidUpdateError extends BaseLangGraphError {\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n super(message, fields);\n this.name = \"InvalidUpdateError\";\n }\n\n static get unminifiable_name() {\n return \"InvalidUpdateError\";\n }\n}\n\n/**\n * @deprecated This exception type is no longer thrown.\n */\nexport class MultipleSubgraphsError extends BaseLangGraphError {\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n super(message, fields);\n this.name = \"MultipleSubgraphError\";\n }\n\n static get unminifiable_name() {\n return \"MultipleSubgraphError\";\n }\n}\n\nexport class UnreachableNodeError extends BaseLangGraphError {\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n super(message, fields);\n this.name = \"UnreachableNodeError\";\n }\n\n static get unminifiable_name() {\n return \"UnreachableNodeError\";\n }\n}\n\n/**\n * Exception raised when an error occurs in the remote graph.\n */\nexport class RemoteException extends BaseLangGraphError {\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n super(message, fields);\n this.name = \"RemoteException\";\n }\n\n static get unminifiable_name() {\n return \"RemoteException\";\n }\n}\n\n/**\n * Error thrown when invalid input is provided to a StateGraph.\n *\n * This typically means that the input to the StateGraph constructor or builder\n * did not match the required types. A valid input should be a\n * StateDefinition, an Annotation.Root, or a Zod schema.\n *\n * @example\n * // Example of incorrect usage:\n * try {\n * new StateGraph({ foo: \"bar\" }); // Not a valid input\n * } catch (err) {\n * if (err instanceof StateGraphInputError) {\n * console.error(err.message);\n * }\n * }\n */\nexport class StateGraphInputError extends BaseLangGraphError {\n /**\n * Create a new StateGraphInputError.\n * @param message - Optional custom error message.\n * @param fields - Optional additional error fields.\n */\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n super(message, fields);\n this.name = \"StateGraphInputError\";\n this.message =\n \"Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema.\";\n }\n\n /**\n * The unminifiable (static, human-readable) error name for this error class.\n */\n static get unminifiable_name() {\n return \"StateGraphInputError\";\n }\n}\n\n/**\n * Used for subgraph detection.\n */\nexport const getSubgraphsSeenSet = () => {\n if (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (globalThis as any)[Symbol.for(\"LG_CHECKPOINT_SEEN_NS_SET\")] === undefined\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (globalThis as any)[Symbol.for(\"LG_CHECKPOINT_SEEN_NS_SET\")] = new Set();\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (globalThis as any)[Symbol.for(\"LG_CHECKPOINT_SEEN_NS_SET\")];\n};\n"],"mappings":";;AAgBA,IAAa,qBAAb,cAAwC,MAAM;CAC5C;CAEA,YAAY,SAAkB,QAAmC;EAC/D,IAAI,eAAe,WAAW;AAC9B,MAAI,QAAQ,cACV,gBAAe,GAAG,aAAa,+EAA+E,OAAO,cAAc;AAErI,QAAM,aAAa;AACnB,OAAK,gBAAgB,QAAQ;;;AAIjC,IAAa,gBAAb,cAAmC,mBAAmB;CACpD,IAAI,eAAe;AACjB,SAAO;;;AAIX,IAAa,sBAAb,cAAyC,mBAAmB;CAC1D,YAAY,SAAkB,QAAmC;AAC/D,QAAM,SAAS,OAAO;AACtB,OAAK,OAAO;;CAGd,WAAW,oBAAoB;AAC7B,SAAO;;;AAIX,IAAa,kBAAb,cAAqC,mBAAmB;CACtD,YAAY,SAAkB,QAAmC;AAC/D,QAAM,SAAS,OAAO;AACtB,OAAK,OAAO;;CAGd,WAAW,oBA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AO;;;;;;AAOX,IAAa,yBAAb,cAA4C,mBAAmB;CAC7D,YAAY,SAAkB,QAAmC;AAC/D,QAAM,SAAS,OAAO;AACtB,OAAK,OAAO;;CAGd,WAAW,oBAAoB;AAC7B,SAAO;;;AAIX,IAAa,uBAAb,cAA0C,mBAAmB;CAC3D,YAAY,SAAkB,QAAmC;AAC/D,QAAM,SAAS,OAAO;AACtB,OAAK,OAAO;;CAGd,WAAW,oBAAoB;AAC7B,SAAO;;;;;;AAOX,IAAa,kBAAb,cAAqC,mBAAmB;CACtD,YAAY,SAAkB,QAAmC;AAC/D,QAAM,SAAS,OAAO;AACtB,OAAK,OAAO;;CAGd,WAAW,oBAAoB;AAC7B,SAAO;;;;;;;;;;;;;;;;;;;;AAqBX,IAAa,uBAAb,cAA0C,mBAAmB;;;;;;CAM3D,YAAY,SAAkB,QAAmC;AAC/D,QAAM,SAAS,OAAO;AACtB,OAAK,OAAO;AACZ,OAAK,UACH;;;;;CAMJ,WAAW,oBAAoB;AAC7B,SAAO;;;;;;AAOX,MAAa,4BAA4B;AACvC,KAEG,WAAmB,OAAO,IAAI,4BAA4B,MAAM,KAAA,EAGhE,YAAmB,OAAO,IAAI,4BAA4B,oBAAI,IAAI,KAAK;AAG1E,QAAQ,WAAmB,OAAO,IAAI,4BAA4B"}
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import { Command, Interrupt } from \"./constants.js\";\n\n// When editing, make sure to update the index found here:\n// https://langchain-ai.github.io/langgraphjs/troubleshooting/errors/\nexport type BaseLangGraphErrorFields = {\n lc_error_code?:\n | \"GRAPH_RECURSION_LIMIT\"\n | \"INVALID_CONCURRENT_GRAPH_UPDATE\"\n | \"INVALID_GRAPH_NODE_RETURN_VALUE\"\n | \"MISSING_CHECKPOINTER\"\n | \"MULTIPLE_SUBGRAPHS\"\n | \"UNREACHABLE_NODE\";\n};\n\n// TODO: Merge with base LangChain error class when we drop support for core@0.2.0\n/** @category Errors */\nexport class BaseLangGraphError extends Error {\n lc_error_code?: string;\n\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n let finalMessage = message ?? \"\";\n if (fields?.lc_error_code) {\n finalMessage = `${finalMessage}\\n\\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${fields.lc_error_code}/\\n`;\n }\n super(finalMessage);\n this.lc_error_code = fields?.lc_error_code;\n }\n}\n\nexport class GraphBubbleUp extends BaseLangGraphError {\n get is_bubble_up() {\n return true;\n }\n}\n\nexport class GraphRecursionError extends BaseLangGraphError {\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n super(message, fields);\n this.name = \"GraphRecursionError\";\n }\n\n static get unminifiable_name() {\n return \"GraphRecursionError\";\n }\n}\n\nexport class GraphValueError extends BaseLangGraphError {\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n super(message, fields);\n this.name = \"GraphValueError\";\n }\n\n static get unminifiable_name() {\n return \"GraphValueError\";\n }\n}\n\n/**\n * Raised when a graph run exits early due to a drain request.\n *\n * This indicates the graph stopped cooperatively at a superstep boundary\n * because {@link RunControl#requestDrain} was called (e.g., in response to\n * SIGTERM). The checkpoint is saved and the run can be resumed later.\n */\nexport class GraphDrained extends GraphBubbleUp {\n reason: string;\n\n constructor(reason: string = \"shutdown\", fields?: BaseLangGraphErrorFields) {\n super(`Graph drained: ${reason}`, fields);\n this.name = \"GraphDrained\";\n this.reason = reason;\n }\n\n static get unminifiable_name() {\n return \"GraphDrained\";\n }\n}\n\nexport function isGraphDrained(e?: unknown): e is GraphDrained {\n return (\n e !== undefined && (e as Error).name === GraphDrained.unminifiable_name\n );\n}\n\nexport class GraphInterrupt extends GraphBubbleUp {\n interrupts: Interrupt[];\n\n constructor(interrupts?: Interrupt[], fields?: BaseLangGraphErrorFields) {\n super(JSON.stringify(interrupts, null, 2), fields);\n this.name = \"GraphInterrupt\";\n this.interrupts = interrupts ?? [];\n }\n\n static get unminifiable_name() {\n return \"GraphInterrupt\";\n }\n}\n\n/** Raised by a node to interrupt execution. */\nexport class NodeInterrupt extends GraphInterrupt {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(message: any, fields?: BaseLangGraphErrorFields) {\n super([{ value: message }], fields);\n this.name = \"NodeInterrupt\";\n }\n\n static get unminifiable_name() {\n return \"NodeInterrupt\";\n }\n}\n\n/**\n * Failure context passed to a node-level error handler.\n *\n * A node-level error handler is registered via\n * `StateGraph.addNode(name, fn, { errorHandler })`. The handler runs ONLY after\n * the failing node's {@link RetryPolicy} is exhausted, so retry and handling\n * stay decoupled. The handler receives the failed node's name and the thrown\n * error via a `NodeError` instance, can return a state update, and can route to\n * a recovery branch via `new Command({ goto })` (saga / compensation flows).\n *\n * @example\n * ```ts\n * import { NodeError } from \"@langchain/langgraph\";\n *\n * function handler(state: State, error: NodeError) {\n * return new Command({\n * update: { status: `recovered from ${error.node}: ${error.error.message}` },\n * goto: \"finalize\",\n * });\n * }\n * ```\n */\nexport class NodeError {\n /** Name of the node whose execution failed. */\n node: string;\n\n /** Error thrown by the failed node. */\n error: Error;\n\n constructor(node: string, error: Error) {\n this.node = node;\n this.error = error;\n }\n\n static get unminifiable_name() {\n return \"NodeError\";\n }\n}\n\n/**\n * Type guard that checks whether a value is a {@link NodeError}.\n */\nexport function isNodeError(e?: unknown): e is NodeError {\n return (\n e != null &&\n typeof e === \"object\" &&\n e.constructor != null &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (e.constructor as any).unminifiable_name === NodeError.unminifiable_name\n );\n}\n\nexport class ParentCommand extends GraphBubbleUp {\n command: Command;\n\n constructor(command: Command) {\n super();\n this.name = \"ParentCommand\";\n this.command = command;\n }\n\n static get unminifiable_name() {\n return \"ParentCommand\";\n }\n}\n\nexport function isParentCommand(e?: unknown): e is ParentCommand {\n return (\n e !== undefined &&\n (e as ParentCommand).name === ParentCommand.unminifiable_name\n );\n}\n\nexport function isGraphBubbleUp(e?: unknown): e is GraphBubbleUp {\n return e !== undefined && (e as GraphBubbleUp).is_bubble_up === true;\n}\n\nexport function isGraphInterrupt(e?: unknown): e is GraphInterrupt {\n return (\n e !== undefined &&\n [\n GraphInterrupt.unminifiable_name,\n NodeInterrupt.unminifiable_name,\n ].includes((e as Error).name)\n );\n}\n\n/**\n * Raised when a node invocation exceeds one of its configured timeouts.\n *\n * Does **not** extend {@link GraphBubbleUp} (so it flows through the normal node\n * error path) and is intentionally treated as retryable by the default retry\n * policy — its message/name do not match the default `retryOn` blocklist, so a\n * configured {@link RetryPolicy} will retry it (see langchain-ai/langgraph#7659).\n *\n * Both {@link NodeTimeoutError.runTimeout} and {@link NodeTimeoutError.idleTimeout}\n * reflect the configured policy at the time of the failure (each `undefined` if\n * not configured). {@link NodeTimeoutError.kind} and {@link NodeTimeoutError.timeout}\n * identify which one fired.\n *\n * @category Errors\n */\nexport class NodeTimeoutError extends BaseLangGraphError {\n /** Name of the node/task that timed out. */\n node: string;\n\n /** Which timeout fired: a hard `\"run\"` cap or a progress-resetting `\"idle\"` cap. */\n kind: \"run\" | \"idle\";\n\n /** The value (ms) of the timeout that fired (`runTimeout` or `idleTimeout`). */\n timeout: number;\n\n /** Elapsed time (ms) since the attempt started, at the moment the timeout fired. */\n elapsed: number;\n\n /** Configured run timeout (ms), if any. */\n runTimeout?: number;\n\n /** Configured idle timeout (ms), if any. */\n idleTimeout?: number;\n\n constructor(\n fields: {\n node: string;\n elapsed: number;\n kind: \"run\" | \"idle\";\n runTimeout?: number;\n idleTimeout?: number;\n },\n errorFields?: BaseLangGraphErrorFields\n ) {\n const { node, elapsed, kind, runTimeout, idleTimeout } = fields;\n let message: string;\n let timeout: number;\n if (kind === \"idle\") {\n if (idleTimeout === undefined) {\n throw new Error(\"idleTimeout is required when kind='idle'\");\n }\n timeout = idleTimeout;\n message =\n `Node \"${node}\" exceeded its idle timeout of ${idleTimeout}ms ` +\n `without making progress (elapsed: ${elapsed}ms).`;\n } else {\n if (runTimeout === undefined) {\n throw new Error(\"runTimeout is required when kind='run'\");\n }\n timeout = runTimeout;\n message =\n `Node \"${node}\" exceeded its run timeout of ${runTimeout}ms ` +\n `(elapsed: ${elapsed}ms).`;\n }\n super(message, errorFields);\n this.name = \"NodeTimeoutError\";\n this.node = node;\n this.kind = kind;\n this.timeout = timeout;\n this.elapsed = elapsed;\n this.runTimeout = runTimeout;\n this.idleTimeout = idleTimeout;\n }\n\n static get unminifiable_name() {\n return \"NodeTimeoutError\";\n }\n}\n\nexport function isNodeTimeoutError(e?: unknown): e is NodeTimeoutError {\n return (\n e !== undefined &&\n (e as NodeTimeoutError).name === NodeTimeoutError.unminifiable_name\n );\n}\n\nexport class EmptyInputError extends BaseLangGraphError {\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n super(message, fields);\n this.name = \"EmptyInputError\";\n }\n\n static get unminifiable_name() {\n return \"EmptyInputError\";\n }\n}\n\nexport class EmptyChannelError extends BaseLangGraphError {\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n // Skip expensive stack trace capture — used for control flow on channel reads.\n const prevLimit = Error.stackTraceLimit;\n Error.stackTraceLimit = 0;\n super(message, fields);\n Error.stackTraceLimit = prevLimit;\n this.name = \"EmptyChannelError\";\n }\n\n static get unminifiable_name() {\n return \"EmptyChannelError\";\n }\n}\n\nexport class InvalidUpdateError extends BaseLangGraphError {\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n super(message, fields);\n this.name = \"InvalidUpdateError\";\n }\n\n static get unminifiable_name() {\n return \"InvalidUpdateError\";\n }\n}\n\n/**\n * @deprecated This exception type is no longer thrown.\n */\nexport class MultipleSubgraphsError extends BaseLangGraphError {\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n super(message, fields);\n this.name = \"MultipleSubgraphError\";\n }\n\n static get unminifiable_name() {\n return \"MultipleSubgraphError\";\n }\n}\n\nexport class UnreachableNodeError extends BaseLangGraphError {\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n super(message, fields);\n this.name = \"UnreachableNodeError\";\n }\n\n static get unminifiable_name() {\n return \"UnreachableNodeError\";\n }\n}\n\n/**\n * Exception raised when an error occurs in the remote graph.\n */\nexport class RemoteException extends BaseLangGraphError {\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n super(message, fields);\n this.name = \"RemoteException\";\n }\n\n static get unminifiable_name() {\n return \"RemoteException\";\n }\n}\n\n/**\n * Error thrown when invalid input is provided to a StateGraph.\n *\n * This typically means that the input to the StateGraph constructor or builder\n * did not match the required types. A valid input should be a\n * StateDefinition, an Annotation.Root, or a Zod schema.\n *\n * @example\n * // Example of incorrect usage:\n * try {\n * new StateGraph({ foo: \"bar\" }); // Not a valid input\n * } catch (err) {\n * if (err instanceof StateGraphInputError) {\n * console.error(err.message);\n * }\n * }\n */\nexport class StateGraphInputError extends BaseLangGraphError {\n /**\n * Create a new StateGraphInputError.\n * @param message - Optional custom error message.\n * @param fields - Optional additional error fields.\n */\n constructor(message?: string, fields?: BaseLangGraphErrorFields) {\n super(message, fields);\n this.name = \"StateGraphInputError\";\n this.message =\n \"Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema.\";\n }\n\n /**\n * The unminifiable (static, human-readable) error name for this error class.\n */\n static get unminifiable_name() {\n return \"StateGraphInputError\";\n }\n}\n\n/**\n * Used for subgraph detection.\n */\nexport const getSubgraphsSeenSet = () => {\n if (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (globalThis as any)[Symbol.for(\"LG_CHECKPOINT_SEEN_NS_SET\")] === undefined\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (globalThis as any)[Symbol.for(\"LG_CHECKPOINT_SEEN_NS_SET\")] = new Set();\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (globalThis as any)[Symbol.for(\"LG_CHECKPOINT_SEEN_NS_SET\")];\n};\n"],"mappings":";;AAgBA,IAAa,qBAAb,cAAwC,MAAM;CAC5C;CAEA,YAAY,SAAkB,QAAmC;EAC/D,IAAI,eAAe,WAAW;AAC9B,M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B,OAAO,IAAI,4BAA4B,MAAM,KAAA,EAGhE,YAAmB,OAAO,IAAI,4BAA4B,oBAAI,IAAI,KAAK;AAG1E,QAAQ,WAAmB,OAAO,IAAI,4BAA4B"}
|
package/dist/func/index.cjs
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
const require_timeout = require("../pregel/utils/timeout.cjs");
|
|
1
2
|
const require_constants = require("../constants.cjs");
|
|
2
3
|
const require_last_value = require("../channels/last_value.cjs");
|
|
3
4
|
const require_utils = require("../utils.cjs");
|
|
4
5
|
const require_write = require("../pregel/write.cjs");
|
|
5
6
|
const require_read = require("../pregel/read.cjs");
|
|
7
|
+
require("../pregel/utils/index.cjs");
|
|
6
8
|
const require_call = require("../pregel/call.cjs");
|
|
7
9
|
const require_pregel_index = require("../pregel/index.cjs");
|
|
8
10
|
const require_ephemeral_value = require("../channels/ephemeral_value.cjs");
|
|
@@ -59,9 +61,11 @@ function task(optionsOrName, func) {
|
|
|
59
61
|
const options = typeof optionsOrName === "string" ? {
|
|
60
62
|
name: optionsOrName,
|
|
61
63
|
retry: void 0,
|
|
62
|
-
cachePolicy: void 0
|
|
64
|
+
cachePolicy: void 0,
|
|
65
|
+
timeout: void 0
|
|
63
66
|
} : optionsOrName;
|
|
64
67
|
const { name, retry } = options;
|
|
68
|
+
const timeout = require_timeout.coerceTimeoutPolicy(options.timeout);
|
|
65
69
|
if (require_utils.isAsyncGeneratorFunction(func) || require_utils.isGeneratorFunction(func)) throw new Error("Generators are disallowed as tasks. For streaming responses, use config.write.");
|
|
66
70
|
const cachePolicy = options.cachePolicy ?? ("cache" in options ? options.cache : void 0);
|
|
67
71
|
let cache;
|
|
@@ -72,7 +76,8 @@ function task(optionsOrName, func) {
|
|
|
72
76
|
func,
|
|
73
77
|
name,
|
|
74
78
|
retry,
|
|
75
|
-
cache
|
|
79
|
+
cache,
|
|
80
|
+
timeout
|
|
76
81
|
}, ...args);
|
|
77
82
|
};
|
|
78
83
|
}
|
|
@@ -214,6 +219,7 @@ const entrypoint = function entrypoint(optionsOrName, func) {
|
|
|
214
219
|
checkpointer: void 0,
|
|
215
220
|
store: void 0
|
|
216
221
|
} : optionsOrName;
|
|
222
|
+
const timeout = require_timeout.coerceTimeoutPolicy(typeof optionsOrName === "string" ? void 0 : optionsOrName.timeout);
|
|
217
223
|
if (require_utils.isAsyncGeneratorFunction(func) || require_utils.isGeneratorFunction(func)) throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write.");
|
|
218
224
|
const streamMode = "updates";
|
|
219
225
|
const bound = require_call.getRunnableForEntrypoint(name, func);
|
|
@@ -236,6 +242,7 @@ const entrypoint = function entrypoint(optionsOrName, func) {
|
|
|
236
242
|
bound,
|
|
237
243
|
triggers: [require_constants.START],
|
|
238
244
|
channels: [require_constants.START],
|
|
245
|
+
timeout,
|
|
239
246
|
writers: [new require_write.ChannelWrite([{
|
|
240
247
|
channel: require_constants.END,
|
|
241
248
|
value: require_write.PASSTHROUGH,
|
package/dist/func/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["isAsyncGeneratorFunction","isGeneratorFunction","call","getRunnableForEntrypoint","RunnableCallable","PregelNode","START","ChannelWrite","END","PASSTHROUGH","PREVIOUS","TAG_HIDDEN","Pregel","EphemeralValue","LastValue","AsyncLocalStorageProviderSingleton","CONFIG_KEY_PREVIOUS_STATE"],"sources":["../../src/func/index.ts"],"sourcesContent":["import {\n BaseCache,\n BaseCheckpointSaver,\n BaseStore,\n} from \"@langchain/langgraph-checkpoint\";\nimport { AsyncLocalStorageProviderSingleton } from \"@langchain/core/singletons\";\nimport { Pregel } from \"../pregel/index.js\";\nimport { PregelNode } from \"../pregel/read.js\";\nimport {\n CONFIG_KEY_PREVIOUS_STATE,\n END,\n PREVIOUS,\n START,\n TAG_HIDDEN,\n} from \"../constants.js\";\nimport { EphemeralValue } from \"../channels/ephemeral_value.js\";\nimport { call, getRunnableForEntrypoint } from \"../pregel/call.js\";\nimport type { CachePolicy, RetryPolicy } from \"../pregel/utils/index.js\";\nimport { LastValue } from \"../channels/last_value.js\";\nimport {\n EntrypointFinal,\n EntrypointReturnT,\n EntrypointFinalSaveT,\n EntrypointFunc,\n TaskFunc,\n} from \"./types.js\";\nimport { LangGraphRunnableConfig } from \"../pregel/runnable_types.js\";\nimport {\n RunnableCallable,\n isAsyncGeneratorFunction,\n isGeneratorFunction,\n} from \"../utils.js\";\nimport { ChannelWrite, PASSTHROUGH } from \"../pregel/write.js\";\n\n/**\n * Options for the {@link task} function\n */\nexport interface TaskOptions {\n /**\n * The name of the task, analogous to the node name in {@link StateGraph}.\n */\n name: string;\n /**\n * The retry policy for the task. Configures how many times and under what conditions\n * the task should be retried if it fails.\n */\n retry?: RetryPolicy;\n\n /**\n * The cache policy for the task. Configures how the task should be cached.\n */\n cachePolicy?: CachePolicy;\n}\n\n/**\n * Define a LangGraph task using the `task` function.\n *\n * Tasks can only be called from within an {@link entrypoint} or from within a StateGraph.\n * A task can be called like a regular function with the following differences:\n *\n * - When a checkpointer is enabled, the function inputs and outputs must be serializable.\n * - The wrapped function can only be called from within an entrypoint or StateGraph.\n * - Calling the function produces a promise. This makes it easy to parallelize tasks.\n *\n * @typeParam ArgsT - The type of arguments the task function accepts\n * @typeParam OutputT - The type of value the task function returns\n * @param optionsOrName - Either an {@link TaskOptions} object, or a string for the name of the task\n * @param func - The function that executes this task\n * @returns A proxy function that accepts the same arguments as the original and always returns the result as a Promise\n *\n * @example basic example\n * ```typescript\n * const addOne = task(\"add\", async (a: number) => a + 1);\n *\n * const workflow = entrypoint(\"example\", async (numbers: number[]) => {\n * const promises = numbers.map(n => addOne(n));\n * const results = await Promise.all(promises);\n * return results;\n * });\n *\n * // Call the entrypoint\n * await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4]\n * ```\n *\n * @example using a retry policy\n * ```typescript\n * const addOne = task({\n * name: \"add\",\n * retry: { maxAttempts: 3 }\n * },\n * async (a: number) => a + 1\n * );\n *\n * const workflow = entrypoint(\"example\", async (numbers: number[]) => {\n * const promises = numbers.map(n => addOne(n));\n * const results = await Promise.all(promises);\n * return results;\n * });\n * ```\n * @category Functional API\n */\nexport function task<ArgsT extends unknown[], OutputT>(\n optionsOrName: TaskOptions | string,\n func: TaskFunc<ArgsT, OutputT>\n): (...args: ArgsT) => Promise<OutputT> {\n const options =\n typeof optionsOrName === \"string\"\n ? { name: optionsOrName, retry: undefined, cachePolicy: undefined }\n : optionsOrName;\n\n const { name, retry } = options;\n if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) {\n throw new Error(\n \"Generators are disallowed as tasks. For streaming responses, use config.write.\"\n );\n }\n\n const cachePolicy =\n options.cachePolicy ??\n // `cache` was mistakingly used as an alias for `cachePolicy` in v0.3.x,\n // TODO: remove in 1.x\n (\"cache\" in options ? (options.cache as CachePolicy) : undefined);\n\n let cache: CachePolicy | undefined;\n if (typeof cachePolicy === \"boolean\") {\n cache = cachePolicy ? {} : undefined;\n } else {\n cache = cachePolicy;\n }\n\n return (...args: ArgsT) => {\n return call({ func, name, retry, cache }, ...args);\n };\n}\n\n/**\n * Options for the {@link entrypoint} function\n */\nexport type EntrypointOptions = {\n /**\n * The name of the {@link entrypoint}, analogous to the node name in {@link StateGraph}.\n * This name is used for logging, debugging, and checkpoint identification.\n */\n name: string;\n /**\n * The checkpointer for the {@link entrypoint}. Used to save and restore state between\n * invocations of the workflow.\n */\n checkpointer?: BaseCheckpointSaver;\n /**\n * The store for the {@link entrypoint}. Used to persist data across workflow runs.\n */\n store?: BaseStore;\n\n /**\n * The cache for the {@link entrypoint}. Used to cache values between workflow runs.\n */\n cache?: BaseCache;\n};\n\n/**\n * Type declaration for the entrypoint function with its properties\n * @category Functional API\n */\nexport interface EntrypointFunction {\n <InputT, OutputT>(\n optionsOrName: EntrypointOptions | string,\n func: EntrypointFunc<InputT, OutputT>\n ): Pregel<\n Record<string, PregelNode<InputT, EntrypointReturnT<OutputT>>>,\n {\n [START]: EphemeralValue<InputT>;\n [END]: LastValue<EntrypointReturnT<OutputT>>;\n [PREVIOUS]: LastValue<EntrypointFinalSaveT<OutputT>>;\n },\n Record<string, unknown>,\n InputT,\n EntrypointReturnT<OutputT>,\n // Because the update type is an return type union of tasks + entrypoint,\n // thus we can't type it properly.\n any, // eslint-disable-line @typescript-eslint/no-explicit-any\n Awaited<EntrypointReturnT<OutputT>>\n >;\n\n /**\n * A helper utility for use with the functional API that returns a value to the caller,\n * as well as a separate state value to persist to the checkpoint. This allows workflows\n * to maintain state between runs while returning different values to the caller.\n *\n * @typeParam ValueT - The type of the value to return to the caller\n * @typeParam SaveT - The type of the state to save to the checkpoint\n * @param options.value - The value to return to the caller\n * @param options.save - The value to save to the checkpoint\n * @returns An object with the value and save properties\n *\n * @example\n * ```typescript\n * return entrypoint.final({\n * value: \"result for caller\",\n * save: { counter: currentCount + 1 }\n * });\n * ```\n */\n final<ValueT, SaveT>(options: {\n value?: ValueT;\n save?: SaveT;\n }): EntrypointFinal<ValueT, SaveT>;\n}\n\n/**\n * Define a LangGraph workflow using the `entrypoint` function.\n *\n * ### Function signature\n *\n * The wrapped function must accept at most **two parameters**. The first parameter\n * is the input to the function. The second (optional) parameter is a\n * {@link LangGraphRunnableConfig} object. If you wish to pass multiple parameters to\n * the function, you can pass them as an object.\n *\n * ### Helper functions\n *\n * #### Streaming\n * To write data to the \"custom\" stream, use the {@link getWriter} function, or the\n * {@link LangGraphRunnableConfig.writer} property.\n *\n * #### State management\n * The {@link getPreviousState} function can be used to access the previous state\n * that was returned from the last invocation of the entrypoint on the same thread id.\n *\n * If you wish to save state other than the return value, you can use the\n * {@link entrypoint.final} function.\n *\n * @typeParam InputT - The type of input the entrypoint accepts\n * @typeParam OutputT - The type of output the entrypoint produces\n * @param optionsOrName - Either an {@link EntrypointOptions} object, or a string for the name of the entrypoint\n * @param func - The function that executes this entrypoint\n * @returns A {@link Pregel} instance that can be run to execute the workflow\n *\n * @example Using entrypoint and tasks\n * ```typescript\n * import { task, entrypoint } from \"@langchain/langgraph\";\n * import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n * import { interrupt, Command } from \"@langchain/langgraph\";\n *\n * const composeEssay = task(\"compose\", async (topic: string) => {\n * await new Promise(r => setTimeout(r, 1000)); // Simulate slow operation\n * return `An essay about ${topic}`;\n * });\n *\n * const reviewWorkflow = entrypoint({\n * name: \"review\",\n * checkpointer: new MemorySaver()\n * }, async (topic: string) => {\n * const essay = await composeEssay(topic);\n * const humanReview = await interrupt({\n * question: \"Please provide a review\",\n * essay\n * });\n * return {\n * essay,\n * review: humanReview\n * };\n * });\n *\n * // Example configuration for the workflow\n * const config = {\n * configurable: {\n * thread_id: \"some_thread\"\n * }\n * };\n *\n * // Topic for the essay\n * const topic = \"cats\";\n *\n * // Stream the workflow to generate the essay and await human review\n * for await (const result of reviewWorkflow.stream(topic, config)) {\n * console.log(result);\n * }\n *\n * // Example human review provided after the interrupt\n * const humanReview = \"This essay is great.\";\n *\n * // Resume the workflow with the provided human review\n * for await (const result of reviewWorkflow.stream(new Command({ resume: humanReview }), config)) {\n * console.log(result);\n * }\n * ```\n *\n * @example Accessing the previous return value\n * ```typescript\n * import { entrypoint, getPreviousState } from \"@langchain/langgraph\";\n * import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n *\n * const accumulator = entrypoint({\n * name: \"accumulator\",\n * checkpointer: new MemorySaver()\n * }, async (input: string) => {\n * const previous = getPreviousState<number>();\n * return previous !== undefined ? `${previous } ${input}` : input;\n * });\n *\n * const config = {\n * configurable: {\n * thread_id: \"some_thread\"\n * }\n * };\n * await accumulator.invoke(\"hello\", config); // returns \"hello\"\n * await accumulator.invoke(\"world\", config); // returns \"hello world\"\n * ```\n *\n * @example Using entrypoint.final to save a value\n * ```typescript\n * import { entrypoint, getPreviousState } from \"@langchain/langgraph\";\n * import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n *\n * const myWorkflow = entrypoint({\n * name: \"accumulator\",\n * checkpointer: new MemorySaver()\n * }, async (num: number) => {\n * const previous = getPreviousState<number>();\n *\n * // This will return the previous value to the caller, saving\n * // 2 * num to the checkpoint, which will be used in the next invocation\n * // for the `previous` parameter.\n * return entrypoint.final({\n * value: previous ?? 0,\n * save: 2 * num\n * });\n * });\n *\n * const config = {\n * configurable: {\n * thread_id: \"some_thread\"\n * }\n * };\n *\n * await myWorkflow.invoke(3, config); // 0 (previous was undefined)\n * await myWorkflow.invoke(1, config); // 6 (previous was 3 * 2 from the previous invocation)\n * ```\n * @category Functional API\n */\nexport const entrypoint = function entrypoint<InputT, OutputT>(\n optionsOrName: EntrypointOptions | string,\n func: EntrypointFunc<InputT, OutputT>\n) {\n const { name, checkpointer, store, cache } =\n typeof optionsOrName === \"string\"\n ? { name: optionsOrName, checkpointer: undefined, store: undefined }\n : optionsOrName;\n if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) {\n throw new Error(\n \"Generators are disallowed as entrypoints. For streaming responses, use config.write.\"\n );\n }\n const streamMode = \"updates\";\n const bound = getRunnableForEntrypoint(name, func);\n\n // Helper to check if a value is an EntrypointFinal\n function isEntrypointFinal(\n value: unknown\n ): value is EntrypointFinal<unknown, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"__lg_type\" in value &&\n value.__lg_type === \"__pregel_final\"\n );\n }\n\n // Helper function to pluck the return value from EntrypointFinal or passthrough\n const pluckReturnValue = new RunnableCallable({\n name: \"pluckReturnValue\",\n func: (value: unknown) => {\n return isEntrypointFinal(value) ? value.value : value;\n },\n });\n\n // Helper function to pluck the save value from EntrypointFinal or passthrough\n const pluckSaveValue = new RunnableCallable({\n name: \"pluckSaveValue\",\n func: (value: unknown) => {\n return isEntrypointFinal(value) ? value.save : value;\n },\n });\n\n const entrypointNode = new PregelNode<InputT, EntrypointReturnT<OutputT>>({\n bound,\n triggers: [START],\n channels: [START],\n writers: [\n new ChannelWrite(\n [\n { channel: END, value: PASSTHROUGH, mapper: pluckReturnValue },\n { channel: PREVIOUS, value: PASSTHROUGH, mapper: pluckSaveValue },\n ],\n [TAG_HIDDEN]\n ),\n ],\n });\n\n return new Pregel<\n Record<string, PregelNode<InputT, EntrypointReturnT<OutputT>>>, // node types\n {\n [START]: EphemeralValue<InputT>;\n [END]: LastValue<EntrypointReturnT<OutputT>>;\n [PREVIOUS]: LastValue<EntrypointFinalSaveT<OutputT>>;\n }, // channel types\n Record<string, unknown>, // configurable types\n InputT, // input type\n EntrypointReturnT<OutputT> // output type\n >({\n name,\n checkpointer,\n nodes: {\n [name]: entrypointNode,\n },\n channels: {\n [START]: new EphemeralValue<InputT>(),\n [END]: new LastValue<EntrypointReturnT<OutputT>>(),\n [PREVIOUS]: new LastValue<EntrypointFinalSaveT<OutputT>>(),\n },\n inputChannels: START,\n outputChannels: END,\n streamChannels: END,\n streamMode,\n store,\n cache,\n });\n} as EntrypointFunction;\n\n// documented by the EntrypointFunction interface\nentrypoint.final = function final<ValueT, SaveT>({\n value,\n save,\n}: {\n value?: ValueT;\n save?: SaveT;\n}): EntrypointFinal<ValueT, SaveT> {\n return { value, save, __lg_type: \"__pregel_final\" };\n};\n\n/**\n * A helper utility function for use with the functional API that returns the previous\n * state from the checkpoint from the last invocation of the current thread.\n *\n * This function allows workflows to access state that was saved in previous runs\n * using {@link entrypoint.final}.\n *\n * @typeParam StateT - The type of the state that was previously saved\n * @returns The previous saved state from the last invocation of the current thread\n *\n * @example\n * ```typescript\n * const previousState = getPreviousState<{ counter: number }>();\n * const newCount = (previousState?.counter ?? 0) + 1;\n * ```\n * @category Functional API\n */\nexport function getPreviousState<StateT>(): StateT {\n const config: LangGraphRunnableConfig =\n AsyncLocalStorageProviderSingleton.getRunnableConfig();\n return config.configurable?.[CONFIG_KEY_PREVIOUS_STATE] as StateT;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqGA,SAAgB,KACd,eACA,MACsC;CACtC,MAAM,UACJ,OAAO,kBAAkB,WACrB;EAAE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,kBAAkB,MAAM,GAAG,MAAM,OAAO;;EAElD,CAAC;CAEF,MAAM,iBAAiB,IAAIC,aAAAA,WAA+C;EACxE;EACA,UAAU,CAACC,kBAAAA,MAAM;EACjB,UAAU,CAACA,kBAAAA,MAAM;EACjB,SAAS,CACP,IAAIC,cAAAA,aACF,CACE;GAAE,SAASC,kBAAAA;GAAK,OAAOC,cAAAA;GAAa,QAAQ;GAAkB,EAC9D;GAAE,SAASC,kBAAAA;GAAU,OAAOD,cAAAA;GAAa,QAAQ;GAAgB,CAClE,EACD,CAACE,kBAAAA,WAAW,CACb,CACF;EACF,CAAC;AAEF,QAAO,IAAIC,qBAAAA,OAUT;EACA;EACA;EACA,OAAO,GACJ,OAAO,gBACT;EACD,UAAU;IACPN,kBAAAA,QAAQ,IAAIO,wBAAAA,gBAAwB;IACpCL,kBAAAA,MAAM,IAAIM,mBAAAA,WAAuC;IACjDJ,kBAAAA,WAAW,IAAII,mBAAAA,WAA0C;GAC3D;EACD,eAAeR,kBAAAA;EACf,gBAAgBE,kBAAAA;EAChB,gBAAgBA,kBAAAA;EAChB;EACA;EACA;EACD,CAAC;;AAIJ,WAAW,QAAQ,SAAS,MAAqB,EAC/C,OACA,QAIiC;AACjC,QAAO;EAAE;EAAO;EAAM,WAAW;EAAkB;;;;;;;;;;;;;;;;;;;AAoBrD,SAAgB,mBAAmC;AAGjD,QADEO,2BAAAA,mCAAmC,mBAAmB,CAC1C,eAAeC,kBAAAA"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["coerceTimeoutPolicy","isAsyncGeneratorFunction","isGeneratorFunction","call","getRunnableForEntrypoint","RunnableCallable","PregelNode","START","ChannelWrite","END","PASSTHROUGH","PREVIOUS","TAG_HIDDEN","Pregel","EphemeralValue","LastValue","AsyncLocalStorageProviderSingleton","CONFIG_KEY_PREVIOUS_STATE"],"sources":["../../src/func/index.ts"],"sourcesContent":["import {\n BaseCache,\n BaseCheckpointSaver,\n BaseStore,\n} from \"@langchain/langgraph-checkpoint\";\nimport { AsyncLocalStorageProviderSingleton } from \"@langchain/core/singletons\";\nimport { Pregel } from \"../pregel/index.js\";\nimport { PregelNode } from \"../pregel/read.js\";\nimport {\n CONFIG_KEY_PREVIOUS_STATE,\n END,\n PREVIOUS,\n START,\n TAG_HIDDEN,\n} from \"../constants.js\";\nimport { EphemeralValue } from \"../channels/ephemeral_value.js\";\nimport { call, getRunnableForEntrypoint } from \"../pregel/call.js\";\nimport type {\n CachePolicy,\n RetryPolicy,\n TimeoutPolicy,\n} from \"../pregel/utils/index.js\";\nimport { coerceTimeoutPolicy } from \"../pregel/utils/index.js\";\nimport { LastValue } from \"../channels/last_value.js\";\nimport {\n EntrypointFinal,\n EntrypointReturnT,\n EntrypointFinalSaveT,\n EntrypointFunc,\n TaskFunc,\n} from \"./types.js\";\nimport { LangGraphRunnableConfig } from \"../pregel/runnable_types.js\";\nimport {\n RunnableCallable,\n isAsyncGeneratorFunction,\n isGeneratorFunction,\n} from \"../utils.js\";\nimport { ChannelWrite, PASSTHROUGH } from \"../pregel/write.js\";\n\n/**\n * Options for the {@link task} function\n */\nexport interface TaskOptions {\n /**\n * The name of the task, analogous to the node name in {@link StateGraph}.\n */\n name: string;\n /**\n * The retry policy for the task. Configures how many times and under what conditions\n * the task should be retried if it fails.\n */\n retry?: RetryPolicy;\n\n /**\n * The cache policy for the task. Configures how the task should be cached.\n */\n cachePolicy?: CachePolicy;\n\n /**\n * Maximum duration for a single attempt of this task. Accepts a number of\n * milliseconds (a hard wall-clock cap) or a {@link TimeoutPolicy} for finer\n * control. When exceeded, a {@link NodeTimeoutError} is raised and the task's\n * retry policy (if any) decides whether to retry.\n */\n timeout?: number | TimeoutPolicy;\n}\n\n/**\n * Define a LangGraph task using the `task` function.\n *\n * Tasks can only be called from within an {@link entrypoint} or from within a StateGraph.\n * A task can be called like a regular function with the following differences:\n *\n * - When a checkpointer is enabled, the function inputs and outputs must be serializable.\n * - The wrapped function can only be called from within an entrypoint or StateGraph.\n * - Calling the function produces a promise. This makes it easy to parallelize tasks.\n *\n * @typeParam ArgsT - The type of arguments the task function accepts\n * @typeParam OutputT - The type of value the task function returns\n * @param optionsOrName - Either an {@link TaskOptions} object, or a string for the name of the task\n * @param func - The function that executes this task\n * @returns A proxy function that accepts the same arguments as the original and always returns the result as a Promise\n *\n * @example basic example\n * ```typescript\n * const addOne = task(\"add\", async (a: number) => a + 1);\n *\n * const workflow = entrypoint(\"example\", async (numbers: number[]) => {\n * const promises = numbers.map(n => addOne(n));\n * const results = await Promise.all(promises);\n * return results;\n * });\n *\n * // Call the entrypoint\n * await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4]\n * ```\n *\n * @example using a retry policy\n * ```typescript\n * const addOne = task({\n * name: \"add\",\n * retry: { maxAttempts: 3 }\n * },\n * async (a: number) => a + 1\n * );\n *\n * const workflow = entrypoint(\"example\", async (numbers: number[]) => {\n * const promises = numbers.map(n => addOne(n));\n * const results = await Promise.all(promises);\n * return results;\n * });\n * ```\n * @category Functional API\n */\nexport function task<ArgsT extends unknown[], OutputT>(\n optionsOrName: TaskOptions | string,\n func: TaskFunc<ArgsT, OutputT>\n): (...args: ArgsT) => Promise<OutputT> {\n const options =\n typeof optionsOrName === \"string\"\n ? {\n name: optionsOrName,\n retry: undefined,\n cachePolicy: undefined,\n timeout: undefined,\n }\n : optionsOrName;\n\n const { name, retry } = options;\n const timeout = coerceTimeoutPolicy(options.timeout);\n if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) {\n throw new Error(\n \"Generators are disallowed as tasks. For streaming responses, use config.write.\"\n );\n }\n\n const cachePolicy =\n options.cachePolicy ??\n // `cache` was mistakingly used as an alias for `cachePolicy` in v0.3.x,\n // TODO: remove in 1.x\n (\"cache\" in options ? (options.cache as CachePolicy) : undefined);\n\n let cache: CachePolicy | undefined;\n if (typeof cachePolicy === \"boolean\") {\n cache = cachePolicy ? {} : undefined;\n } else {\n cache = cachePolicy;\n }\n\n return (...args: ArgsT) => {\n return call({ func, name, retry, cache, timeout }, ...args);\n };\n}\n\n/**\n * Options for the {@link entrypoint} function\n */\nexport type EntrypointOptions = {\n /**\n * The name of the {@link entrypoint}, analogous to the node name in {@link StateGraph}.\n * This name is used for logging, debugging, and checkpoint identification.\n */\n name: string;\n /**\n * The checkpointer for the {@link entrypoint}. Used to save and restore state between\n * invocations of the workflow.\n */\n checkpointer?: BaseCheckpointSaver;\n /**\n * The store for the {@link entrypoint}. Used to persist data across workflow runs.\n */\n store?: BaseStore;\n\n /**\n * The cache for the {@link entrypoint}. Used to cache values between workflow runs.\n */\n cache?: BaseCache;\n\n /**\n * Maximum duration for a single attempt of this entrypoint. Accepts a number\n * of milliseconds (a hard wall-clock cap) or a {@link TimeoutPolicy} for finer\n * control. When exceeded, a {@link NodeTimeoutError} is raised.\n */\n timeout?: number | TimeoutPolicy;\n};\n\n/**\n * Type declaration for the entrypoint function with its properties\n * @category Functional API\n */\nexport interface EntrypointFunction {\n <InputT, OutputT>(\n optionsOrName: EntrypointOptions | string,\n func: EntrypointFunc<InputT, OutputT>\n ): Pregel<\n Record<string, PregelNode<InputT, EntrypointReturnT<OutputT>>>,\n {\n [START]: EphemeralValue<InputT>;\n [END]: LastValue<EntrypointReturnT<OutputT>>;\n [PREVIOUS]: LastValue<EntrypointFinalSaveT<OutputT>>;\n },\n Record<string, unknown>,\n InputT,\n EntrypointReturnT<OutputT>,\n // Because the update type is an return type union of tasks + entrypoint,\n // thus we can't type it properly.\n any, // eslint-disable-line @typescript-eslint/no-explicit-any\n Awaited<EntrypointReturnT<OutputT>>\n >;\n\n /**\n * A helper utility for use with the functional API that returns a value to the caller,\n * as well as a separate state value to persist to the checkpoint. This allows workflows\n * to maintain state between runs while returning different values to the caller.\n *\n * @typeParam ValueT - The type of the value to return to the caller\n * @typeParam SaveT - The type of the state to save to the checkpoint\n * @param options.value - The value to return to the caller\n * @param options.save - The value to save to the checkpoint\n * @returns An object with the value and save properties\n *\n * @example\n * ```typescript\n * return entrypoint.final({\n * value: \"result for caller\",\n * save: { counter: currentCount + 1 }\n * });\n * ```\n */\n final<ValueT, SaveT>(options: {\n value?: ValueT;\n save?: SaveT;\n }): EntrypointFinal<ValueT, SaveT>;\n}\n\n/**\n * Define a LangGraph workflow using the `entrypoint` function.\n *\n * ### Function signature\n *\n * The wrapped function must accept at most **two parameters**. The first parameter\n * is the input to the function. The second (optional) parameter is a\n * {@link LangGraphRunnableConfig} object. If you wish to pass multiple parameters to\n * the function, you can pass them as an object.\n *\n * ### Helper functions\n *\n * #### Streaming\n * To write data to the \"custom\" stream, use the {@link getWriter} function, or the\n * {@link LangGraphRunnableConfig.writer} property.\n *\n * #### State management\n * The {@link getPreviousState} function can be used to access the previous state\n * that was returned from the last invocation of the entrypoint on the same thread id.\n *\n * If you wish to save state other than the return value, you can use the\n * {@link entrypoint.final} function.\n *\n * @typeParam InputT - The type of input the entrypoint accepts\n * @typeParam OutputT - The type of output the entrypoint produces\n * @param optionsOrName - Either an {@link EntrypointOptions} object, or a string for the name of the entrypoint\n * @param func - The function that executes this entrypoint\n * @returns A {@link Pregel} instance that can be run to execute the workflow\n *\n * @example Using entrypoint and tasks\n * ```typescript\n * import { task, entrypoint } from \"@langchain/langgraph\";\n * import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n * import { interrupt, Command } from \"@langchain/langgraph\";\n *\n * const composeEssay = task(\"compose\", async (topic: string) => {\n * await new Promise(r => setTimeout(r, 1000)); // Simulate slow operation\n * return `An essay about ${topic}`;\n * });\n *\n * const reviewWorkflow = entrypoint({\n * name: \"review\",\n * checkpointer: new MemorySaver()\n * }, async (topic: string) => {\n * const essay = await composeEssay(topic);\n * const humanReview = await interrupt({\n * question: \"Please provide a review\",\n * essay\n * });\n * return {\n * essay,\n * review: humanReview\n * };\n * });\n *\n * // Example configuration for the workflow\n * const config = {\n * configurable: {\n * thread_id: \"some_thread\"\n * }\n * };\n *\n * // Topic for the essay\n * const topic = \"cats\";\n *\n * // Stream the workflow to generate the essay and await human review\n * for await (const result of reviewWorkflow.stream(topic, config)) {\n * console.log(result);\n * }\n *\n * // Example human review provided after the interrupt\n * const humanReview = \"This essay is great.\";\n *\n * // Resume the workflow with the provided human review\n * for await (const result of reviewWorkflow.stream(new Command({ resume: humanReview }), config)) {\n * console.log(result);\n * }\n * ```\n *\n * @example Accessing the previous return value\n * ```typescript\n * import { entrypoint, getPreviousState } from \"@langchain/langgraph\";\n * import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n *\n * const accumulator = entrypoint({\n * name: \"accumulator\",\n * checkpointer: new MemorySaver()\n * }, async (input: string) => {\n * const previous = getPreviousState<number>();\n * return previous !== undefined ? `${previous } ${input}` : input;\n * });\n *\n * const config = {\n * configurable: {\n * thread_id: \"some_thread\"\n * }\n * };\n * await accumulator.invoke(\"hello\", config); // returns \"hello\"\n * await accumulator.invoke(\"world\", config); // returns \"hello world\"\n * ```\n *\n * @example Using entrypoint.final to save a value\n * ```typescript\n * import { entrypoint, getPreviousState } from \"@langchain/langgraph\";\n * import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n *\n * const myWorkflow = entrypoint({\n * name: \"accumulator\",\n * checkpointer: new MemorySaver()\n * }, async (num: number) => {\n * const previous = getPreviousState<number>();\n *\n * // This will return the previous value to the caller, saving\n * // 2 * num to the checkpoint, which will be used in the next invocation\n * // for the `previous` parameter.\n * return entrypoint.final({\n * value: previous ?? 0,\n * save: 2 * num\n * });\n * });\n *\n * const config = {\n * configurable: {\n * thread_id: \"some_thread\"\n * }\n * };\n *\n * await myWorkflow.invoke(3, config); // 0 (previous was undefined)\n * await myWorkflow.invoke(1, config); // 6 (previous was 3 * 2 from the previous invocation)\n * ```\n * @category Functional API\n */\nexport const entrypoint = function entrypoint<InputT, OutputT>(\n optionsOrName: EntrypointOptions | string,\n func: EntrypointFunc<InputT, OutputT>\n) {\n const { name, checkpointer, store, cache } =\n typeof optionsOrName === \"string\"\n ? { name: optionsOrName, checkpointer: undefined, store: undefined }\n : optionsOrName;\n const timeout = coerceTimeoutPolicy(\n typeof optionsOrName === \"string\" ? undefined : optionsOrName.timeout\n );\n if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) {\n throw new Error(\n \"Generators are disallowed as entrypoints. For streaming responses, use config.write.\"\n );\n }\n const streamMode = \"updates\";\n const bound = getRunnableForEntrypoint(name, func);\n\n // Helper to check if a value is an EntrypointFinal\n function isEntrypointFinal(\n value: unknown\n ): value is EntrypointFinal<unknown, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"__lg_type\" in value &&\n value.__lg_type === \"__pregel_final\"\n );\n }\n\n // Helper function to pluck the return value from EntrypointFinal or passthrough\n const pluckReturnValue = new RunnableCallable({\n name: \"pluckReturnValue\",\n func: (value: unknown) => {\n return isEntrypointFinal(value) ? value.value : value;\n },\n });\n\n // Helper function to pluck the save value from EntrypointFinal or passthrough\n const pluckSaveValue = new RunnableCallable({\n name: \"pluckSaveValue\",\n func: (value: unknown) => {\n return isEntrypointFinal(value) ? value.save : value;\n },\n });\n\n const entrypointNode = new PregelNode<InputT, EntrypointReturnT<OutputT>>({\n bound,\n triggers: [START],\n channels: [START],\n timeout,\n writers: [\n new ChannelWrite(\n [\n { channel: END, value: PASSTHROUGH, mapper: pluckReturnValue },\n { channel: PREVIOUS, value: PASSTHROUGH, mapper: pluckSaveValue },\n ],\n [TAG_HIDDEN]\n ),\n ],\n });\n\n return new Pregel<\n Record<string, PregelNode<InputT, EntrypointReturnT<OutputT>>>, // node types\n {\n [START]: EphemeralValue<InputT>;\n [END]: LastValue<EntrypointReturnT<OutputT>>;\n [PREVIOUS]: LastValue<EntrypointFinalSaveT<OutputT>>;\n }, // channel types\n Record<string, unknown>, // configurable types\n InputT, // input type\n EntrypointReturnT<OutputT> // output type\n >({\n name,\n checkpointer,\n nodes: {\n [name]: entrypointNode,\n },\n channels: {\n [START]: new EphemeralValue<InputT>(),\n [END]: new LastValue<EntrypointReturnT<OutputT>>(),\n [PREVIOUS]: new LastValue<EntrypointFinalSaveT<OutputT>>(),\n },\n inputChannels: START,\n outputChannels: END,\n streamChannels: END,\n streamMode,\n store,\n cache,\n });\n} as EntrypointFunction;\n\n// documented by the EntrypointFunction interface\nentrypoint.final = function final<ValueT, SaveT>({\n value,\n save,\n}: {\n value?: ValueT;\n save?: SaveT;\n}): EntrypointFinal<ValueT, SaveT> {\n return { value, save, __lg_type: \"__pregel_final\" };\n};\n\n/**\n * A helper utility function for use with the functional API that returns the previous\n * state from the checkpoint from the last invocation of the current thread.\n *\n * This function allows workflows to access state that was saved in previous runs\n * using {@link entrypoint.final}.\n *\n * @typeParam StateT - The type of the state that was previously saved\n * @returns The previous saved state from the last invocation of the current thread\n *\n * @example\n * ```typescript\n * const previousState = getPreviousState<{ counter: number }>();\n * const newCount = (previousState?.counter ?? 0) + 1;\n * ```\n * @category Functional API\n */\nexport function getPreviousState<StateT>(): StateT {\n const config: LangGraphRunnableConfig =\n AsyncLocalStorageProviderSingleton.getRunnableConfig();\n return config.configurable?.[CONFIG_KEY_PREVIOUS_STATE] as StateT;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkHA,SAAgB,KACd,eACA,MACsC;CACtC,MAAM,UACJ,OAAO,kBAAkB,WACrB;EACE,MAAM;EACN,OAAO,KAAA;EACP,aAAa,KAAA;EACb,SAAS,KAAA;EACV,GACD;CAEN,MAAM,EAAE,MAAM,UAAU;CACxB,MAAM,UAAUA,gBAAAA,oBAAoB,QAAQ,QAAQ;AACpD,KAAIC,cAAAA,yBAAyB,KAAK,IAAIC,cAAAA,oBAAoB,KAAK,CAC7D,OAAM,IAAI,MACR,iFACD;CAGH,MAAM,cACJ,QAAQ,gBAGP,WAAW,UAAW,QAAQ,QAAwB,KAAA;CAEzD,IAAI;AACJ,KAAI,OAAO,gBAAgB,UACzB,SAAQ,cAAc,EAAE,GAAG,KAAA;KAE3B,SAAQ;AAGV,SAAQ,GAAG,SAAgB;AACzB,SAAOC,a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;GAAU,OAAOD,cAAAA;GAAa,QAAQ;GAAgB,CAClE,EACD,CAACE,kBAAAA,WAAW,CACb,CACF;EACF,CAAC;AAEF,QAAO,IAAIC,qBAAAA,OAUT;EACA;EACA;EACA,OAAO,GACJ,OAAO,gBACT;EACD,UAAU;IACPN,kBAAAA,QAAQ,IAAIO,wBAAAA,gBAAwB;IACpCL,kBAAAA,MAAM,IAAIM,mBAAAA,WAAuC;IACjDJ,kBAAAA,WAAW,IAAII,mBAAAA,WAA0C;GAC3D;EACD,eAAeR,kBAAAA;EACf,gBAAgBE,kBAAAA;EAChB,gBAAgBA,kBAAAA;EAChB;EACA;EACA;EACD,CAAC;;AAIJ,WAAW,QAAQ,SAAS,MAAqB,EAC/C,OACA,QAIiC;AACjC,QAAO;EAAE;EAAO;EAAM,WAAW;EAAkB;;;;;;;;;;;;;;;;;;;AAoBrD,SAAgB,mBAAmC;AAGjD,QADEO,2BAAAA,mCAAmC,mBAAmB,CAC1C,eAAeC,kBAAAA"}
|
package/dist/func/index.d.cts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { TimeoutPolicy } from "../pregel/utils/timeout.cjs";
|
|
1
2
|
import { END, PREVIOUS, START } from "../constants.cjs";
|
|
2
3
|
import { LastValue } from "../channels/last_value.cjs";
|
|
3
4
|
import { EphemeralValue } from "../channels/ephemeral_value.cjs";
|
|
@@ -25,6 +26,13 @@ interface TaskOptions {
|
|
|
25
26
|
* The cache policy for the task. Configures how the task should be cached.
|
|
26
27
|
*/
|
|
27
28
|
cachePolicy?: CachePolicy;
|
|
29
|
+
/**
|
|
30
|
+
* Maximum duration for a single attempt of this task. Accepts a number of
|
|
31
|
+
* milliseconds (a hard wall-clock cap) or a {@link TimeoutPolicy} for finer
|
|
32
|
+
* control. When exceeded, a {@link NodeTimeoutError} is raised and the task's
|
|
33
|
+
* retry policy (if any) decides whether to retry.
|
|
34
|
+
*/
|
|
35
|
+
timeout?: number | TimeoutPolicy;
|
|
28
36
|
}
|
|
29
37
|
/**
|
|
30
38
|
* Define a LangGraph task using the `task` function.
|
|
@@ -96,6 +104,12 @@ type EntrypointOptions = {
|
|
|
96
104
|
* The cache for the {@link entrypoint}. Used to cache values between workflow runs.
|
|
97
105
|
*/
|
|
98
106
|
cache?: BaseCache;
|
|
107
|
+
/**
|
|
108
|
+
* Maximum duration for a single attempt of this entrypoint. Accepts a number
|
|
109
|
+
* of milliseconds (a hard wall-clock cap) or a {@link TimeoutPolicy} for finer
|
|
110
|
+
* control. When exceeded, a {@link NodeTimeoutError} is raised.
|
|
111
|
+
*/
|
|
112
|
+
timeout?: number | TimeoutPolicy;
|
|
99
113
|
};
|
|
100
114
|
/**
|
|
101
115
|
* Type declaration for the entrypoint function with its properties
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/func/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/func/index.ts"],"mappings":";;;;;;;;;;;;;;UA0CiB,WAAA;EAAW;;;EAI1B,IAAA;EAkBmB;;;;EAbnB,KAAA,GAAQ,WAAA;EAAA;;;EAKR,WAAA,GAAc,WAAA;EAQK;;;AAkDrB;;;EAlDE,OAAA,YAAmB,aAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;AA6FrB;;;;;;;;;;;;;;;;;;;;AAiCA;;;;;;iBA5EgB,IAAA,kCAAA,CACd,aAAA,EAAe,WAAA,WACf,IAAA,EAAM,QAAA,CAAS,KAAA,EAAO,OAAA,QACjB,IAAA,EAAM,KAAA,KAAU,OAAA,CAAQ,OAAA;;;;KAwCnB,iBAAA;EAsCR;;;;EAjCF,IAAA;EAoCqB;;;;EA/BrB,YAAA,GAAe,mBAAA;EAgCC;;;EA5BhB,KAAA,GAAQ,SAAA;EAgCY;;;EA3BpB,KAAA,GAAQ,SAAA;EA+BN;;;;;EAxBF,OAAA,YAAmB,aAAA;AAAA;;;;;UAOJ,kBAAA;EAAA,kBAEb,aAAA,EAAe,iBAAA,WACf,IAAA,EAAM,cAAA,CAAe,MAAA,EAAQ,OAAA,IAC5B,MAAA,CACD,MAAA,SAAe,UAAA,CAAW,MAAA,EAAQ,iBAAA,CAAkB,OAAA;IAAA,CAEjD,KAAA,GAAQ,cAAA,CAAe,MAAA;IAAA,CACvB,GAAA,GAAM,SAAA,CAAU,iBAAA,CAAkB,OAAA;IAAA,CAClC,QAAA,GAAW,SAAA,CAAU,oBAAA,CAAqB,OAAA;EAAA,GAE7C,MAAA,mBACA,MAAA,EACA,iBAAA,CAAkB,OAAA,QAIlB,OAAA,CAAQ,iBAAA,CAAkB,OAAA;EAbzB;;;;;;;;;;;;;;;;;;;EAmCH,KAAA,gBAAqB,OAAA;IACnB,KAAA,GAAQ,MAAA;IACR,IAAA,GAAO,KAAA;EAAA,IACL,eAAA,CAAgB,MAAA,EAAQ,KAAA;AAAA;;;;;;;;;;;;;;AAuI9B;;;;;AAyHA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAzHa,UAAA,EAAU,kBAAA;;;;;;;;;;;;;;;;;;iBAyHP,gBAAA,QAAA,CAAA,GAA4B,MAAA"}
|
package/dist/func/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { TimeoutPolicy } from "../pregel/utils/timeout.js";
|
|
1
2
|
import { END, PREVIOUS, START } from "../constants.js";
|
|
2
3
|
import { LastValue } from "../channels/last_value.js";
|
|
3
4
|
import { EphemeralValue } from "../channels/ephemeral_value.js";
|
|
@@ -25,6 +26,13 @@ interface TaskOptions {
|
|
|
25
26
|
* The cache policy for the task. Configures how the task should be cached.
|
|
26
27
|
*/
|
|
27
28
|
cachePolicy?: CachePolicy;
|
|
29
|
+
/**
|
|
30
|
+
* Maximum duration for a single attempt of this task. Accepts a number of
|
|
31
|
+
* milliseconds (a hard wall-clock cap) or a {@link TimeoutPolicy} for finer
|
|
32
|
+
* control. When exceeded, a {@link NodeTimeoutError} is raised and the task's
|
|
33
|
+
* retry policy (if any) decides whether to retry.
|
|
34
|
+
*/
|
|
35
|
+
timeout?: number | TimeoutPolicy;
|
|
28
36
|
}
|
|
29
37
|
/**
|
|
30
38
|
* Define a LangGraph task using the `task` function.
|
|
@@ -96,6 +104,12 @@ type EntrypointOptions = {
|
|
|
96
104
|
* The cache for the {@link entrypoint}. Used to cache values between workflow runs.
|
|
97
105
|
*/
|
|
98
106
|
cache?: BaseCache;
|
|
107
|
+
/**
|
|
108
|
+
* Maximum duration for a single attempt of this entrypoint. Accepts a number
|
|
109
|
+
* of milliseconds (a hard wall-clock cap) or a {@link TimeoutPolicy} for finer
|
|
110
|
+
* control. When exceeded, a {@link NodeTimeoutError} is raised.
|
|
111
|
+
*/
|
|
112
|
+
timeout?: number | TimeoutPolicy;
|
|
99
113
|
};
|
|
100
114
|
/**
|
|
101
115
|
* Type declaration for the entrypoint function with its properties
|
package/dist/func/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/func/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/func/index.ts"],"mappings":";;;;;;;;;;;;;;UA0CiB,WAAA;EAAW;;;EAI1B,IAAA;EAkBmB;;;;EAbnB,KAAA,GAAQ,WAAA;EAAA;;;EAKR,WAAA,GAAc,WAAA;EAQK;;;AAkDrB;;;EAlDE,OAAA,YAAmB,aAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;AA6FrB;;;;;;;;;;;;;;;;;;;;AAiCA;;;;;;iBA5EgB,IAAA,kCAAA,CACd,aAAA,EAAe,WAAA,WACf,IAAA,EAAM,QAAA,CAAS,KAAA,EAAO,OAAA,QACjB,IAAA,EAAM,KAAA,KAAU,OAAA,CAAQ,OAAA;;;;KAwCnB,iBAAA;EAsCR;;;;EAjCF,IAAA;EAoCqB;;;;EA/BrB,YAAA,GAAe,mBAAA;EAgCC;;;EA5BhB,KAAA,GAAQ,SAAA;EAgCY;;;EA3BpB,KAAA,GAAQ,SAAA;EA+BN;;;;;EAxBF,OAAA,YAAmB,aAAA;AAAA;;;;;UAOJ,kBAAA;EAAA,kBAEb,aAAA,EAAe,iBAAA,WACf,IAAA,EAAM,cAAA,CAAe,MAAA,EAAQ,OAAA,IAC5B,MAAA,CACD,MAAA,SAAe,UAAA,CAAW,MAAA,EAAQ,iBAAA,CAAkB,OAAA;IAAA,CAEjD,KAAA,GAAQ,cAAA,CAAe,MAAA;IAAA,CACvB,GAAA,GAAM,SAAA,CAAU,iBAAA,CAAkB,OAAA;IAAA,CAClC,QAAA,GAAW,SAAA,CAAU,oBAAA,CAAqB,OAAA;EAAA,GAE7C,MAAA,mBACA,MAAA,EACA,iBAAA,CAAkB,OAAA,QAIlB,OAAA,CAAQ,iBAAA,CAAkB,OAAA;EAbzB;;;;;;;;;;;;;;;;;;;EAmCH,KAAA,gBAAqB,OAAA;IACnB,KAAA,GAAQ,MAAA;IACR,IAAA,GAAO,KAAA;EAAA,IACL,eAAA,CAAgB,MAAA,EAAQ,KAAA;AAAA;;;;;;;;;;;;;;AAuI9B;;;;;AAyHA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAzHa,UAAA,EAAU,kBAAA;;;;;;;;;;;;;;;;;;iBAyHP,gBAAA,QAAA,CAAA,GAA4B,MAAA"}
|
package/dist/func/index.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { coerceTimeoutPolicy } from "../pregel/utils/timeout.js";
|
|
1
2
|
import { CONFIG_KEY_PREVIOUS_STATE, END, PREVIOUS, START, TAG_HIDDEN } from "../constants.js";
|
|
2
3
|
import { LastValue } from "../channels/last_value.js";
|
|
3
4
|
import { RunnableCallable, isAsyncGeneratorFunction, isGeneratorFunction } from "../utils.js";
|
|
4
5
|
import { ChannelWrite, PASSTHROUGH } from "../pregel/write.js";
|
|
5
6
|
import { PregelNode } from "../pregel/read.js";
|
|
7
|
+
import "../pregel/utils/index.js";
|
|
6
8
|
import { call, getRunnableForEntrypoint } from "../pregel/call.js";
|
|
7
9
|
import { Pregel } from "../pregel/index.js";
|
|
8
10
|
import { EphemeralValue } from "../channels/ephemeral_value.js";
|
|
@@ -59,9 +61,11 @@ function task(optionsOrName, func) {
|
|
|
59
61
|
const options = typeof optionsOrName === "string" ? {
|
|
60
62
|
name: optionsOrName,
|
|
61
63
|
retry: void 0,
|
|
62
|
-
cachePolicy: void 0
|
|
64
|
+
cachePolicy: void 0,
|
|
65
|
+
timeout: void 0
|
|
63
66
|
} : optionsOrName;
|
|
64
67
|
const { name, retry } = options;
|
|
68
|
+
const timeout = coerceTimeoutPolicy(options.timeout);
|
|
65
69
|
if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) throw new Error("Generators are disallowed as tasks. For streaming responses, use config.write.");
|
|
66
70
|
const cachePolicy = options.cachePolicy ?? ("cache" in options ? options.cache : void 0);
|
|
67
71
|
let cache;
|
|
@@ -72,7 +76,8 @@ function task(optionsOrName, func) {
|
|
|
72
76
|
func,
|
|
73
77
|
name,
|
|
74
78
|
retry,
|
|
75
|
-
cache
|
|
79
|
+
cache,
|
|
80
|
+
timeout
|
|
76
81
|
}, ...args);
|
|
77
82
|
};
|
|
78
83
|
}
|
|
@@ -214,6 +219,7 @@ const entrypoint = function entrypoint(optionsOrName, func) {
|
|
|
214
219
|
checkpointer: void 0,
|
|
215
220
|
store: void 0
|
|
216
221
|
} : optionsOrName;
|
|
222
|
+
const timeout = coerceTimeoutPolicy(typeof optionsOrName === "string" ? void 0 : optionsOrName.timeout);
|
|
217
223
|
if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write.");
|
|
218
224
|
const streamMode = "updates";
|
|
219
225
|
const bound = getRunnableForEntrypoint(name, func);
|
|
@@ -236,6 +242,7 @@ const entrypoint = function entrypoint(optionsOrName, func) {
|
|
|
236
242
|
bound,
|
|
237
243
|
triggers: [START],
|
|
238
244
|
channels: [START],
|
|
245
|
+
timeout,
|
|
239
246
|
writers: [new ChannelWrite([{
|
|
240
247
|
channel: END,
|
|
241
248
|
value: PASSTHROUGH,
|
package/dist/func/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/func/index.ts"],"sourcesContent":["import {\n BaseCache,\n BaseCheckpointSaver,\n BaseStore,\n} from \"@langchain/langgraph-checkpoint\";\nimport { AsyncLocalStorageProviderSingleton } from \"@langchain/core/singletons\";\nimport { Pregel } from \"../pregel/index.js\";\nimport { PregelNode } from \"../pregel/read.js\";\nimport {\n CONFIG_KEY_PREVIOUS_STATE,\n END,\n PREVIOUS,\n START,\n TAG_HIDDEN,\n} from \"../constants.js\";\nimport { EphemeralValue } from \"../channels/ephemeral_value.js\";\nimport { call, getRunnableForEntrypoint } from \"../pregel/call.js\";\nimport type { CachePolicy, RetryPolicy } from \"../pregel/utils/index.js\";\nimport { LastValue } from \"../channels/last_value.js\";\nimport {\n EntrypointFinal,\n EntrypointReturnT,\n EntrypointFinalSaveT,\n EntrypointFunc,\n TaskFunc,\n} from \"./types.js\";\nimport { LangGraphRunnableConfig } from \"../pregel/runnable_types.js\";\nimport {\n RunnableCallable,\n isAsyncGeneratorFunction,\n isGeneratorFunction,\n} from \"../utils.js\";\nimport { ChannelWrite, PASSTHROUGH } from \"../pregel/write.js\";\n\n/**\n * Options for the {@link task} function\n */\nexport interface TaskOptions {\n /**\n * The name of the task, analogous to the node name in {@link StateGraph}.\n */\n name: string;\n /**\n * The retry policy for the task. Configures how many times and under what conditions\n * the task should be retried if it fails.\n */\n retry?: RetryPolicy;\n\n /**\n * The cache policy for the task. Configures how the task should be cached.\n */\n cachePolicy?: CachePolicy;\n}\n\n/**\n * Define a LangGraph task using the `task` function.\n *\n * Tasks can only be called from within an {@link entrypoint} or from within a StateGraph.\n * A task can be called like a regular function with the following differences:\n *\n * - When a checkpointer is enabled, the function inputs and outputs must be serializable.\n * - The wrapped function can only be called from within an entrypoint or StateGraph.\n * - Calling the function produces a promise. This makes it easy to parallelize tasks.\n *\n * @typeParam ArgsT - The type of arguments the task function accepts\n * @typeParam OutputT - The type of value the task function returns\n * @param optionsOrName - Either an {@link TaskOptions} object, or a string for the name of the task\n * @param func - The function that executes this task\n * @returns A proxy function that accepts the same arguments as the original and always returns the result as a Promise\n *\n * @example basic example\n * ```typescript\n * const addOne = task(\"add\", async (a: number) => a + 1);\n *\n * const workflow = entrypoint(\"example\", async (numbers: number[]) => {\n * const promises = numbers.map(n => addOne(n));\n * const results = await Promise.all(promises);\n * return results;\n * });\n *\n * // Call the entrypoint\n * await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4]\n * ```\n *\n * @example using a retry policy\n * ```typescript\n * const addOne = task({\n * name: \"add\",\n * retry: { maxAttempts: 3 }\n * },\n * async (a: number) => a + 1\n * );\n *\n * const workflow = entrypoint(\"example\", async (numbers: number[]) => {\n * const promises = numbers.map(n => addOne(n));\n * const results = await Promise.all(promises);\n * return results;\n * });\n * ```\n * @category Functional API\n */\nexport function task<ArgsT extends unknown[], OutputT>(\n optionsOrName: TaskOptions | string,\n func: TaskFunc<ArgsT, OutputT>\n): (...args: ArgsT) => Promise<OutputT> {\n const options =\n typeof optionsOrName === \"string\"\n ? { name: optionsOrName, retry: undefined, cachePolicy: undefined }\n : optionsOrName;\n\n const { name, retry } = options;\n if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) {\n throw new Error(\n \"Generators are disallowed as tasks. For streaming responses, use config.write.\"\n );\n }\n\n const cachePolicy =\n options.cachePolicy ??\n // `cache` was mistakingly used as an alias for `cachePolicy` in v0.3.x,\n // TODO: remove in 1.x\n (\"cache\" in options ? (options.cache as CachePolicy) : undefined);\n\n let cache: CachePolicy | undefined;\n if (typeof cachePolicy === \"boolean\") {\n cache = cachePolicy ? {} : undefined;\n } else {\n cache = cachePolicy;\n }\n\n return (...args: ArgsT) => {\n return call({ func, name, retry, cache }, ...args);\n };\n}\n\n/**\n * Options for the {@link entrypoint} function\n */\nexport type EntrypointOptions = {\n /**\n * The name of the {@link entrypoint}, analogous to the node name in {@link StateGraph}.\n * This name is used for logging, debugging, and checkpoint identification.\n */\n name: string;\n /**\n * The checkpointer for the {@link entrypoint}. Used to save and restore state between\n * invocations of the workflow.\n */\n checkpointer?: BaseCheckpointSaver;\n /**\n * The store for the {@link entrypoint}. Used to persist data across workflow runs.\n */\n store?: BaseStore;\n\n /**\n * The cache for the {@link entrypoint}. Used to cache values between workflow runs.\n */\n cache?: BaseCache;\n};\n\n/**\n * Type declaration for the entrypoint function with its properties\n * @category Functional API\n */\nexport interface EntrypointFunction {\n <InputT, OutputT>(\n optionsOrName: EntrypointOptions | string,\n func: EntrypointFunc<InputT, OutputT>\n ): Pregel<\n Record<string, PregelNode<InputT, EntrypointReturnT<OutputT>>>,\n {\n [START]: EphemeralValue<InputT>;\n [END]: LastValue<EntrypointReturnT<OutputT>>;\n [PREVIOUS]: LastValue<EntrypointFinalSaveT<OutputT>>;\n },\n Record<string, unknown>,\n InputT,\n EntrypointReturnT<OutputT>,\n // Because the update type is an return type union of tasks + entrypoint,\n // thus we can't type it properly.\n any, // eslint-disable-line @typescript-eslint/no-explicit-any\n Awaited<EntrypointReturnT<OutputT>>\n >;\n\n /**\n * A helper utility for use with the functional API that returns a value to the caller,\n * as well as a separate state value to persist to the checkpoint. This allows workflows\n * to maintain state between runs while returning different values to the caller.\n *\n * @typeParam ValueT - The type of the value to return to the caller\n * @typeParam SaveT - The type of the state to save to the checkpoint\n * @param options.value - The value to return to the caller\n * @param options.save - The value to save to the checkpoint\n * @returns An object with the value and save properties\n *\n * @example\n * ```typescript\n * return entrypoint.final({\n * value: \"result for caller\",\n * save: { counter: currentCount + 1 }\n * });\n * ```\n */\n final<ValueT, SaveT>(options: {\n value?: ValueT;\n save?: SaveT;\n }): EntrypointFinal<ValueT, SaveT>;\n}\n\n/**\n * Define a LangGraph workflow using the `entrypoint` function.\n *\n * ### Function signature\n *\n * The wrapped function must accept at most **two parameters**. The first parameter\n * is the input to the function. The second (optional) parameter is a\n * {@link LangGraphRunnableConfig} object. If you wish to pass multiple parameters to\n * the function, you can pass them as an object.\n *\n * ### Helper functions\n *\n * #### Streaming\n * To write data to the \"custom\" stream, use the {@link getWriter} function, or the\n * {@link LangGraphRunnableConfig.writer} property.\n *\n * #### State management\n * The {@link getPreviousState} function can be used to access the previous state\n * that was returned from the last invocation of the entrypoint on the same thread id.\n *\n * If you wish to save state other than the return value, you can use the\n * {@link entrypoint.final} function.\n *\n * @typeParam InputT - The type of input the entrypoint accepts\n * @typeParam OutputT - The type of output the entrypoint produces\n * @param optionsOrName - Either an {@link EntrypointOptions} object, or a string for the name of the entrypoint\n * @param func - The function that executes this entrypoint\n * @returns A {@link Pregel} instance that can be run to execute the workflow\n *\n * @example Using entrypoint and tasks\n * ```typescript\n * import { task, entrypoint } from \"@langchain/langgraph\";\n * import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n * import { interrupt, Command } from \"@langchain/langgraph\";\n *\n * const composeEssay = task(\"compose\", async (topic: string) => {\n * await new Promise(r => setTimeout(r, 1000)); // Simulate slow operation\n * return `An essay about ${topic}`;\n * });\n *\n * const reviewWorkflow = entrypoint({\n * name: \"review\",\n * checkpointer: new MemorySaver()\n * }, async (topic: string) => {\n * const essay = await composeEssay(topic);\n * const humanReview = await interrupt({\n * question: \"Please provide a review\",\n * essay\n * });\n * return {\n * essay,\n * review: humanReview\n * };\n * });\n *\n * // Example configuration for the workflow\n * const config = {\n * configurable: {\n * thread_id: \"some_thread\"\n * }\n * };\n *\n * // Topic for the essay\n * const topic = \"cats\";\n *\n * // Stream the workflow to generate the essay and await human review\n * for await (const result of reviewWorkflow.stream(topic, config)) {\n * console.log(result);\n * }\n *\n * // Example human review provided after the interrupt\n * const humanReview = \"This essay is great.\";\n *\n * // Resume the workflow with the provided human review\n * for await (const result of reviewWorkflow.stream(new Command({ resume: humanReview }), config)) {\n * console.log(result);\n * }\n * ```\n *\n * @example Accessing the previous return value\n * ```typescript\n * import { entrypoint, getPreviousState } from \"@langchain/langgraph\";\n * import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n *\n * const accumulator = entrypoint({\n * name: \"accumulator\",\n * checkpointer: new MemorySaver()\n * }, async (input: string) => {\n * const previous = getPreviousState<number>();\n * return previous !== undefined ? `${previous } ${input}` : input;\n * });\n *\n * const config = {\n * configurable: {\n * thread_id: \"some_thread\"\n * }\n * };\n * await accumulator.invoke(\"hello\", config); // returns \"hello\"\n * await accumulator.invoke(\"world\", config); // returns \"hello world\"\n * ```\n *\n * @example Using entrypoint.final to save a value\n * ```typescript\n * import { entrypoint, getPreviousState } from \"@langchain/langgraph\";\n * import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n *\n * const myWorkflow = entrypoint({\n * name: \"accumulator\",\n * checkpointer: new MemorySaver()\n * }, async (num: number) => {\n * const previous = getPreviousState<number>();\n *\n * // This will return the previous value to the caller, saving\n * // 2 * num to the checkpoint, which will be used in the next invocation\n * // for the `previous` parameter.\n * return entrypoint.final({\n * value: previous ?? 0,\n * save: 2 * num\n * });\n * });\n *\n * const config = {\n * configurable: {\n * thread_id: \"some_thread\"\n * }\n * };\n *\n * await myWorkflow.invoke(3, config); // 0 (previous was undefined)\n * await myWorkflow.invoke(1, config); // 6 (previous was 3 * 2 from the previous invocation)\n * ```\n * @category Functional API\n */\nexport const entrypoint = function entrypoint<InputT, OutputT>(\n optionsOrName: EntrypointOptions | string,\n func: EntrypointFunc<InputT, OutputT>\n) {\n const { name, checkpointer, store, cache } =\n typeof optionsOrName === \"string\"\n ? { name: optionsOrName, checkpointer: undefined, store: undefined }\n : optionsOrName;\n if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) {\n throw new Error(\n \"Generators are disallowed as entrypoints. For streaming responses, use config.write.\"\n );\n }\n const streamMode = \"updates\";\n const bound = getRunnableForEntrypoint(name, func);\n\n // Helper to check if a value is an EntrypointFinal\n function isEntrypointFinal(\n value: unknown\n ): value is EntrypointFinal<unknown, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"__lg_type\" in value &&\n value.__lg_type === \"__pregel_final\"\n );\n }\n\n // Helper function to pluck the return value from EntrypointFinal or passthrough\n const pluckReturnValue = new RunnableCallable({\n name: \"pluckReturnValue\",\n func: (value: unknown) => {\n return isEntrypointFinal(value) ? value.value : value;\n },\n });\n\n // Helper function to pluck the save value from EntrypointFinal or passthrough\n const pluckSaveValue = new RunnableCallable({\n name: \"pluckSaveValue\",\n func: (value: unknown) => {\n return isEntrypointFinal(value) ? value.save : value;\n },\n });\n\n const entrypointNode = new PregelNode<InputT, EntrypointReturnT<OutputT>>({\n bound,\n triggers: [START],\n channels: [START],\n writers: [\n new ChannelWrite(\n [\n { channel: END, value: PASSTHROUGH, mapper: pluckReturnValue },\n { channel: PREVIOUS, value: PASSTHROUGH, mapper: pluckSaveValue },\n ],\n [TAG_HIDDEN]\n ),\n ],\n });\n\n return new Pregel<\n Record<string, PregelNode<InputT, EntrypointReturnT<OutputT>>>, // node types\n {\n [START]: EphemeralValue<InputT>;\n [END]: LastValue<EntrypointReturnT<OutputT>>;\n [PREVIOUS]: LastValue<EntrypointFinalSaveT<OutputT>>;\n }, // channel types\n Record<string, unknown>, // configurable types\n InputT, // input type\n EntrypointReturnT<OutputT> // output type\n >({\n name,\n checkpointer,\n nodes: {\n [name]: entrypointNode,\n },\n channels: {\n [START]: new EphemeralValue<InputT>(),\n [END]: new LastValue<EntrypointReturnT<OutputT>>(),\n [PREVIOUS]: new LastValue<EntrypointFinalSaveT<OutputT>>(),\n },\n inputChannels: START,\n outputChannels: END,\n streamChannels: END,\n streamMode,\n store,\n cache,\n });\n} as EntrypointFunction;\n\n// documented by the EntrypointFunction interface\nentrypoint.final = function final<ValueT, SaveT>({\n value,\n save,\n}: {\n value?: ValueT;\n save?: SaveT;\n}): EntrypointFinal<ValueT, SaveT> {\n return { value, save, __lg_type: \"__pregel_final\" };\n};\n\n/**\n * A helper utility function for use with the functional API that returns the previous\n * state from the checkpoint from the last invocation of the current thread.\n *\n * This function allows workflows to access state that was saved in previous runs\n * using {@link entrypoint.final}.\n *\n * @typeParam StateT - The type of the state that was previously saved\n * @returns The previous saved state from the last invocation of the current thread\n *\n * @example\n * ```typescript\n * const previousState = getPreviousState<{ counter: number }>();\n * const newCount = (previousState?.counter ?? 0) + 1;\n * ```\n * @category Functional API\n */\nexport function getPreviousState<StateT>(): StateT {\n const config: LangGraphRunnableConfig =\n AsyncLocalStorageProviderSingleton.getRunnableConfig();\n return config.configurable?.[CONFIG_KEY_PREVIOUS_STATE] as StateT;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqGA,SAAgB,KACd,eACA,MACsC;CACtC,MAAM,UACJ,OAAO,kBAAkB,WACrB;EAAE,MAAM;EAAe,OAAO,KAAA;EAAW,aAAa,KAAA;EAAW,GACjE;CAEN,MAAM,EAAE,MAAM,UAAU;AACxB,KAAI,yBAAyB,KAAK,IAAI,oBAAoB,KAAK,CAC7D,OAAM,IAAI,MACR,iFACD;CAGH,MAAM,cACJ,QAAQ,gBAGP,WAAW,UAAW,QAAQ,QAAwB,KAAA;CAEzD,IAAI;AACJ,KAAI,OAAO,gBAAgB,UACzB,SAAQ,cAAc,EAAE,GAAG,KAAA;KAE3B,SAAQ;AAGV,SAAQ,GAAG,SAAgB;AACzB,SAAO,KAAK;GAAE;GAAM;GAAM;GAAO;GAAO,EAAE,GAAG,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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C/C,OACA,QAIiC;AACjC,QAAO;EAAE;EAAO;EAAM,WAAW;EAAkB;;;;;;;;;;;;;;;;;;;AAoBrD,SAAgB,mBAAmC;AAGjD,QADE,mCAAmC,mBAAmB,CAC1C,eAAe"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/func/index.ts"],"sourcesContent":["import {\n BaseCache,\n BaseCheckpointSaver,\n BaseStore,\n} from \"@langchain/langgraph-checkpoint\";\nimport { AsyncLocalStorageProviderSingleton } from \"@langchain/core/singletons\";\nimport { Pregel } from \"../pregel/index.js\";\nimport { PregelNode } from \"../pregel/read.js\";\nimport {\n CONFIG_KEY_PREVIOUS_STATE,\n END,\n PREVIOUS,\n START,\n TAG_HIDDEN,\n} from \"../constants.js\";\nimport { EphemeralValue } from \"../channels/ephemeral_value.js\";\nimport { call, getRunnableForEntrypoint } from \"../pregel/call.js\";\nimport type {\n CachePolicy,\n RetryPolicy,\n TimeoutPolicy,\n} from \"../pregel/utils/index.js\";\nimport { coerceTimeoutPolicy } from \"../pregel/utils/index.js\";\nimport { LastValue } from \"../channels/last_value.js\";\nimport {\n EntrypointFinal,\n EntrypointReturnT,\n EntrypointFinalSaveT,\n EntrypointFunc,\n TaskFunc,\n} from \"./types.js\";\nimport { LangGraphRunnableConfig } from \"../pregel/runnable_types.js\";\nimport {\n RunnableCallable,\n isAsyncGeneratorFunction,\n isGeneratorFunction,\n} from \"../utils.js\";\nimport { ChannelWrite, PASSTHROUGH } from \"../pregel/write.js\";\n\n/**\n * Options for the {@link task} function\n */\nexport interface TaskOptions {\n /**\n * The name of the task, analogous to the node name in {@link StateGraph}.\n */\n name: string;\n /**\n * The retry policy for the task. Configures how many times and under what conditions\n * the task should be retried if it fails.\n */\n retry?: RetryPolicy;\n\n /**\n * The cache policy for the task. Configures how the task should be cached.\n */\n cachePolicy?: CachePolicy;\n\n /**\n * Maximum duration for a single attempt of this task. Accepts a number of\n * milliseconds (a hard wall-clock cap) or a {@link TimeoutPolicy} for finer\n * control. When exceeded, a {@link NodeTimeoutError} is raised and the task's\n * retry policy (if any) decides whether to retry.\n */\n timeout?: number | TimeoutPolicy;\n}\n\n/**\n * Define a LangGraph task using the `task` function.\n *\n * Tasks can only be called from within an {@link entrypoint} or from within a StateGraph.\n * A task can be called like a regular function with the following differences:\n *\n * - When a checkpointer is enabled, the function inputs and outputs must be serializable.\n * - The wrapped function can only be called from within an entrypoint or StateGraph.\n * - Calling the function produces a promise. This makes it easy to parallelize tasks.\n *\n * @typeParam ArgsT - The type of arguments the task function accepts\n * @typeParam OutputT - The type of value the task function returns\n * @param optionsOrName - Either an {@link TaskOptions} object, or a string for the name of the task\n * @param func - The function that executes this task\n * @returns A proxy function that accepts the same arguments as the original and always returns the result as a Promise\n *\n * @example basic example\n * ```typescript\n * const addOne = task(\"add\", async (a: number) => a + 1);\n *\n * const workflow = entrypoint(\"example\", async (numbers: number[]) => {\n * const promises = numbers.map(n => addOne(n));\n * const results = await Promise.all(promises);\n * return results;\n * });\n *\n * // Call the entrypoint\n * await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4]\n * ```\n *\n * @example using a retry policy\n * ```typescript\n * const addOne = task({\n * name: \"add\",\n * retry: { maxAttempts: 3 }\n * },\n * async (a: number) => a + 1\n * );\n *\n * const workflow = entrypoint(\"example\", async (numbers: number[]) => {\n * const promises = numbers.map(n => addOne(n));\n * const results = await Promise.all(promises);\n * return results;\n * });\n * ```\n * @category Functional API\n */\nexport function task<ArgsT extends unknown[], OutputT>(\n optionsOrName: TaskOptions | string,\n func: TaskFunc<ArgsT, OutputT>\n): (...args: ArgsT) => Promise<OutputT> {\n const options =\n typeof optionsOrName === \"string\"\n ? {\n name: optionsOrName,\n retry: undefined,\n cachePolicy: undefined,\n timeout: undefined,\n }\n : optionsOrName;\n\n const { name, retry } = options;\n const timeout = coerceTimeoutPolicy(options.timeout);\n if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) {\n throw new Error(\n \"Generators are disallowed as tasks. For streaming responses, use config.write.\"\n );\n }\n\n const cachePolicy =\n options.cachePolicy ??\n // `cache` was mistakingly used as an alias for `cachePolicy` in v0.3.x,\n // TODO: remove in 1.x\n (\"cache\" in options ? (options.cache as CachePolicy) : undefined);\n\n let cache: CachePolicy | undefined;\n if (typeof cachePolicy === \"boolean\") {\n cache = cachePolicy ? {} : undefined;\n } else {\n cache = cachePolicy;\n }\n\n return (...args: ArgsT) => {\n return call({ func, name, retry, cache, timeout }, ...args);\n };\n}\n\n/**\n * Options for the {@link entrypoint} function\n */\nexport type EntrypointOptions = {\n /**\n * The name of the {@link entrypoint}, analogous to the node name in {@link StateGraph}.\n * This name is used for logging, debugging, and checkpoint identification.\n */\n name: string;\n /**\n * The checkpointer for the {@link entrypoint}. Used to save and restore state between\n * invocations of the workflow.\n */\n checkpointer?: BaseCheckpointSaver;\n /**\n * The store for the {@link entrypoint}. Used to persist data across workflow runs.\n */\n store?: BaseStore;\n\n /**\n * The cache for the {@link entrypoint}. Used to cache values between workflow runs.\n */\n cache?: BaseCache;\n\n /**\n * Maximum duration for a single attempt of this entrypoint. Accepts a number\n * of milliseconds (a hard wall-clock cap) or a {@link TimeoutPolicy} for finer\n * control. When exceeded, a {@link NodeTimeoutError} is raised.\n */\n timeout?: number | TimeoutPolicy;\n};\n\n/**\n * Type declaration for the entrypoint function with its properties\n * @category Functional API\n */\nexport interface EntrypointFunction {\n <InputT, OutputT>(\n optionsOrName: EntrypointOptions | string,\n func: EntrypointFunc<InputT, OutputT>\n ): Pregel<\n Record<string, PregelNode<InputT, EntrypointReturnT<OutputT>>>,\n {\n [START]: EphemeralValue<InputT>;\n [END]: LastValue<EntrypointReturnT<OutputT>>;\n [PREVIOUS]: LastValue<EntrypointFinalSaveT<OutputT>>;\n },\n Record<string, unknown>,\n InputT,\n EntrypointReturnT<OutputT>,\n // Because the update type is an return type union of tasks + entrypoint,\n // thus we can't type it properly.\n any, // eslint-disable-line @typescript-eslint/no-explicit-any\n Awaited<EntrypointReturnT<OutputT>>\n >;\n\n /**\n * A helper utility for use with the functional API that returns a value to the caller,\n * as well as a separate state value to persist to the checkpoint. This allows workflows\n * to maintain state between runs while returning different values to the caller.\n *\n * @typeParam ValueT - The type of the value to return to the caller\n * @typeParam SaveT - The type of the state to save to the checkpoint\n * @param options.value - The value to return to the caller\n * @param options.save - The value to save to the checkpoint\n * @returns An object with the value and save properties\n *\n * @example\n * ```typescript\n * return entrypoint.final({\n * value: \"result for caller\",\n * save: { counter: currentCount + 1 }\n * });\n * ```\n */\n final<ValueT, SaveT>(options: {\n value?: ValueT;\n save?: SaveT;\n }): EntrypointFinal<ValueT, SaveT>;\n}\n\n/**\n * Define a LangGraph workflow using the `entrypoint` function.\n *\n * ### Function signature\n *\n * The wrapped function must accept at most **two parameters**. The first parameter\n * is the input to the function. The second (optional) parameter is a\n * {@link LangGraphRunnableConfig} object. If you wish to pass multiple parameters to\n * the function, you can pass them as an object.\n *\n * ### Helper functions\n *\n * #### Streaming\n * To write data to the \"custom\" stream, use the {@link getWriter} function, or the\n * {@link LangGraphRunnableConfig.writer} property.\n *\n * #### State management\n * The {@link getPreviousState} function can be used to access the previous state\n * that was returned from the last invocation of the entrypoint on the same thread id.\n *\n * If you wish to save state other than the return value, you can use the\n * {@link entrypoint.final} function.\n *\n * @typeParam InputT - The type of input the entrypoint accepts\n * @typeParam OutputT - The type of output the entrypoint produces\n * @param optionsOrName - Either an {@link EntrypointOptions} object, or a string for the name of the entrypoint\n * @param func - The function that executes this entrypoint\n * @returns A {@link Pregel} instance that can be run to execute the workflow\n *\n * @example Using entrypoint and tasks\n * ```typescript\n * import { task, entrypoint } from \"@langchain/langgraph\";\n * import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n * import { interrupt, Command } from \"@langchain/langgraph\";\n *\n * const composeEssay = task(\"compose\", async (topic: string) => {\n * await new Promise(r => setTimeout(r, 1000)); // Simulate slow operation\n * return `An essay about ${topic}`;\n * });\n *\n * const reviewWorkflow = entrypoint({\n * name: \"review\",\n * checkpointer: new MemorySaver()\n * }, async (topic: string) => {\n * const essay = await composeEssay(topic);\n * const humanReview = await interrupt({\n * question: \"Please provide a review\",\n * essay\n * });\n * return {\n * essay,\n * review: humanReview\n * };\n * });\n *\n * // Example configuration for the workflow\n * const config = {\n * configurable: {\n * thread_id: \"some_thread\"\n * }\n * };\n *\n * // Topic for the essay\n * const topic = \"cats\";\n *\n * // Stream the workflow to generate the essay and await human review\n * for await (const result of reviewWorkflow.stream(topic, config)) {\n * console.log(result);\n * }\n *\n * // Example human review provided after the interrupt\n * const humanReview = \"This essay is great.\";\n *\n * // Resume the workflow with the provided human review\n * for await (const result of reviewWorkflow.stream(new Command({ resume: humanReview }), config)) {\n * console.log(result);\n * }\n * ```\n *\n * @example Accessing the previous return value\n * ```typescript\n * import { entrypoint, getPreviousState } from \"@langchain/langgraph\";\n * import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n *\n * const accumulator = entrypoint({\n * name: \"accumulator\",\n * checkpointer: new MemorySaver()\n * }, async (input: string) => {\n * const previous = getPreviousState<number>();\n * return previous !== undefined ? `${previous } ${input}` : input;\n * });\n *\n * const config = {\n * configurable: {\n * thread_id: \"some_thread\"\n * }\n * };\n * await accumulator.invoke(\"hello\", config); // returns \"hello\"\n * await accumulator.invoke(\"world\", config); // returns \"hello world\"\n * ```\n *\n * @example Using entrypoint.final to save a value\n * ```typescript\n * import { entrypoint, getPreviousState } from \"@langchain/langgraph\";\n * import { MemorySaver } from \"@langchain/langgraph-checkpoint\";\n *\n * const myWorkflow = entrypoint({\n * name: \"accumulator\",\n * checkpointer: new MemorySaver()\n * }, async (num: number) => {\n * const previous = getPreviousState<number>();\n *\n * // This will return the previous value to the caller, saving\n * // 2 * num to the checkpoint, which will be used in the next invocation\n * // for the `previous` parameter.\n * return entrypoint.final({\n * value: previous ?? 0,\n * save: 2 * num\n * });\n * });\n *\n * const config = {\n * configurable: {\n * thread_id: \"some_thread\"\n * }\n * };\n *\n * await myWorkflow.invoke(3, config); // 0 (previous was undefined)\n * await myWorkflow.invoke(1, config); // 6 (previous was 3 * 2 from the previous invocation)\n * ```\n * @category Functional API\n */\nexport const entrypoint = function entrypoint<InputT, OutputT>(\n optionsOrName: EntrypointOptions | string,\n func: EntrypointFunc<InputT, OutputT>\n) {\n const { name, checkpointer, store, cache } =\n typeof optionsOrName === \"string\"\n ? { name: optionsOrName, checkpointer: undefined, store: undefined }\n : optionsOrName;\n const timeout = coerceTimeoutPolicy(\n typeof optionsOrName === \"string\" ? undefined : optionsOrName.timeout\n );\n if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) {\n throw new Error(\n \"Generators are disallowed as entrypoints. For streaming responses, use config.write.\"\n );\n }\n const streamMode = \"updates\";\n const bound = getRunnableForEntrypoint(name, func);\n\n // Helper to check if a value is an EntrypointFinal\n function isEntrypointFinal(\n value: unknown\n ): value is EntrypointFinal<unknown, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"__lg_type\" in value &&\n value.__lg_type === \"__pregel_final\"\n );\n }\n\n // Helper function to pluck the return value from EntrypointFinal or passthrough\n const pluckReturnValue = new RunnableCallable({\n name: \"pluckReturnValue\",\n func: (value: unknown) => {\n return isEntrypointFinal(value) ? value.value : value;\n },\n });\n\n // Helper function to pluck the save value from EntrypointFinal or passthrough\n const pluckSaveValue = new RunnableCallable({\n name: \"pluckSaveValue\",\n func: (value: unknown) => {\n return isEntrypointFinal(value) ? value.save : value;\n },\n });\n\n const entrypointNode = new PregelNode<InputT, EntrypointReturnT<OutputT>>({\n bound,\n triggers: [START],\n channels: [START],\n timeout,\n writers: [\n new ChannelWrite(\n [\n { channel: END, value: PASSTHROUGH, mapper: pluckReturnValue },\n { channel: PREVIOUS, value: PASSTHROUGH, mapper: pluckSaveValue },\n ],\n [TAG_HIDDEN]\n ),\n ],\n });\n\n return new Pregel<\n Record<string, PregelNode<InputT, EntrypointReturnT<OutputT>>>, // node types\n {\n [START]: EphemeralValue<InputT>;\n [END]: LastValue<EntrypointReturnT<OutputT>>;\n [PREVIOUS]: LastValue<EntrypointFinalSaveT<OutputT>>;\n }, // channel types\n Record<string, unknown>, // configurable types\n InputT, // input type\n EntrypointReturnT<OutputT> // output type\n >({\n name,\n checkpointer,\n nodes: {\n [name]: entrypointNode,\n },\n channels: {\n [START]: new EphemeralValue<InputT>(),\n [END]: new LastValue<EntrypointReturnT<OutputT>>(),\n [PREVIOUS]: new LastValue<EntrypointFinalSaveT<OutputT>>(),\n },\n inputChannels: START,\n outputChannels: END,\n streamChannels: END,\n streamMode,\n store,\n cache,\n });\n} as EntrypointFunction;\n\n// documented by the EntrypointFunction interface\nentrypoint.final = function final<ValueT, SaveT>({\n value,\n save,\n}: {\n value?: ValueT;\n save?: SaveT;\n}): EntrypointFinal<ValueT, SaveT> {\n return { value, save, __lg_type: \"__pregel_final\" };\n};\n\n/**\n * A helper utility function for use with the functional API that returns the previous\n * state from the checkpoint from the last invocation of the current thread.\n *\n * This function allows workflows to access state that was saved in previous runs\n * using {@link entrypoint.final}.\n *\n * @typeParam StateT - The type of the state that was previously saved\n * @returns The previous saved state from the last invocation of the current thread\n *\n * @example\n * ```typescript\n * const previousState = getPreviousState<{ counter: number }>();\n * const newCount = (previousState?.counter ?? 0) + 1;\n * ```\n * @category Functional API\n */\nexport function getPreviousState<StateT>(): StateT {\n const config: LangGraphRunnableConfig =\n AsyncLocalStorageProviderSingleton.getRunnableConfig();\n return config.configurable?.[CONFIG_KEY_PREVIOUS_STATE] as StateT;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkHA,SAAgB,KACd,eACA,MACsC;CACtC,MAAM,UACJ,OAAO,kBAAkB,WACrB;EACE,MAAM;EACN,OAAO,KAAA;EACP,aAAa,KAAA;EACb,SAAS,KAAA;EACV,GACD;CAEN,MAAM,EAAE,MAAM,UAAU;CACxB,MAAM,UAAU,oBAAoB,QAAQ,QAAQ;AACpD,KAAI,yBAAyB,KAAK,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MAAM;EACjB,UAAU,CAAC,MAAM;EACjB;EACA,SAAS,CACP,IAAI,aACF,CACE;GAAE,SAAS;GAAK,OAAO;GAAa,QAAQ;GAAkB,EAC9D;GAAE,SAAS;GAAU,OAAO;GAAa,QAAQ;GAAgB,CAClE,EACD,CAAC,WAAW,CACb,CACF;EACF,CAAC;AAEF,QAAO,IAAI,OAUT;EACA;EACA;EACA,OAAO,GACJ,OAAO,gBACT;EACD,UAAU;IACP,QAAQ,IAAI,gBAAwB;IACpC,MAAM,IAAI,WAAuC;IACjD,WAAW,IAAI,WAA0C;GAC3D;EACD,eAAe;EACf,gBAAgB;EAChB,gBAAgB;EAChB;EACA;EACA;EACD,CAAC;;AAIJ,WAAW,QAAQ,SAAS,MAAqB,EAC/C,OACA,QAIiC;AACjC,QAAO;EAAE;EAAO;EAAM,WAAW;EAAkB;;;;;;;;;;;;;;;;;;;AAoBrD,SAAgB,mBAAmC;AAGjD,QADE,mCAAmC,mBAAmB,CAC1C,eAAe"}
|
package/dist/graph/graph.cjs
CHANGED
|
@@ -161,13 +161,17 @@ var Graph = class {
|
|
|
161
161
|
for (const node of Object.keys(this.nodes)) if (node !== start) allTargets.add(node);
|
|
162
162
|
}
|
|
163
163
|
for (const node of Object.values(this.nodes)) for (const target of node.ends ?? []) allTargets.add(target);
|
|
164
|
-
for (const node of Object.keys(this.nodes))
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
164
|
+
if (Object.values(this.nodes).some((node) => node.isErrorHandler)) for (const node of Object.keys(this.nodes)) allTargets.add(node);
|
|
165
|
+
for (const node of Object.keys(this.nodes)) {
|
|
166
|
+
if (this.nodes[node].isErrorHandler) continue;
|
|
167
|
+
if (!allTargets.has(node)) throw new require_errors.UnreachableNodeError([
|
|
168
|
+
`Node \`${node}\` is not reachable.`,
|
|
169
|
+
"",
|
|
170
|
+
"If you are returning Command objects from your node,",
|
|
171
|
+
"make sure you are passing names of potential destination nodes as an \"ends\" array",
|
|
172
|
+
"into \".addNode(..., { ends: [\"node1\", \"node2\"] })\"."
|
|
173
|
+
].join("\n"), { lc_error_code: "UNREACHABLE_NODE" });
|
|
174
|
+
}
|
|
171
175
|
for (const target of allTargets) if (target !== "__end__" && !(target in this.nodes)) throw new Error(`Found edge ending at unknown node \`${target}\``);
|
|
172
176
|
if (interrupt) {
|
|
173
177
|
for (const node of interrupt) if (!(node in this.nodes)) throw new Error(`Interrupt node \`${node}\` is not present`);
|
|
@@ -239,10 +243,16 @@ var CompiledGraph = class extends require_pregel_index.Pregel {
|
|
|
239
243
|
const endNodes = {};
|
|
240
244
|
let subgraphs = {};
|
|
241
245
|
if (xray) subgraphs = Object.fromEntries((await require_utils.gatherIterator(this.getSubgraphsAsync())).filter((x) => isCompiledGraph(x[1])));
|
|
246
|
+
const discoveredEdges = [];
|
|
242
247
|
function addEdge(start, end, label, conditional = false) {
|
|
243
248
|
if (end === "__end__" && endNodes["__end__"] === void 0) endNodes[require_constants.END] = graph.addNode({ schema: zod_v4.z.any() }, require_constants.END);
|
|
244
249
|
if (startNodes[start] === void 0) return;
|
|
245
250
|
if (endNodes[end] === void 0) throw new Error(`End node ${end} not found!`);
|
|
251
|
+
discoveredEdges.push({
|
|
252
|
+
src: start,
|
|
253
|
+
dest: end,
|
|
254
|
+
conditional
|
|
255
|
+
});
|
|
246
256
|
return graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : void 0, conditional);
|
|
247
257
|
}
|
|
248
258
|
for (const [key, nodeSpec] of Object.entries(this.builder.nodes)) {
|
|
@@ -315,6 +325,7 @@ var CompiledGraph = class extends require_pregel_index.Pregel {
|
|
|
315
325
|
}
|
|
316
326
|
}
|
|
317
327
|
for (const [key, node] of Object.entries(this.builder.nodes)) if (node.ends !== void 0) for (const end of node.ends) addEdge(_escapeMermaidKeywords(key), _escapeMermaidKeywords(end), void 0, true);
|
|
328
|
+
addImplicitTerminalEndEdges(this.builder.nodes, discoveredEdges, addEdge);
|
|
318
329
|
return graph;
|
|
319
330
|
}
|
|
320
331
|
/**
|
|
@@ -329,8 +340,16 @@ var CompiledGraph = class extends require_pregel_index.Pregel {
|
|
|
329
340
|
const endNodes = {};
|
|
330
341
|
let subgraphs = {};
|
|
331
342
|
if (xray) subgraphs = Object.fromEntries(require_utils.gatherIteratorSync(this.getSubgraphs()).filter((x) => isCompiledGraph(x[1])));
|
|
343
|
+
const discoveredEdges = [];
|
|
332
344
|
function addEdge(start, end, label, conditional = false) {
|
|
333
345
|
if (end === "__end__" && endNodes["__end__"] === void 0) endNodes[require_constants.END] = graph.addNode({ schema: zod_v4.z.any() }, require_constants.END);
|
|
346
|
+
if (startNodes[start] === void 0) return;
|
|
347
|
+
if (endNodes[end] === void 0) throw new Error(`End node ${end} not found!`);
|
|
348
|
+
discoveredEdges.push({
|
|
349
|
+
src: start,
|
|
350
|
+
dest: end,
|
|
351
|
+
conditional
|
|
352
|
+
});
|
|
334
353
|
return graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : void 0, conditional);
|
|
335
354
|
}
|
|
336
355
|
for (const [key, nodeSpec] of Object.entries(this.builder.nodes)) {
|
|
@@ -402,6 +421,8 @@ var CompiledGraph = class extends require_pregel_index.Pregel {
|
|
|
402
421
|
for (const [label, end] of Object.entries(ends)) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end), label, true);
|
|
403
422
|
}
|
|
404
423
|
}
|
|
424
|
+
for (const [key, node] of Object.entries(this.builder.nodes)) if (node.ends !== void 0) for (const end of node.ends) addEdge(_escapeMermaidKeywords(key), _escapeMermaidKeywords(end), void 0, true);
|
|
425
|
+
addImplicitTerminalEndEdges(this.builder.nodes, discoveredEdges, addEdge);
|
|
405
426
|
return graph;
|
|
406
427
|
}
|
|
407
428
|
};
|
|
@@ -412,6 +433,22 @@ function _escapeMermaidKeywords(key) {
|
|
|
412
433
|
if (key === "subgraph") return `"${key}"`;
|
|
413
434
|
return key;
|
|
414
435
|
}
|
|
436
|
+
/**
|
|
437
|
+
* Add implicit edges to END for terminal nodes (targets with no outgoing edges).
|
|
438
|
+
*
|
|
439
|
+
* Only nodes reached by a non-conditional edge are considered, so
|
|
440
|
+
* conditional-branch targets are not treated as implicit sinks.
|
|
441
|
+
*/
|
|
442
|
+
function addImplicitTerminalEndEdges(nodes, discovered, addEdge) {
|
|
443
|
+
const sources = new Set(discovered.map((e) => e.src));
|
|
444
|
+
const nonConditionalDestinations = [...new Set(discovered.filter((e) => !e.conditional && e.dest !== "__end__").map((e) => e.dest))].sort();
|
|
445
|
+
for (const displayDest of nonConditionalDestinations) {
|
|
446
|
+
if (sources.has(displayDest)) continue;
|
|
447
|
+
const rawKey = Object.keys(nodes).find((k) => _escapeMermaidKeywords(k) === displayDest);
|
|
448
|
+
if (rawKey !== void 0 && nodes[rawKey]?.isErrorHandler) continue;
|
|
449
|
+
addEdge(displayDest, require_constants.END);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
415
452
|
//#endregion
|
|
416
453
|
exports.Branch = Branch;
|
|
417
454
|
exports.CompiledGraph = CompiledGraph;
|