@langchain/langgraph 1.0.12 → 1.0.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/channels/any_value.cjs +46 -0
- package/dist/channels/any_value.cjs.map +1 -0
- package/dist/channels/any_value.d.cts +23 -0
- package/dist/channels/any_value.d.cts.map +1 -0
- package/dist/channels/any_value.d.ts +23 -0
- package/dist/channels/any_value.d.ts.map +1 -0
- package/dist/channels/any_value.js +46 -0
- package/dist/channels/any_value.js.map +1 -0
- package/dist/channels/base.cjs +101 -0
- package/dist/channels/base.cjs.map +1 -0
- package/dist/channels/base.d.cts +79 -0
- package/dist/channels/base.d.cts.map +1 -0
- package/dist/channels/base.d.ts +79 -0
- package/dist/channels/base.d.ts.map +1 -0
- package/dist/channels/base.js +97 -0
- package/dist/channels/base.js.map +1 -0
- package/dist/channels/binop.cjs +49 -0
- package/dist/channels/binop.cjs.map +1 -0
- package/dist/channels/binop.d.cts +22 -0
- package/dist/channels/binop.d.cts.map +1 -0
- package/dist/channels/binop.d.ts +22 -0
- package/dist/channels/binop.d.ts.map +1 -0
- package/dist/channels/binop.js +49 -0
- package/dist/channels/binop.js.map +1 -0
- package/dist/channels/dynamic_barrier_value.cjs +75 -0
- package/dist/channels/dynamic_barrier_value.cjs.map +1 -0
- package/dist/channels/dynamic_barrier_value.d.cts +40 -0
- package/dist/channels/dynamic_barrier_value.d.cts.map +1 -0
- package/dist/channels/dynamic_barrier_value.d.ts +40 -0
- package/dist/channels/dynamic_barrier_value.d.ts.map +1 -0
- package/dist/channels/dynamic_barrier_value.js +75 -0
- package/dist/channels/dynamic_barrier_value.js.map +1 -0
- package/dist/channels/ephemeral_value.cjs +46 -0
- package/dist/channels/ephemeral_value.cjs.map +1 -0
- package/dist/channels/ephemeral_value.d.cts +21 -0
- package/dist/channels/ephemeral_value.d.cts.map +1 -0
- package/dist/channels/ephemeral_value.d.ts +21 -0
- package/dist/channels/ephemeral_value.d.ts.map +1 -0
- package/dist/channels/ephemeral_value.js +46 -0
- package/dist/channels/ephemeral_value.js.map +1 -0
- package/dist/channels/index.cjs +21 -0
- package/dist/channels/index.d.cts +9 -0
- package/dist/channels/index.d.ts +9 -0
- package/dist/channels/index.js +10 -0
- package/dist/channels/last_value.cjs +98 -0
- package/dist/channels/last_value.cjs.map +1 -0
- package/dist/channels/last_value.d.cts +42 -0
- package/dist/channels/last_value.d.cts.map +1 -0
- package/dist/channels/last_value.d.ts +42 -0
- package/dist/channels/last_value.d.ts.map +1 -0
- package/dist/channels/last_value.js +97 -0
- package/dist/channels/last_value.js.map +1 -0
- package/dist/channels/named_barrier_value.cjs +116 -0
- package/dist/channels/named_barrier_value.cjs.map +1 -0
- package/dist/channels/named_barrier_value.d.cts +44 -0
- package/dist/channels/named_barrier_value.d.cts.map +1 -0
- package/dist/channels/named_barrier_value.d.ts +44 -0
- package/dist/channels/named_barrier_value.d.ts.map +1 -0
- package/dist/channels/named_barrier_value.js +114 -0
- package/dist/channels/named_barrier_value.js.map +1 -0
- package/dist/channels/topic.cjs +65 -0
- package/dist/channels/topic.cjs.map +1 -0
- package/dist/channels/topic.d.cts +32 -0
- package/dist/channels/topic.d.cts.map +1 -0
- package/dist/channels/topic.d.ts +32 -0
- package/dist/channels/topic.d.ts.map +1 -0
- package/dist/channels/topic.js +65 -0
- package/dist/channels/topic.js.map +1 -0
- package/dist/constants.cjs +406 -0
- package/dist/constants.cjs.map +1 -0
- package/dist/constants.d.cts +281 -0
- package/dist/constants.d.cts.map +1 -0
- package/dist/constants.d.ts +281 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +362 -0
- package/dist/constants.js.map +1 -0
- package/dist/errors.cjs +163 -0
- package/dist/errors.cjs.map +1 -0
- package/dist/errors.d.cts +77 -0
- package/dist/errors.d.cts.map +1 -0
- package/dist/errors.d.ts +77 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +146 -0
- package/dist/errors.js.map +1 -0
- package/dist/func/index.cjs +299 -0
- package/dist/func/index.cjs.map +1 -0
- package/dist/func/index.d.cts +288 -0
- package/dist/func/index.d.cts.map +1 -0
- package/dist/func/index.d.ts +288 -0
- package/dist/func/index.d.ts.map +1 -0
- package/dist/func/index.js +297 -0
- package/dist/func/index.js.map +1 -0
- package/dist/func/types.d.cts +62 -0
- package/dist/func/types.d.cts.map +1 -0
- package/dist/func/types.d.ts +62 -0
- package/dist/func/types.d.ts.map +1 -0
- package/dist/graph/annotation.cjs +101 -0
- package/dist/graph/annotation.cjs.map +1 -0
- package/dist/graph/annotation.d.cts +116 -0
- package/dist/graph/annotation.d.cts.map +1 -0
- package/dist/graph/annotation.d.ts +116 -0
- package/dist/graph/annotation.d.ts.map +1 -0
- package/dist/graph/annotation.js +99 -0
- package/dist/graph/annotation.js.map +1 -0
- package/dist/graph/graph.cjs +420 -0
- package/dist/graph/graph.cjs.map +1 -0
- package/dist/graph/graph.d.cts +108 -0
- package/dist/graph/graph.d.cts.map +1 -0
- package/dist/graph/graph.d.ts +108 -0
- package/dist/graph/graph.d.ts.map +1 -0
- package/dist/graph/graph.js +418 -0
- package/dist/graph/graph.js.map +1 -0
- package/dist/graph/index.cjs +5 -0
- package/dist/graph/index.js +7 -0
- package/dist/graph/message.cjs +97 -0
- package/dist/graph/message.cjs.map +1 -0
- package/dist/graph/message.d.cts +40 -0
- package/dist/graph/message.d.cts.map +1 -0
- package/dist/graph/message.d.ts +40 -0
- package/dist/graph/message.d.ts.map +1 -0
- package/dist/graph/message.js +94 -0
- package/dist/graph/message.js.map +1 -0
- package/dist/graph/messages_annotation.cjs +109 -0
- package/dist/graph/messages_annotation.cjs.map +1 -0
- package/dist/graph/messages_annotation.d.cts +112 -0
- package/dist/graph/messages_annotation.d.cts.map +1 -0
- package/dist/graph/messages_annotation.d.ts +112 -0
- package/dist/graph/messages_annotation.d.ts.map +1 -0
- package/dist/graph/messages_annotation.js +107 -0
- package/dist/graph/messages_annotation.js.map +1 -0
- package/dist/graph/state.cjs +494 -0
- package/dist/graph/state.cjs.map +1 -0
- package/dist/graph/state.d.cts +229 -0
- package/dist/graph/state.d.cts.map +1 -0
- package/dist/graph/state.d.ts +229 -0
- package/dist/graph/state.d.ts.map +1 -0
- package/dist/graph/state.js +493 -0
- package/dist/graph/state.js.map +1 -0
- package/dist/graph/zod/index.cjs +10 -0
- package/dist/graph/zod/index.d.cts +3 -0
- package/dist/graph/zod/index.d.ts +3 -0
- package/dist/graph/zod/index.js +5 -0
- package/dist/graph/zod/meta.cjs +144 -0
- package/dist/graph/zod/meta.cjs.map +1 -0
- package/dist/graph/zod/meta.d.cts +115 -0
- package/dist/graph/zod/meta.d.cts.map +1 -0
- package/dist/graph/zod/meta.d.ts +115 -0
- package/dist/graph/zod/meta.d.ts.map +1 -0
- package/dist/graph/zod/meta.js +141 -0
- package/dist/graph/zod/meta.js.map +1 -0
- package/dist/graph/zod/plugin.cjs +39 -0
- package/dist/graph/zod/plugin.cjs.map +1 -0
- package/dist/graph/zod/plugin.js +40 -0
- package/dist/graph/zod/plugin.js.map +1 -0
- package/dist/graph/zod/schema.cjs +98 -0
- package/dist/graph/zod/schema.cjs.map +1 -0
- package/dist/graph/zod/schema.d.cts +38 -0
- package/dist/graph/zod/schema.d.cts.map +1 -0
- package/dist/graph/zod/schema.d.ts +38 -0
- package/dist/graph/zod/schema.d.ts.map +1 -0
- package/dist/graph/zod/schema.js +94 -0
- package/dist/graph/zod/schema.js.map +1 -0
- package/dist/graph/zod/zod-registry.cjs +42 -0
- package/dist/graph/zod/zod-registry.cjs.map +1 -0
- package/dist/graph/zod/zod-registry.d.cts +49 -0
- package/dist/graph/zod/zod-registry.d.cts.map +1 -0
- package/dist/graph/zod/zod-registry.d.ts +49 -0
- package/dist/graph/zod/zod-registry.d.ts.map +1 -0
- package/dist/graph/zod/zod-registry.js +41 -0
- package/dist/graph/zod/zod-registry.js.map +1 -0
- package/dist/hash.cjs +265 -0
- package/dist/hash.cjs.map +1 -0
- package/dist/hash.js +263 -0
- package/dist/hash.js.map +1 -0
- package/dist/index.cjs +111 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +26 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +22 -0
- package/dist/index.js.map +1 -0
- package/dist/interrupt.cjs +79 -0
- package/dist/interrupt.cjs.map +1 -0
- package/dist/interrupt.d.cts +55 -0
- package/dist/interrupt.d.cts.map +1 -0
- package/dist/interrupt.d.ts +55 -0
- package/dist/interrupt.d.ts.map +1 -0
- package/dist/interrupt.js +79 -0
- package/dist/interrupt.js.map +1 -0
- package/dist/prebuilt/agentName.cjs +148 -0
- package/dist/prebuilt/agentName.cjs.map +1 -0
- package/dist/prebuilt/agentName.d.cts +42 -0
- package/dist/prebuilt/agentName.d.cts.map +1 -0
- package/dist/prebuilt/agentName.d.ts +42 -0
- package/dist/prebuilt/agentName.d.ts.map +1 -0
- package/dist/prebuilt/agentName.js +148 -0
- package/dist/prebuilt/agentName.js.map +1 -0
- package/dist/prebuilt/agent_executor.cjs +41 -0
- package/dist/prebuilt/agent_executor.cjs.map +1 -0
- package/dist/prebuilt/agent_executor.d.cts +58 -0
- package/dist/prebuilt/agent_executor.d.cts.map +1 -0
- package/dist/prebuilt/agent_executor.d.ts +58 -0
- package/dist/prebuilt/agent_executor.d.ts.map +1 -0
- package/dist/prebuilt/agent_executor.js +41 -0
- package/dist/prebuilt/agent_executor.js.map +1 -0
- package/dist/prebuilt/chat_agent_executor.cjs +62 -0
- package/dist/prebuilt/chat_agent_executor.cjs.map +1 -0
- package/dist/prebuilt/chat_agent_executor.d.cts +23 -0
- package/dist/prebuilt/chat_agent_executor.d.cts.map +1 -0
- package/dist/prebuilt/chat_agent_executor.d.ts +23 -0
- package/dist/prebuilt/chat_agent_executor.d.ts.map +1 -0
- package/dist/prebuilt/chat_agent_executor.js +62 -0
- package/dist/prebuilt/chat_agent_executor.js.map +1 -0
- package/dist/prebuilt/index.cjs +15 -0
- package/dist/prebuilt/index.d.cts +8 -0
- package/dist/prebuilt/index.d.ts +8 -0
- package/dist/prebuilt/index.js +8 -0
- package/dist/prebuilt/interrupt.d.cts +60 -0
- package/dist/prebuilt/interrupt.d.cts.map +1 -0
- package/dist/prebuilt/interrupt.d.ts +60 -0
- package/dist/prebuilt/interrupt.d.ts.map +1 -0
- package/dist/prebuilt/react_agent_executor.cjs +339 -0
- package/dist/prebuilt/react_agent_executor.cjs.map +1 -0
- package/dist/prebuilt/react_agent_executor.d.cts +211 -0
- package/dist/prebuilt/react_agent_executor.d.cts.map +1 -0
- package/dist/prebuilt/react_agent_executor.d.ts +211 -0
- package/dist/prebuilt/react_agent_executor.d.ts.map +1 -0
- package/dist/prebuilt/react_agent_executor.js +338 -0
- package/dist/prebuilt/react_agent_executor.js.map +1 -0
- package/dist/prebuilt/tool_executor.cjs +43 -0
- package/dist/prebuilt/tool_executor.cjs.map +1 -0
- package/dist/prebuilt/tool_executor.d.cts +40 -0
- package/dist/prebuilt/tool_executor.d.cts.map +1 -0
- package/dist/prebuilt/tool_executor.d.ts +40 -0
- package/dist/prebuilt/tool_executor.d.ts.map +1 -0
- package/dist/prebuilt/tool_executor.js +43 -0
- package/dist/prebuilt/tool_executor.js.map +1 -0
- package/dist/prebuilt/tool_node.cjs +247 -0
- package/dist/prebuilt/tool_node.cjs.map +1 -0
- package/dist/prebuilt/tool_node.d.cts +180 -0
- package/dist/prebuilt/tool_node.d.cts.map +1 -0
- package/dist/prebuilt/tool_node.d.ts +180 -0
- package/dist/prebuilt/tool_node.d.ts.map +1 -0
- package/dist/prebuilt/tool_node.js +246 -0
- package/dist/prebuilt/tool_node.js.map +1 -0
- package/dist/pregel/algo.cjs +565 -0
- package/dist/pregel/algo.cjs.map +1 -0
- package/dist/pregel/algo.d.cts +13 -0
- package/dist/pregel/algo.d.cts.map +1 -0
- package/dist/pregel/algo.d.ts +13 -0
- package/dist/pregel/algo.d.ts.map +1 -0
- package/dist/pregel/algo.js +560 -0
- package/dist/pregel/algo.js.map +1 -0
- package/dist/pregel/call.cjs +50 -0
- package/dist/pregel/call.cjs.map +1 -0
- package/dist/pregel/call.js +48 -0
- package/dist/pregel/call.js.map +1 -0
- package/dist/pregel/debug.cjs +172 -0
- package/dist/pregel/debug.cjs.map +1 -0
- package/dist/pregel/debug.js +166 -0
- package/dist/pregel/debug.js.map +1 -0
- package/dist/pregel/index.cjs +1163 -0
- package/dist/pregel/index.cjs.map +1 -0
- package/dist/pregel/index.d.cts +498 -0
- package/dist/pregel/index.d.cts.map +1 -0
- package/dist/pregel/index.d.ts +498 -0
- package/dist/pregel/index.d.ts.map +1 -0
- package/dist/pregel/index.js +1162 -0
- package/dist/pregel/index.js.map +1 -0
- package/dist/pregel/io.cjs +140 -0
- package/dist/pregel/io.cjs.map +1 -0
- package/dist/pregel/io.js +135 -0
- package/dist/pregel/io.js.map +1 -0
- package/dist/pregel/loop.cjs +545 -0
- package/dist/pregel/loop.cjs.map +1 -0
- package/dist/pregel/loop.js +545 -0
- package/dist/pregel/loop.js.map +1 -0
- package/dist/pregel/messages.cjs +107 -0
- package/dist/pregel/messages.cjs.map +1 -0
- package/dist/pregel/messages.js +107 -0
- package/dist/pregel/messages.js.map +1 -0
- package/dist/pregel/read.cjs +151 -0
- package/dist/pregel/read.cjs.map +1 -0
- package/dist/pregel/read.d.cts +45 -0
- package/dist/pregel/read.d.cts.map +1 -0
- package/dist/pregel/read.d.ts +45 -0
- package/dist/pregel/read.d.ts.map +1 -0
- package/dist/pregel/read.js +150 -0
- package/dist/pregel/read.js.map +1 -0
- package/dist/pregel/remote.cjs +341 -0
- package/dist/pregel/remote.cjs.map +1 -0
- package/dist/pregel/remote.d.cts +118 -0
- package/dist/pregel/remote.d.cts.map +1 -0
- package/dist/pregel/remote.d.ts +118 -0
- package/dist/pregel/remote.d.ts.map +1 -0
- package/dist/pregel/remote.js +341 -0
- package/dist/pregel/remote.js.map +1 -0
- package/dist/pregel/retry.cjs +91 -0
- package/dist/pregel/retry.cjs.map +1 -0
- package/dist/pregel/retry.js +91 -0
- package/dist/pregel/retry.js.map +1 -0
- package/dist/pregel/runnable_types.d.cts +43 -0
- package/dist/pregel/runnable_types.d.cts.map +1 -0
- package/dist/pregel/runnable_types.d.ts +43 -0
- package/dist/pregel/runnable_types.d.ts.map +1 -0
- package/dist/pregel/runner.cjs +228 -0
- package/dist/pregel/runner.cjs.map +1 -0
- package/dist/pregel/runner.js +228 -0
- package/dist/pregel/runner.js.map +1 -0
- package/dist/pregel/stream.cjs +197 -0
- package/dist/pregel/stream.cjs.map +1 -0
- package/dist/pregel/stream.js +195 -0
- package/dist/pregel/stream.js.map +1 -0
- package/dist/pregel/types.cjs +27 -0
- package/dist/pregel/types.cjs.map +1 -0
- package/dist/pregel/types.d.cts +440 -0
- package/dist/pregel/types.d.cts.map +1 -0
- package/dist/pregel/types.d.ts +440 -0
- package/dist/pregel/types.d.ts.map +1 -0
- package/dist/pregel/types.js +25 -0
- package/dist/pregel/types.js.map +1 -0
- package/dist/pregel/utils/config.cjs +121 -0
- package/dist/pregel/utils/config.cjs.map +1 -0
- package/dist/pregel/utils/config.d.cts +36 -0
- package/dist/pregel/utils/config.d.cts.map +1 -0
- package/dist/pregel/utils/config.d.ts +36 -0
- package/dist/pregel/utils/config.d.ts.map +1 -0
- package/dist/pregel/utils/config.js +115 -0
- package/dist/pregel/utils/config.js.map +1 -0
- package/dist/pregel/utils/index.cjs +102 -0
- package/dist/pregel/utils/index.cjs.map +1 -0
- package/dist/pregel/utils/index.d.cts +51 -0
- package/dist/pregel/utils/index.d.cts.map +1 -0
- package/dist/pregel/utils/index.d.ts +51 -0
- package/dist/pregel/utils/index.d.ts.map +1 -0
- package/dist/pregel/utils/index.js +96 -0
- package/dist/pregel/utils/index.js.map +1 -0
- package/dist/pregel/utils/subgraph.cjs +18 -0
- package/dist/pregel/utils/subgraph.cjs.map +1 -0
- package/dist/pregel/utils/subgraph.js +16 -0
- package/dist/pregel/utils/subgraph.js.map +1 -0
- package/dist/pregel/validate.cjs +45 -0
- package/dist/pregel/validate.cjs.map +1 -0
- package/dist/pregel/validate.js +44 -0
- package/dist/pregel/validate.js.map +1 -0
- package/dist/pregel/write.cjs +96 -0
- package/dist/pregel/write.cjs.map +1 -0
- package/dist/pregel/write.d.cts +31 -0
- package/dist/pregel/write.d.cts.map +1 -0
- package/dist/pregel/write.d.ts +31 -0
- package/dist/pregel/write.d.ts.map +1 -0
- package/dist/pregel/write.js +95 -0
- package/dist/pregel/write.js.map +1 -0
- package/dist/remote.cjs +3 -0
- package/dist/remote.d.cts +2 -0
- package/dist/remote.d.ts +2 -0
- package/dist/remote.js +3 -0
- package/dist/setup/async_local_storage.cjs +11 -0
- package/dist/setup/async_local_storage.cjs.map +1 -0
- package/dist/setup/async_local_storage.js +11 -0
- package/dist/setup/async_local_storage.js.map +1 -0
- package/dist/utils.cjs +86 -0
- package/dist/utils.cjs.map +1 -0
- package/dist/utils.d.cts +25 -0
- package/dist/utils.d.cts.map +1 -0
- package/dist/utils.d.ts +25 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +80 -0
- package/dist/utils.js.map +1 -0
- package/dist/web.cjs +95 -0
- package/dist/web.d.cts +23 -0
- package/dist/web.d.ts +23 -0
- package/dist/web.js +15 -0
- package/dist/writer.cjs +14 -0
- package/dist/writer.cjs.map +1 -0
- package/dist/writer.d.cts +6 -0
- package/dist/writer.d.cts.map +1 -0
- package/dist/writer.d.ts +6 -0
- package/dist/writer.d.ts.map +1 -0
- package/dist/writer.js +14 -0
- package/dist/writer.js.map +1 -0
- package/package.json +2 -2
|
@@ -0,0 +1,1162 @@
|
|
|
1
|
+
import { GraphRecursionError, GraphValueError, InvalidUpdateError } from "../errors.js";
|
|
2
|
+
import { createCheckpoint, emptyChannels, getOnlyChannels } from "../channels/base.js";
|
|
3
|
+
import { CHECKPOINT_NAMESPACE_END, CHECKPOINT_NAMESPACE_SEPARATOR, CONFIG_KEY_CHECKPOINTER, CONFIG_KEY_CHECKPOINT_NS, CONFIG_KEY_DURABILITY, CONFIG_KEY_NODE_FINISHED, CONFIG_KEY_READ, CONFIG_KEY_SEND, CONFIG_KEY_STREAM, CONFIG_KEY_TASK_ID, COPY, END, ERROR, INPUT, INTERRUPT, NULL_TASK_ID, PUSH, TASKS, isInterrupted } from "../constants.js";
|
|
4
|
+
import { ensureLangGraphConfig, getConfig, recastCheckpointNamespace } from "./utils/config.js";
|
|
5
|
+
import { gatherIterator, patchConfigurable } from "../utils.js";
|
|
6
|
+
import { ChannelWrite, PASSTHROUGH } from "./write.js";
|
|
7
|
+
import { PregelNode } from "./read.js";
|
|
8
|
+
import { mapInput, readChannels } from "./io.js";
|
|
9
|
+
import { _coerceToDict, combineAbortSignals, combineCallbacks, getNewChannelVersions, patchCheckpointMap } from "./utils/index.js";
|
|
10
|
+
import { _applyWrites, _localRead, _prepareNextTasks } from "./algo.js";
|
|
11
|
+
import { findSubgraphPregel } from "./utils/subgraph.js";
|
|
12
|
+
import { printStepCheckpoint, printStepTasks, printStepWrites, tasksWithWrites } from "./debug.js";
|
|
13
|
+
import { IterableReadableStreamWithAbortSignal, IterableReadableWritableStream, toEventStream } from "./stream.js";
|
|
14
|
+
import { PregelLoop } from "./loop.js";
|
|
15
|
+
import { StreamMessagesHandler } from "./messages.js";
|
|
16
|
+
import { PregelRunner } from "./runner.js";
|
|
17
|
+
import { validateGraph, validateKeys } from "./validate.js";
|
|
18
|
+
import { Topic } from "../channels/topic.js";
|
|
19
|
+
import { interrupt } from "../interrupt.js";
|
|
20
|
+
import { SCHEDULED, compareChannelVersions, copyCheckpoint, emptyCheckpoint, uuid5 } from "@langchain/langgraph-checkpoint";
|
|
21
|
+
import { Runnable, RunnableSequence, _coerceToRunnable, getCallbackManagerForConfig, mergeConfigs, patchConfig } from "@langchain/core/runnables";
|
|
22
|
+
|
|
23
|
+
//#region src/pregel/index.ts
|
|
24
|
+
/**
|
|
25
|
+
* Utility class for working with channels in the Pregel system.
|
|
26
|
+
* Provides static methods for subscribing to channels and writing to them.
|
|
27
|
+
*
|
|
28
|
+
* Channels are the communication pathways between nodes in a Pregel graph.
|
|
29
|
+
* They enable message passing and state updates between different parts of the graph.
|
|
30
|
+
*/
|
|
31
|
+
var Channel = class {
|
|
32
|
+
static subscribeTo(channels, options) {
|
|
33
|
+
const { key, tags } = {
|
|
34
|
+
key: void 0,
|
|
35
|
+
tags: void 0,
|
|
36
|
+
...options ?? {}
|
|
37
|
+
};
|
|
38
|
+
if (Array.isArray(channels) && key !== void 0) throw new Error("Can't specify a key when subscribing to multiple channels");
|
|
39
|
+
let channelMappingOrArray;
|
|
40
|
+
if (typeof channels === "string") if (key) channelMappingOrArray = { [key]: channels };
|
|
41
|
+
else channelMappingOrArray = [channels];
|
|
42
|
+
else channelMappingOrArray = Object.fromEntries(channels.map((chan) => [chan, chan]));
|
|
43
|
+
return new PregelNode({
|
|
44
|
+
channels: channelMappingOrArray,
|
|
45
|
+
triggers: Array.isArray(channels) ? channels : [channels],
|
|
46
|
+
tags
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Creates a ChannelWrite that specifies how to write values to channels.
|
|
51
|
+
* This is used to define how nodes send output to channels.
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```typescript
|
|
55
|
+
* // Write to multiple channels
|
|
56
|
+
* const write = Channel.writeTo(["output", "state"]);
|
|
57
|
+
*
|
|
58
|
+
* // Write with specific values
|
|
59
|
+
* const write = Channel.writeTo(["output"], {
|
|
60
|
+
* state: "completed",
|
|
61
|
+
* result: calculateResult()
|
|
62
|
+
* });
|
|
63
|
+
*
|
|
64
|
+
* // Write with a transformation function
|
|
65
|
+
* const write = Channel.writeTo(["output"], {
|
|
66
|
+
* result: (x) => processResult(x)
|
|
67
|
+
* });
|
|
68
|
+
* ```
|
|
69
|
+
*
|
|
70
|
+
* @param channels - Array of channel names to write to
|
|
71
|
+
* @param writes - Optional map of channel names to values or transformations
|
|
72
|
+
* @returns A ChannelWrite object that can be used to write to the specified channels
|
|
73
|
+
*/
|
|
74
|
+
static writeTo(channels, writes) {
|
|
75
|
+
const channelWriteEntries = [];
|
|
76
|
+
for (const channel of channels) channelWriteEntries.push({
|
|
77
|
+
channel,
|
|
78
|
+
value: PASSTHROUGH,
|
|
79
|
+
skipNone: false
|
|
80
|
+
});
|
|
81
|
+
for (const [key, value] of Object.entries(writes ?? {})) if (Runnable.isRunnable(value) || typeof value === "function") channelWriteEntries.push({
|
|
82
|
+
channel: key,
|
|
83
|
+
value: PASSTHROUGH,
|
|
84
|
+
skipNone: true,
|
|
85
|
+
mapper: _coerceToRunnable(value)
|
|
86
|
+
});
|
|
87
|
+
else channelWriteEntries.push({
|
|
88
|
+
channel: key,
|
|
89
|
+
value,
|
|
90
|
+
skipNone: false
|
|
91
|
+
});
|
|
92
|
+
return new ChannelWrite(channelWriteEntries);
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
var PartialRunnable = class extends Runnable {
|
|
96
|
+
lc_namespace = ["langgraph", "pregel"];
|
|
97
|
+
invoke(_input, _options) {
|
|
98
|
+
throw new Error("Not implemented");
|
|
99
|
+
}
|
|
100
|
+
withConfig(_config) {
|
|
101
|
+
return super.withConfig(_config);
|
|
102
|
+
}
|
|
103
|
+
stream(input, options) {
|
|
104
|
+
return super.stream(input, options);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
/**
|
|
108
|
+
* The Pregel class is the core runtime engine of LangGraph, implementing a message-passing graph computation model
|
|
109
|
+
* inspired by [Google's Pregel system](https://research.google/pubs/pregel-a-system-for-large-scale-graph-processing/).
|
|
110
|
+
* It provides the foundation for building reliable, controllable agent workflows that can evolve state over time.
|
|
111
|
+
*
|
|
112
|
+
* Key features:
|
|
113
|
+
* - Message passing between nodes in discrete "supersteps"
|
|
114
|
+
* - Built-in persistence layer through checkpointers
|
|
115
|
+
* - First-class streaming support for values, updates, and events
|
|
116
|
+
* - Human-in-the-loop capabilities via interrupts
|
|
117
|
+
* - Support for parallel node execution within supersteps
|
|
118
|
+
*
|
|
119
|
+
* The Pregel class is not intended to be instantiated directly by consumers. Instead, use the following higher-level APIs:
|
|
120
|
+
* - {@link StateGraph}: The main graph class for building agent workflows
|
|
121
|
+
* - Compiling a {@link StateGraph} will return a {@link CompiledGraph} instance, which extends `Pregel`
|
|
122
|
+
* - Functional API: A declarative approach using tasks and entrypoints
|
|
123
|
+
* - A `Pregel` instance is returned by the {@link entrypoint} function
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* ```typescript
|
|
127
|
+
* // Using StateGraph API
|
|
128
|
+
* const graph = new StateGraph(annotation)
|
|
129
|
+
* .addNode("nodeA", myNodeFunction)
|
|
130
|
+
* .addEdge("nodeA", "nodeB")
|
|
131
|
+
* .compile();
|
|
132
|
+
*
|
|
133
|
+
* // The compiled graph is a Pregel instance
|
|
134
|
+
* const result = await graph.invoke(input);
|
|
135
|
+
* ```
|
|
136
|
+
*
|
|
137
|
+
* @example
|
|
138
|
+
* ```typescript
|
|
139
|
+
* // Using Functional API
|
|
140
|
+
* import { task, entrypoint } from "@langchain/langgraph";
|
|
141
|
+
* import { MemorySaver } from "@langchain/langgraph-checkpoint";
|
|
142
|
+
*
|
|
143
|
+
* // Define tasks that can be composed
|
|
144
|
+
* const addOne = task("add", async (x: number) => x + 1);
|
|
145
|
+
*
|
|
146
|
+
* // Create a workflow using the entrypoint function
|
|
147
|
+
* const workflow = entrypoint({
|
|
148
|
+
* name: "workflow",
|
|
149
|
+
* checkpointer: new MemorySaver()
|
|
150
|
+
* }, async (numbers: number[]) => {
|
|
151
|
+
* // Tasks can be run in parallel
|
|
152
|
+
* const results = await Promise.all(numbers.map(n => addOne(n)));
|
|
153
|
+
* return results;
|
|
154
|
+
* });
|
|
155
|
+
*
|
|
156
|
+
* // The workflow is a Pregel instance
|
|
157
|
+
* const result = await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4]
|
|
158
|
+
* ```
|
|
159
|
+
*
|
|
160
|
+
* @typeParam Nodes - Mapping of node names to their {@link PregelNode} implementations
|
|
161
|
+
* @typeParam Channels - Mapping of channel names to their {@link BaseChannel} or {@link ManagedValueSpec} implementations
|
|
162
|
+
* @typeParam ContextType - Type of context that can be passed to the graph
|
|
163
|
+
* @typeParam InputType - Type of input values accepted by the graph
|
|
164
|
+
* @typeParam OutputType - Type of output values produced by the graph
|
|
165
|
+
*/
|
|
166
|
+
var Pregel = class extends PartialRunnable {
|
|
167
|
+
/**
|
|
168
|
+
* Name of the class when serialized
|
|
169
|
+
* @internal
|
|
170
|
+
*/
|
|
171
|
+
static lc_name() {
|
|
172
|
+
return "LangGraph";
|
|
173
|
+
}
|
|
174
|
+
/** @internal LangChain namespace for serialization necessary because Pregel extends Runnable */
|
|
175
|
+
lc_namespace = ["langgraph", "pregel"];
|
|
176
|
+
/** @internal Flag indicating this is a Pregel instance - necessary for serialization */
|
|
177
|
+
lg_is_pregel = true;
|
|
178
|
+
/** The nodes in the graph, mapping node names to their PregelNode instances */
|
|
179
|
+
nodes;
|
|
180
|
+
/** The channels in the graph, mapping channel names to their BaseChannel or ManagedValueSpec instances */
|
|
181
|
+
channels;
|
|
182
|
+
/**
|
|
183
|
+
* The input channels for the graph. These channels receive the initial input when the graph is invoked.
|
|
184
|
+
* Can be a single channel key or an array of channel keys.
|
|
185
|
+
*/
|
|
186
|
+
inputChannels;
|
|
187
|
+
/**
|
|
188
|
+
* The output channels for the graph. These channels contain the final output when the graph completes.
|
|
189
|
+
* Can be a single channel key or an array of channel keys.
|
|
190
|
+
*/
|
|
191
|
+
outputChannels;
|
|
192
|
+
/** Whether to automatically validate the graph structure when it is compiled. Defaults to true. */
|
|
193
|
+
autoValidate = true;
|
|
194
|
+
/**
|
|
195
|
+
* The streaming modes enabled for this graph. Defaults to ["values"].
|
|
196
|
+
* Supported modes:
|
|
197
|
+
* - "values": Streams the full state after each step
|
|
198
|
+
* - "updates": Streams state updates after each step
|
|
199
|
+
* - "messages": Streams messages from within nodes
|
|
200
|
+
* - "custom": Streams custom events from within nodes
|
|
201
|
+
* - "debug": Streams events related to the execution of the graph - useful for tracing & debugging graph execution
|
|
202
|
+
*/
|
|
203
|
+
streamMode = ["values"];
|
|
204
|
+
/**
|
|
205
|
+
* Optional channels to stream. If not specified, all channels will be streamed.
|
|
206
|
+
* Can be a single channel key or an array of channel keys.
|
|
207
|
+
*/
|
|
208
|
+
streamChannels;
|
|
209
|
+
/**
|
|
210
|
+
* Optional array of node names or "all" to interrupt after executing these nodes.
|
|
211
|
+
* Used for implementing human-in-the-loop workflows.
|
|
212
|
+
*/
|
|
213
|
+
interruptAfter;
|
|
214
|
+
/**
|
|
215
|
+
* Optional array of node names or "all" to interrupt before executing these nodes.
|
|
216
|
+
* Used for implementing human-in-the-loop workflows.
|
|
217
|
+
*/
|
|
218
|
+
interruptBefore;
|
|
219
|
+
/** Optional timeout in milliseconds for the execution of each superstep */
|
|
220
|
+
stepTimeout;
|
|
221
|
+
/** Whether to enable debug logging. Defaults to false. */
|
|
222
|
+
debug = false;
|
|
223
|
+
/**
|
|
224
|
+
* Optional checkpointer for persisting graph state.
|
|
225
|
+
* When provided, saves a checkpoint of the graph state at every superstep.
|
|
226
|
+
* When false or undefined, checkpointing is disabled, and the graph will not be able to save or restore state.
|
|
227
|
+
*/
|
|
228
|
+
checkpointer;
|
|
229
|
+
/** Optional retry policy for handling failures in node execution */
|
|
230
|
+
retryPolicy;
|
|
231
|
+
/** The default configuration for graph execution, can be overridden on a per-invocation basis */
|
|
232
|
+
config;
|
|
233
|
+
/**
|
|
234
|
+
* Optional long-term memory store for the graph, allows for persistence & retrieval of data across threads
|
|
235
|
+
*/
|
|
236
|
+
store;
|
|
237
|
+
/**
|
|
238
|
+
* Optional cache for the graph, useful for caching tasks.
|
|
239
|
+
*/
|
|
240
|
+
cache;
|
|
241
|
+
/**
|
|
242
|
+
* Optional interrupt helper function.
|
|
243
|
+
* @internal
|
|
244
|
+
*/
|
|
245
|
+
userInterrupt;
|
|
246
|
+
/**
|
|
247
|
+
* The trigger to node mapping for the graph run.
|
|
248
|
+
* @internal
|
|
249
|
+
*/
|
|
250
|
+
triggerToNodes = {};
|
|
251
|
+
/**
|
|
252
|
+
* Constructor for Pregel - meant for internal use only.
|
|
253
|
+
*
|
|
254
|
+
* @internal
|
|
255
|
+
*/
|
|
256
|
+
constructor(fields) {
|
|
257
|
+
super(fields);
|
|
258
|
+
let { streamMode } = fields;
|
|
259
|
+
if (streamMode != null && !Array.isArray(streamMode)) streamMode = [streamMode];
|
|
260
|
+
this.nodes = fields.nodes;
|
|
261
|
+
this.channels = fields.channels;
|
|
262
|
+
if (TASKS in this.channels && "lc_graph_name" in this.channels[TASKS] && this.channels[TASKS].lc_graph_name !== "Topic") throw new Error(`Channel '${TASKS}' is reserved and cannot be used in the graph.`);
|
|
263
|
+
else this.channels[TASKS] = new Topic({ accumulate: false });
|
|
264
|
+
this.autoValidate = fields.autoValidate ?? this.autoValidate;
|
|
265
|
+
this.streamMode = streamMode ?? this.streamMode;
|
|
266
|
+
this.inputChannels = fields.inputChannels;
|
|
267
|
+
this.outputChannels = fields.outputChannels;
|
|
268
|
+
this.streamChannels = fields.streamChannels ?? this.streamChannels;
|
|
269
|
+
this.interruptAfter = fields.interruptAfter;
|
|
270
|
+
this.interruptBefore = fields.interruptBefore;
|
|
271
|
+
this.stepTimeout = fields.stepTimeout ?? this.stepTimeout;
|
|
272
|
+
this.debug = fields.debug ?? this.debug;
|
|
273
|
+
this.checkpointer = fields.checkpointer;
|
|
274
|
+
this.retryPolicy = fields.retryPolicy;
|
|
275
|
+
this.config = fields.config;
|
|
276
|
+
this.store = fields.store;
|
|
277
|
+
this.cache = fields.cache;
|
|
278
|
+
this.name = fields.name;
|
|
279
|
+
this.triggerToNodes = fields.triggerToNodes ?? this.triggerToNodes;
|
|
280
|
+
this.userInterrupt = fields.userInterrupt;
|
|
281
|
+
if (this.autoValidate) this.validate();
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Creates a new instance of the Pregel graph with updated configuration.
|
|
285
|
+
* This method follows the immutable pattern - instead of modifying the current instance,
|
|
286
|
+
* it returns a new instance with the merged configuration.
|
|
287
|
+
*
|
|
288
|
+
* @example
|
|
289
|
+
* ```typescript
|
|
290
|
+
* // Create a new instance with debug enabled
|
|
291
|
+
* const debugGraph = graph.withConfig({ debug: true });
|
|
292
|
+
*
|
|
293
|
+
* // Create a new instance with a specific thread ID
|
|
294
|
+
* const threadGraph = graph.withConfig({
|
|
295
|
+
* configurable: { thread_id: "123" }
|
|
296
|
+
* });
|
|
297
|
+
* ```
|
|
298
|
+
*
|
|
299
|
+
* @param config - The configuration to merge with the current configuration
|
|
300
|
+
* @returns A new Pregel instance with the merged configuration
|
|
301
|
+
*/
|
|
302
|
+
withConfig(config) {
|
|
303
|
+
const mergedConfig = mergeConfigs(this.config, config);
|
|
304
|
+
return new this.constructor({
|
|
305
|
+
...this,
|
|
306
|
+
config: mergedConfig
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Validates the graph structure to ensure it is well-formed.
|
|
311
|
+
* Checks for:
|
|
312
|
+
* - No orphaned nodes
|
|
313
|
+
* - Valid input/output channel configurations
|
|
314
|
+
* - Valid interrupt configurations
|
|
315
|
+
*
|
|
316
|
+
* @returns this - The Pregel instance for method chaining
|
|
317
|
+
* @throws {GraphValidationError} If the graph structure is invalid
|
|
318
|
+
*/
|
|
319
|
+
validate() {
|
|
320
|
+
validateGraph({
|
|
321
|
+
nodes: this.nodes,
|
|
322
|
+
channels: this.channels,
|
|
323
|
+
outputChannels: this.outputChannels,
|
|
324
|
+
inputChannels: this.inputChannels,
|
|
325
|
+
streamChannels: this.streamChannels,
|
|
326
|
+
interruptAfterNodes: this.interruptAfter,
|
|
327
|
+
interruptBeforeNodes: this.interruptBefore
|
|
328
|
+
});
|
|
329
|
+
for (const [name, node] of Object.entries(this.nodes)) for (const trigger of node.triggers) {
|
|
330
|
+
this.triggerToNodes[trigger] ??= [];
|
|
331
|
+
this.triggerToNodes[trigger].push(name);
|
|
332
|
+
}
|
|
333
|
+
return this;
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Gets a list of all channels that should be streamed.
|
|
337
|
+
* If streamChannels is specified, returns those channels.
|
|
338
|
+
* Otherwise, returns all channels in the graph.
|
|
339
|
+
*
|
|
340
|
+
* @returns Array of channel keys to stream
|
|
341
|
+
*/
|
|
342
|
+
get streamChannelsList() {
|
|
343
|
+
if (Array.isArray(this.streamChannels)) return this.streamChannels;
|
|
344
|
+
else if (this.streamChannels) return [this.streamChannels];
|
|
345
|
+
else return Object.keys(this.channels);
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Gets the channels to stream in their original format.
|
|
349
|
+
* If streamChannels is specified, returns it as-is (either single key or array).
|
|
350
|
+
* Otherwise, returns all channels in the graph as an array.
|
|
351
|
+
*
|
|
352
|
+
* @returns Channel keys to stream, either as a single key or array
|
|
353
|
+
*/
|
|
354
|
+
get streamChannelsAsIs() {
|
|
355
|
+
if (this.streamChannels) return this.streamChannels;
|
|
356
|
+
else return Object.keys(this.channels);
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Gets a drawable representation of the graph structure.
|
|
360
|
+
* This is an async version of getGraph() and is the preferred method to use.
|
|
361
|
+
*
|
|
362
|
+
* @param config - Configuration for generating the graph visualization
|
|
363
|
+
* @returns A representation of the graph that can be visualized
|
|
364
|
+
*/
|
|
365
|
+
async getGraphAsync(config) {
|
|
366
|
+
return this.getGraph(config);
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Gets all subgraphs within this graph.
|
|
370
|
+
* A subgraph is a Pregel instance that is nested within a node of this graph.
|
|
371
|
+
*
|
|
372
|
+
* @deprecated Use getSubgraphsAsync instead. The async method will become the default in the next minor release.
|
|
373
|
+
* @param namespace - Optional namespace to filter subgraphs
|
|
374
|
+
* @param recurse - Whether to recursively get subgraphs of subgraphs
|
|
375
|
+
* @returns Generator yielding tuples of [name, subgraph]
|
|
376
|
+
*/
|
|
377
|
+
*getSubgraphs(namespace, recurse) {
|
|
378
|
+
for (const [name, node] of Object.entries(this.nodes)) {
|
|
379
|
+
if (namespace !== void 0) {
|
|
380
|
+
if (!namespace.startsWith(name)) continue;
|
|
381
|
+
}
|
|
382
|
+
const candidates = node.subgraphs?.length ? node.subgraphs : [node.bound];
|
|
383
|
+
for (const candidate of candidates) {
|
|
384
|
+
const graph = findSubgraphPregel(candidate);
|
|
385
|
+
if (graph !== void 0) {
|
|
386
|
+
if (name === namespace) {
|
|
387
|
+
yield [name, graph];
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
if (namespace === void 0) yield [name, graph];
|
|
391
|
+
if (recurse) {
|
|
392
|
+
let newNamespace = namespace;
|
|
393
|
+
if (namespace !== void 0) newNamespace = namespace.slice(name.length + 1);
|
|
394
|
+
for (const [subgraphName, subgraph] of graph.getSubgraphs(newNamespace, recurse)) yield [`${name}${CHECKPOINT_NAMESPACE_SEPARATOR}${subgraphName}`, subgraph];
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* Gets all subgraphs within this graph asynchronously.
|
|
402
|
+
* A subgraph is a Pregel instance that is nested within a node of this graph.
|
|
403
|
+
*
|
|
404
|
+
* @param namespace - Optional namespace to filter subgraphs
|
|
405
|
+
* @param recurse - Whether to recursively get subgraphs of subgraphs
|
|
406
|
+
* @returns AsyncGenerator yielding tuples of [name, subgraph]
|
|
407
|
+
*/
|
|
408
|
+
async *getSubgraphsAsync(namespace, recurse) {
|
|
409
|
+
yield* this.getSubgraphs(namespace, recurse);
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Prepares a state snapshot from saved checkpoint data.
|
|
413
|
+
* This is an internal method used by getState and getStateHistory.
|
|
414
|
+
*
|
|
415
|
+
* @param config - Configuration for preparing the snapshot
|
|
416
|
+
* @param saved - Optional saved checkpoint data
|
|
417
|
+
* @param subgraphCheckpointer - Optional checkpointer for subgraphs
|
|
418
|
+
* @param applyPendingWrites - Whether to apply pending writes to tasks and then to channels
|
|
419
|
+
* @returns A snapshot of the graph state
|
|
420
|
+
* @internal
|
|
421
|
+
*/
|
|
422
|
+
async _prepareStateSnapshot({ config, saved, subgraphCheckpointer, applyPendingWrites = false }) {
|
|
423
|
+
if (saved === void 0) return {
|
|
424
|
+
values: {},
|
|
425
|
+
next: [],
|
|
426
|
+
config,
|
|
427
|
+
tasks: []
|
|
428
|
+
};
|
|
429
|
+
const channels = emptyChannels(this.channels, saved.checkpoint);
|
|
430
|
+
if (saved.pendingWrites?.length) {
|
|
431
|
+
const nullWrites = saved.pendingWrites.filter(([taskId, _]) => taskId === NULL_TASK_ID).map(([_, channel, value]) => [String(channel), value]);
|
|
432
|
+
if (nullWrites.length > 0) _applyWrites(saved.checkpoint, channels, [{
|
|
433
|
+
name: INPUT,
|
|
434
|
+
writes: nullWrites,
|
|
435
|
+
triggers: []
|
|
436
|
+
}], void 0, this.triggerToNodes);
|
|
437
|
+
}
|
|
438
|
+
const nextTasks = Object.values(_prepareNextTasks(saved.checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, {
|
|
439
|
+
step: (saved.metadata?.step ?? -1) + 1,
|
|
440
|
+
store: this.store
|
|
441
|
+
}));
|
|
442
|
+
const subgraphs = await gatherIterator(this.getSubgraphsAsync());
|
|
443
|
+
const parentNamespace = saved.config.configurable?.checkpoint_ns ?? "";
|
|
444
|
+
const taskStates = {};
|
|
445
|
+
for (const task of nextTasks) {
|
|
446
|
+
const matchingSubgraph = subgraphs.find(([name]) => name === task.name);
|
|
447
|
+
if (!matchingSubgraph) continue;
|
|
448
|
+
let taskNs = `${String(task.name)}${CHECKPOINT_NAMESPACE_END}${task.id}`;
|
|
449
|
+
if (parentNamespace) taskNs = `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${taskNs}`;
|
|
450
|
+
if (subgraphCheckpointer === void 0) {
|
|
451
|
+
const config$1 = { configurable: {
|
|
452
|
+
thread_id: saved.config.configurable?.thread_id,
|
|
453
|
+
checkpoint_ns: taskNs
|
|
454
|
+
} };
|
|
455
|
+
taskStates[task.id] = config$1;
|
|
456
|
+
} else {
|
|
457
|
+
const subgraphConfig = { configurable: {
|
|
458
|
+
[CONFIG_KEY_CHECKPOINTER]: subgraphCheckpointer,
|
|
459
|
+
thread_id: saved.config.configurable?.thread_id,
|
|
460
|
+
checkpoint_ns: taskNs
|
|
461
|
+
} };
|
|
462
|
+
const pregel = matchingSubgraph[1];
|
|
463
|
+
taskStates[task.id] = await pregel.getState(subgraphConfig, { subgraphs: true });
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
if (applyPendingWrites && saved.pendingWrites?.length) {
|
|
467
|
+
const nextTaskById = Object.fromEntries(nextTasks.map((task) => [task.id, task]));
|
|
468
|
+
for (const [taskId, channel, value] of saved.pendingWrites) {
|
|
469
|
+
if ([
|
|
470
|
+
ERROR,
|
|
471
|
+
INTERRUPT,
|
|
472
|
+
SCHEDULED
|
|
473
|
+
].includes(channel)) continue;
|
|
474
|
+
if (!(taskId in nextTaskById)) continue;
|
|
475
|
+
nextTaskById[taskId].writes.push([String(channel), value]);
|
|
476
|
+
}
|
|
477
|
+
const tasksWithWrites$1 = nextTasks.filter((task) => task.writes.length > 0);
|
|
478
|
+
if (tasksWithWrites$1.length > 0) _applyWrites(saved.checkpoint, channels, tasksWithWrites$1, void 0, this.triggerToNodes);
|
|
479
|
+
}
|
|
480
|
+
let metadata = saved?.metadata;
|
|
481
|
+
if (metadata && saved?.config?.configurable?.thread_id) metadata = {
|
|
482
|
+
...metadata,
|
|
483
|
+
thread_id: saved.config.configurable.thread_id
|
|
484
|
+
};
|
|
485
|
+
const nextList = nextTasks.filter((task) => task.writes.length === 0).map((task) => task.name);
|
|
486
|
+
return {
|
|
487
|
+
values: readChannels(channels, this.streamChannelsAsIs),
|
|
488
|
+
next: nextList,
|
|
489
|
+
tasks: tasksWithWrites(nextTasks, saved?.pendingWrites ?? [], taskStates, this.streamChannelsAsIs),
|
|
490
|
+
metadata,
|
|
491
|
+
config: patchCheckpointMap(saved.config, saved.metadata),
|
|
492
|
+
createdAt: saved.checkpoint.ts,
|
|
493
|
+
parentConfig: saved.parentConfig
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* Gets the current state of the graph.
|
|
498
|
+
* Requires a checkpointer to be configured.
|
|
499
|
+
*
|
|
500
|
+
* @param config - Configuration for retrieving the state
|
|
501
|
+
* @param options - Additional options
|
|
502
|
+
* @returns A snapshot of the current graph state
|
|
503
|
+
* @throws {GraphValueError} If no checkpointer is configured
|
|
504
|
+
*/
|
|
505
|
+
async getState(config, options) {
|
|
506
|
+
const checkpointer = config.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;
|
|
507
|
+
if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" });
|
|
508
|
+
const checkpointNamespace = config.configurable?.checkpoint_ns ?? "";
|
|
509
|
+
if (checkpointNamespace !== "" && config.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) {
|
|
510
|
+
const recastNamespace = recastCheckpointNamespace(checkpointNamespace);
|
|
511
|
+
for await (const [name, subgraph] of this.getSubgraphsAsync(recastNamespace, true)) if (name === recastNamespace) return await subgraph.getState(patchConfigurable(config, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), { subgraphs: options?.subgraphs });
|
|
512
|
+
throw new Error(`Subgraph with namespace "${recastNamespace}" not found.`);
|
|
513
|
+
}
|
|
514
|
+
const mergedConfig = mergeConfigs(this.config, config);
|
|
515
|
+
const saved = await checkpointer.getTuple(config);
|
|
516
|
+
return await this._prepareStateSnapshot({
|
|
517
|
+
config: mergedConfig,
|
|
518
|
+
saved,
|
|
519
|
+
subgraphCheckpointer: options?.subgraphs ? checkpointer : void 0,
|
|
520
|
+
applyPendingWrites: !config.configurable?.checkpoint_id
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Gets the history of graph states.
|
|
525
|
+
* Requires a checkpointer to be configured.
|
|
526
|
+
* Useful for:
|
|
527
|
+
* - Debugging execution history
|
|
528
|
+
* - Implementing time travel
|
|
529
|
+
* - Analyzing graph behavior
|
|
530
|
+
*
|
|
531
|
+
* @param config - Configuration for retrieving the history
|
|
532
|
+
* @param options - Options for filtering the history
|
|
533
|
+
* @returns An async iterator of state snapshots
|
|
534
|
+
* @throws {Error} If no checkpointer is configured
|
|
535
|
+
*/
|
|
536
|
+
async *getStateHistory(config, options) {
|
|
537
|
+
const checkpointer = config.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;
|
|
538
|
+
if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" });
|
|
539
|
+
const checkpointNamespace = config.configurable?.checkpoint_ns ?? "";
|
|
540
|
+
if (checkpointNamespace !== "" && config.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) {
|
|
541
|
+
const recastNamespace = recastCheckpointNamespace(checkpointNamespace);
|
|
542
|
+
for await (const [name, pregel] of this.getSubgraphsAsync(recastNamespace, true)) if (name === recastNamespace) {
|
|
543
|
+
yield* pregel.getStateHistory(patchConfigurable(config, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), options);
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
throw new Error(`Subgraph with namespace "${recastNamespace}" not found.`);
|
|
547
|
+
}
|
|
548
|
+
const mergedConfig = mergeConfigs(this.config, config, { configurable: { checkpoint_ns: checkpointNamespace } });
|
|
549
|
+
for await (const checkpointTuple of checkpointer.list(mergedConfig, options)) yield this._prepareStateSnapshot({
|
|
550
|
+
config: checkpointTuple.config,
|
|
551
|
+
saved: checkpointTuple
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* Apply updates to the graph state in bulk.
|
|
556
|
+
* Requires a checkpointer to be configured.
|
|
557
|
+
*
|
|
558
|
+
* This method is useful for recreating a thread
|
|
559
|
+
* from a list of updates, especially if a checkpoint
|
|
560
|
+
* is created as a result of multiple tasks.
|
|
561
|
+
*
|
|
562
|
+
* @internal The API might change in the future.
|
|
563
|
+
*
|
|
564
|
+
* @param startConfig - Configuration for the update
|
|
565
|
+
* @param updates - The list of updates to apply to graph state
|
|
566
|
+
* @returns Updated configuration
|
|
567
|
+
* @throws {GraphValueError} If no checkpointer is configured
|
|
568
|
+
* @throws {InvalidUpdateError} If the update cannot be attributed to a node or an update can be only applied in sequence.
|
|
569
|
+
*/
|
|
570
|
+
async bulkUpdateState(startConfig, supersteps) {
|
|
571
|
+
const checkpointer = startConfig.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer;
|
|
572
|
+
if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" });
|
|
573
|
+
if (supersteps.length === 0) throw new Error("No supersteps provided");
|
|
574
|
+
if (supersteps.some((s) => s.updates.length === 0)) throw new Error("No updates provided");
|
|
575
|
+
const checkpointNamespace = startConfig.configurable?.checkpoint_ns ?? "";
|
|
576
|
+
if (checkpointNamespace !== "" && startConfig.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) {
|
|
577
|
+
const recastNamespace = recastCheckpointNamespace(checkpointNamespace);
|
|
578
|
+
for await (const [, pregel] of this.getSubgraphsAsync(recastNamespace, true)) return await pregel.bulkUpdateState(patchConfigurable(startConfig, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), supersteps);
|
|
579
|
+
throw new Error(`Subgraph "${recastNamespace}" not found`);
|
|
580
|
+
}
|
|
581
|
+
const updateSuperStep = async (inputConfig, updates) => {
|
|
582
|
+
const config = this.config ? mergeConfigs(this.config, inputConfig) : inputConfig;
|
|
583
|
+
const saved = await checkpointer.getTuple(config);
|
|
584
|
+
const checkpoint = saved !== void 0 ? copyCheckpoint(saved.checkpoint) : emptyCheckpoint();
|
|
585
|
+
const checkpointPreviousVersions = { ...saved?.checkpoint.channel_versions };
|
|
586
|
+
const step = saved?.metadata?.step ?? -1;
|
|
587
|
+
let checkpointConfig = patchConfigurable(config, { checkpoint_ns: config.configurable?.checkpoint_ns ?? "" });
|
|
588
|
+
let checkpointMetadata = config.metadata ?? {};
|
|
589
|
+
if (saved?.config.configurable) {
|
|
590
|
+
checkpointConfig = patchConfigurable(config, saved.config.configurable);
|
|
591
|
+
checkpointMetadata = {
|
|
592
|
+
...saved.metadata,
|
|
593
|
+
...checkpointMetadata
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
const { values, asNode } = updates[0];
|
|
597
|
+
if (values == null && asNode === void 0) {
|
|
598
|
+
if (updates.length > 1) throw new InvalidUpdateError(`Cannot create empty checkpoint with multiple updates`);
|
|
599
|
+
return patchCheckpointMap(await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, void 0, step), {
|
|
600
|
+
source: "update",
|
|
601
|
+
step: step + 1,
|
|
602
|
+
parents: saved?.metadata?.parents ?? {}
|
|
603
|
+
}, {}), saved ? saved.metadata : void 0);
|
|
604
|
+
}
|
|
605
|
+
const channels = emptyChannels(this.channels, checkpoint);
|
|
606
|
+
if (values === null && asNode === END) {
|
|
607
|
+
if (updates.length > 1) throw new InvalidUpdateError(`Cannot apply multiple updates when clearing state`);
|
|
608
|
+
if (saved) {
|
|
609
|
+
const nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites || [], this.nodes, channels, saved.config, true, {
|
|
610
|
+
step: (saved.metadata?.step ?? -1) + 1,
|
|
611
|
+
checkpointer,
|
|
612
|
+
store: this.store
|
|
613
|
+
});
|
|
614
|
+
const nullWrites = (saved.pendingWrites || []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1));
|
|
615
|
+
if (nullWrites.length > 0) _applyWrites(checkpoint, channels, [{
|
|
616
|
+
name: INPUT,
|
|
617
|
+
writes: nullWrites,
|
|
618
|
+
triggers: []
|
|
619
|
+
}], checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes);
|
|
620
|
+
for (const [taskId, k, v] of saved.pendingWrites || []) {
|
|
621
|
+
if ([
|
|
622
|
+
ERROR,
|
|
623
|
+
INTERRUPT,
|
|
624
|
+
SCHEDULED
|
|
625
|
+
].includes(k)) continue;
|
|
626
|
+
if (!(taskId in nextTasks)) continue;
|
|
627
|
+
nextTasks[taskId].writes.push([k, v]);
|
|
628
|
+
}
|
|
629
|
+
_applyWrites(checkpoint, channels, Object.values(nextTasks), checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes);
|
|
630
|
+
}
|
|
631
|
+
return patchCheckpointMap(await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step), {
|
|
632
|
+
...checkpointMetadata,
|
|
633
|
+
source: "update",
|
|
634
|
+
step: step + 1,
|
|
635
|
+
parents: saved?.metadata?.parents ?? {}
|
|
636
|
+
}, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions)), saved ? saved.metadata : void 0);
|
|
637
|
+
}
|
|
638
|
+
if (asNode === COPY) {
|
|
639
|
+
if (updates.length > 1) throw new InvalidUpdateError(`Cannot copy checkpoint with multiple updates`);
|
|
640
|
+
if (saved == null) throw new InvalidUpdateError(`Cannot copy a non-existent checkpoint`);
|
|
641
|
+
const isCopyWithUpdates = (values$1) => {
|
|
642
|
+
if (!Array.isArray(values$1)) return false;
|
|
643
|
+
if (values$1.length === 0) return false;
|
|
644
|
+
return values$1.every((v) => Array.isArray(v) && v.length === 2);
|
|
645
|
+
};
|
|
646
|
+
const nextCheckpoint = createCheckpoint(checkpoint, void 0, step);
|
|
647
|
+
const nextConfig$1 = await checkpointer.put(saved.parentConfig ?? patchConfigurable(saved.config, { checkpoint_id: void 0 }), nextCheckpoint, {
|
|
648
|
+
source: "fork",
|
|
649
|
+
step: step + 1,
|
|
650
|
+
parents: saved.metadata?.parents ?? {}
|
|
651
|
+
}, {});
|
|
652
|
+
if (isCopyWithUpdates(values)) {
|
|
653
|
+
const nextTasks = _prepareNextTasks(nextCheckpoint, saved.pendingWrites, this.nodes, channels, nextConfig$1, false, { step: step + 2 });
|
|
654
|
+
const tasksGroupBy = Object.values(nextTasks).reduce((acc, { name, id }) => {
|
|
655
|
+
acc[name] ??= [];
|
|
656
|
+
acc[name].push({ id });
|
|
657
|
+
return acc;
|
|
658
|
+
}, {});
|
|
659
|
+
const userGroupBy = values.reduce((acc, item) => {
|
|
660
|
+
const [values$1, asNode$1] = item;
|
|
661
|
+
acc[asNode$1] ??= [];
|
|
662
|
+
const targetIdx = acc[asNode$1].length;
|
|
663
|
+
const taskId = tasksGroupBy[asNode$1]?.[targetIdx]?.id;
|
|
664
|
+
acc[asNode$1].push({
|
|
665
|
+
values: values$1,
|
|
666
|
+
asNode: asNode$1,
|
|
667
|
+
taskId
|
|
668
|
+
});
|
|
669
|
+
return acc;
|
|
670
|
+
}, {});
|
|
671
|
+
return updateSuperStep(patchCheckpointMap(nextConfig$1, saved.metadata), Object.values(userGroupBy).flat());
|
|
672
|
+
}
|
|
673
|
+
return patchCheckpointMap(nextConfig$1, saved.metadata);
|
|
674
|
+
}
|
|
675
|
+
if (asNode === INPUT) {
|
|
676
|
+
if (updates.length > 1) throw new InvalidUpdateError(`Cannot apply multiple updates when updating as input`);
|
|
677
|
+
const inputWrites = await gatherIterator(mapInput(this.inputChannels, values));
|
|
678
|
+
if (inputWrites.length === 0) throw new InvalidUpdateError(`Received no input writes for ${JSON.stringify(this.inputChannels, null, 2)}`);
|
|
679
|
+
_applyWrites(checkpoint, channels, [{
|
|
680
|
+
name: INPUT,
|
|
681
|
+
writes: inputWrites,
|
|
682
|
+
triggers: []
|
|
683
|
+
}], checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes);
|
|
684
|
+
const nextStep = saved?.metadata?.step != null ? saved.metadata.step + 1 : -1;
|
|
685
|
+
const nextConfig$1 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, nextStep), {
|
|
686
|
+
source: "input",
|
|
687
|
+
step: nextStep,
|
|
688
|
+
parents: saved?.metadata?.parents ?? {}
|
|
689
|
+
}, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions));
|
|
690
|
+
await checkpointer.putWrites(nextConfig$1, inputWrites, uuid5(INPUT, checkpoint.id));
|
|
691
|
+
return patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0);
|
|
692
|
+
}
|
|
693
|
+
if (config.configurable?.checkpoint_id === void 0 && saved?.pendingWrites !== void 0 && saved.pendingWrites.length > 0) {
|
|
694
|
+
const nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, {
|
|
695
|
+
store: this.store,
|
|
696
|
+
checkpointer: this.checkpointer,
|
|
697
|
+
step: (saved.metadata?.step ?? -1) + 1
|
|
698
|
+
});
|
|
699
|
+
const nullWrites = (saved.pendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1));
|
|
700
|
+
if (nullWrites.length > 0) _applyWrites(saved.checkpoint, channels, [{
|
|
701
|
+
name: INPUT,
|
|
702
|
+
writes: nullWrites,
|
|
703
|
+
triggers: []
|
|
704
|
+
}], void 0, this.triggerToNodes);
|
|
705
|
+
for (const [tid, k, v] of saved.pendingWrites) {
|
|
706
|
+
if ([
|
|
707
|
+
ERROR,
|
|
708
|
+
INTERRUPT,
|
|
709
|
+
SCHEDULED
|
|
710
|
+
].includes(k) || nextTasks[tid] === void 0) continue;
|
|
711
|
+
nextTasks[tid].writes.push([k, v]);
|
|
712
|
+
}
|
|
713
|
+
const tasks$1 = Object.values(nextTasks).filter((task) => {
|
|
714
|
+
return task.writes.length > 0;
|
|
715
|
+
});
|
|
716
|
+
if (tasks$1.length > 0) _applyWrites(checkpoint, channels, tasks$1, void 0, this.triggerToNodes);
|
|
717
|
+
}
|
|
718
|
+
const nonNullVersion = Object.values(checkpoint.versions_seen).map((seenVersions) => {
|
|
719
|
+
return Object.values(seenVersions);
|
|
720
|
+
}).flat().find((v) => !!v);
|
|
721
|
+
const validUpdates = [];
|
|
722
|
+
if (updates.length === 1) {
|
|
723
|
+
let { values: values$1, asNode: asNode$1, taskId } = updates[0];
|
|
724
|
+
if (asNode$1 === void 0 && Object.keys(this.nodes).length === 1) [asNode$1] = Object.keys(this.nodes);
|
|
725
|
+
else if (asNode$1 === void 0 && nonNullVersion === void 0) {
|
|
726
|
+
if (typeof this.inputChannels === "string" && this.nodes[this.inputChannels] !== void 0) asNode$1 = this.inputChannels;
|
|
727
|
+
} else if (asNode$1 === void 0) {
|
|
728
|
+
const lastSeenByNode = Object.entries(checkpoint.versions_seen).map(([n, seen]) => {
|
|
729
|
+
return Object.values(seen).map((v) => {
|
|
730
|
+
return [v, n];
|
|
731
|
+
});
|
|
732
|
+
}).flat().filter(([_, v]) => v !== INTERRUPT).sort(([aNumber], [bNumber]) => compareChannelVersions(aNumber, bNumber));
|
|
733
|
+
if (lastSeenByNode) {
|
|
734
|
+
if (lastSeenByNode.length === 1) asNode$1 = lastSeenByNode[0][1];
|
|
735
|
+
else if (lastSeenByNode[lastSeenByNode.length - 1][0] !== lastSeenByNode[lastSeenByNode.length - 2][0]) asNode$1 = lastSeenByNode[lastSeenByNode.length - 1][1];
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
if (asNode$1 === void 0) throw new InvalidUpdateError(`Ambiguous update, specify "asNode"`);
|
|
739
|
+
validUpdates.push({
|
|
740
|
+
values: values$1,
|
|
741
|
+
asNode: asNode$1,
|
|
742
|
+
taskId
|
|
743
|
+
});
|
|
744
|
+
} else for (const { asNode: asNode$1, values: values$1, taskId } of updates) {
|
|
745
|
+
if (asNode$1 == null) throw new InvalidUpdateError(`"asNode" is required when applying multiple updates`);
|
|
746
|
+
validUpdates.push({
|
|
747
|
+
values: values$1,
|
|
748
|
+
asNode: asNode$1,
|
|
749
|
+
taskId
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
const tasks = [];
|
|
753
|
+
for (const { asNode: asNode$1, values: values$1, taskId } of validUpdates) {
|
|
754
|
+
if (this.nodes[asNode$1] === void 0) throw new InvalidUpdateError(`Node "${asNode$1.toString()}" does not exist`);
|
|
755
|
+
const writers = this.nodes[asNode$1].getWriters();
|
|
756
|
+
if (!writers.length) throw new InvalidUpdateError(`No writers found for node "${asNode$1.toString()}"`);
|
|
757
|
+
tasks.push({
|
|
758
|
+
name: asNode$1,
|
|
759
|
+
input: values$1,
|
|
760
|
+
proc: writers.length > 1 ? RunnableSequence.from(writers, { omitSequenceTags: true }) : writers[0],
|
|
761
|
+
writes: [],
|
|
762
|
+
triggers: [INTERRUPT],
|
|
763
|
+
id: taskId ?? uuid5(INTERRUPT, checkpoint.id),
|
|
764
|
+
writers: []
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
for (const task of tasks) await task.proc.invoke(task.input, patchConfig({
|
|
768
|
+
...config,
|
|
769
|
+
store: config?.store ?? this.store
|
|
770
|
+
}, {
|
|
771
|
+
runName: config.runName ?? `${this.getName()}UpdateState`,
|
|
772
|
+
configurable: {
|
|
773
|
+
[CONFIG_KEY_SEND]: (items) => task.writes.push(...items),
|
|
774
|
+
[CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, task, select_, fresh_)
|
|
775
|
+
}
|
|
776
|
+
}));
|
|
777
|
+
for (const task of tasks) {
|
|
778
|
+
const channelWrites = task.writes.filter((w) => w[0] !== PUSH);
|
|
779
|
+
if (saved !== void 0 && channelWrites.length > 0) await checkpointer.putWrites(checkpointConfig, channelWrites, task.id);
|
|
780
|
+
}
|
|
781
|
+
_applyWrites(checkpoint, channels, tasks, checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes);
|
|
782
|
+
const newVersions = getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions);
|
|
783
|
+
const nextConfig = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step + 1), {
|
|
784
|
+
source: "update",
|
|
785
|
+
step: step + 1,
|
|
786
|
+
parents: saved?.metadata?.parents ?? {}
|
|
787
|
+
}, newVersions);
|
|
788
|
+
for (const task of tasks) {
|
|
789
|
+
const pushWrites = task.writes.filter((w) => w[0] === PUSH);
|
|
790
|
+
if (pushWrites.length > 0) await checkpointer.putWrites(nextConfig, pushWrites, task.id);
|
|
791
|
+
}
|
|
792
|
+
return patchCheckpointMap(nextConfig, saved ? saved.metadata : void 0);
|
|
793
|
+
};
|
|
794
|
+
let currentConfig = startConfig;
|
|
795
|
+
for (const { updates } of supersteps) currentConfig = await updateSuperStep(currentConfig, updates);
|
|
796
|
+
return currentConfig;
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* Updates the state of the graph with new values.
|
|
800
|
+
* Requires a checkpointer to be configured.
|
|
801
|
+
*
|
|
802
|
+
* This method can be used for:
|
|
803
|
+
* - Implementing human-in-the-loop workflows
|
|
804
|
+
* - Modifying graph state during breakpoints
|
|
805
|
+
* - Integrating external inputs into the graph
|
|
806
|
+
*
|
|
807
|
+
* @param inputConfig - Configuration for the update
|
|
808
|
+
* @param values - The values to update the state with
|
|
809
|
+
* @param asNode - Optional node name to attribute the update to
|
|
810
|
+
* @returns Updated configuration
|
|
811
|
+
* @throws {GraphValueError} If no checkpointer is configured
|
|
812
|
+
* @throws {InvalidUpdateError} If the update cannot be attributed to a node
|
|
813
|
+
*/
|
|
814
|
+
async updateState(inputConfig, values, asNode) {
|
|
815
|
+
return this.bulkUpdateState(inputConfig, [{ updates: [{
|
|
816
|
+
values,
|
|
817
|
+
asNode
|
|
818
|
+
}] }]);
|
|
819
|
+
}
|
|
820
|
+
/**
|
|
821
|
+
* Gets the default values for various graph configuration options.
|
|
822
|
+
* This is an internal method used to process and normalize configuration options.
|
|
823
|
+
*
|
|
824
|
+
* @param config - The input configuration options
|
|
825
|
+
* @returns A tuple containing normalized values for:
|
|
826
|
+
* - debug mode
|
|
827
|
+
* - stream modes
|
|
828
|
+
* - input keys
|
|
829
|
+
* - output keys
|
|
830
|
+
* - remaining config
|
|
831
|
+
* - interrupt before nodes
|
|
832
|
+
* - interrupt after nodes
|
|
833
|
+
* - checkpointer
|
|
834
|
+
* - store
|
|
835
|
+
* - whether stream mode is single
|
|
836
|
+
* - node cache
|
|
837
|
+
* - whether checkpoint during is enabled
|
|
838
|
+
* @internal
|
|
839
|
+
*/
|
|
840
|
+
_defaults(config) {
|
|
841
|
+
const { debug, streamMode, inputKeys, outputKeys, interruptAfter, interruptBefore, ...rest } = config;
|
|
842
|
+
let streamModeSingle = true;
|
|
843
|
+
const defaultDebug = debug !== void 0 ? debug : this.debug;
|
|
844
|
+
let defaultOutputKeys = outputKeys;
|
|
845
|
+
if (defaultOutputKeys === void 0) defaultOutputKeys = this.streamChannelsAsIs;
|
|
846
|
+
else validateKeys(defaultOutputKeys, this.channels);
|
|
847
|
+
let defaultInputKeys = inputKeys;
|
|
848
|
+
if (defaultInputKeys === void 0) defaultInputKeys = this.inputChannels;
|
|
849
|
+
else validateKeys(defaultInputKeys, this.channels);
|
|
850
|
+
const defaultInterruptBefore = interruptBefore ?? this.interruptBefore ?? [];
|
|
851
|
+
const defaultInterruptAfter = interruptAfter ?? this.interruptAfter ?? [];
|
|
852
|
+
let defaultStreamMode;
|
|
853
|
+
if (streamMode !== void 0) {
|
|
854
|
+
defaultStreamMode = Array.isArray(streamMode) ? streamMode : [streamMode];
|
|
855
|
+
streamModeSingle = typeof streamMode === "string";
|
|
856
|
+
} else {
|
|
857
|
+
if (config.configurable?.[CONFIG_KEY_TASK_ID] !== void 0) defaultStreamMode = ["values"];
|
|
858
|
+
else defaultStreamMode = this.streamMode;
|
|
859
|
+
streamModeSingle = true;
|
|
860
|
+
}
|
|
861
|
+
let defaultCheckpointer;
|
|
862
|
+
if (this.checkpointer === false) defaultCheckpointer = void 0;
|
|
863
|
+
else if (config !== void 0 && config.configurable?.[CONFIG_KEY_CHECKPOINTER] !== void 0) defaultCheckpointer = config.configurable[CONFIG_KEY_CHECKPOINTER];
|
|
864
|
+
else if (this.checkpointer === true) throw new Error("checkpointer: true cannot be used for root graphs.");
|
|
865
|
+
else defaultCheckpointer = this.checkpointer;
|
|
866
|
+
const defaultStore = config.store ?? this.store;
|
|
867
|
+
const defaultCache = config.cache ?? this.cache;
|
|
868
|
+
if (config.durability != null && config.checkpointDuring != null) throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time.");
|
|
869
|
+
const checkpointDuringDurability = (() => {
|
|
870
|
+
if (config.checkpointDuring == null) return void 0;
|
|
871
|
+
if (config.checkpointDuring === false) return "exit";
|
|
872
|
+
return "async";
|
|
873
|
+
})();
|
|
874
|
+
const defaultDurability = config.durability ?? checkpointDuringDurability ?? config?.configurable?.[CONFIG_KEY_DURABILITY] ?? "async";
|
|
875
|
+
return [
|
|
876
|
+
defaultDebug,
|
|
877
|
+
defaultStreamMode,
|
|
878
|
+
defaultInputKeys,
|
|
879
|
+
defaultOutputKeys,
|
|
880
|
+
rest,
|
|
881
|
+
defaultInterruptBefore,
|
|
882
|
+
defaultInterruptAfter,
|
|
883
|
+
defaultCheckpointer,
|
|
884
|
+
defaultStore,
|
|
885
|
+
streamModeSingle,
|
|
886
|
+
defaultCache,
|
|
887
|
+
defaultDurability
|
|
888
|
+
];
|
|
889
|
+
}
|
|
890
|
+
/**
|
|
891
|
+
* Streams the execution of the graph, emitting state updates as they occur.
|
|
892
|
+
* This is the primary method for observing graph execution in real-time.
|
|
893
|
+
*
|
|
894
|
+
* Stream modes:
|
|
895
|
+
* - "values": Emits complete state after each step
|
|
896
|
+
* - "updates": Emits only state changes after each step
|
|
897
|
+
* - "debug": Emits detailed debug information
|
|
898
|
+
* - "messages": Emits messages from within nodes
|
|
899
|
+
* - "custom": Emits custom events from within nodes
|
|
900
|
+
* - "checkpoints": Emits checkpoints from within nodes
|
|
901
|
+
* - "tasks": Emits tasks from within nodes
|
|
902
|
+
*
|
|
903
|
+
* @param input - The input to start graph execution with
|
|
904
|
+
* @param options - Configuration options for streaming
|
|
905
|
+
* @returns An async iterable stream of graph state updates
|
|
906
|
+
*/
|
|
907
|
+
async stream(input, options) {
|
|
908
|
+
const abortController = new AbortController();
|
|
909
|
+
const config = {
|
|
910
|
+
recursionLimit: this.config?.recursionLimit,
|
|
911
|
+
...options,
|
|
912
|
+
signal: combineAbortSignals(options?.signal, abortController.signal).signal
|
|
913
|
+
};
|
|
914
|
+
const stream = await super.stream(input, config);
|
|
915
|
+
return new IterableReadableStreamWithAbortSignal(options?.encoding === "text/event-stream" ? toEventStream(stream) : stream, abortController);
|
|
916
|
+
}
|
|
917
|
+
streamEvents(input, options, streamOptions) {
|
|
918
|
+
const abortController = new AbortController();
|
|
919
|
+
const config = {
|
|
920
|
+
recursionLimit: this.config?.recursionLimit,
|
|
921
|
+
...options,
|
|
922
|
+
callbacks: combineCallbacks(this.config?.callbacks, options?.callbacks),
|
|
923
|
+
signal: combineAbortSignals(options?.signal, abortController.signal).signal
|
|
924
|
+
};
|
|
925
|
+
return new IterableReadableStreamWithAbortSignal(super.streamEvents(input, config, streamOptions), abortController);
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Validates the input for the graph.
|
|
929
|
+
* @param input - The input to validate
|
|
930
|
+
* @returns The validated input
|
|
931
|
+
* @internal
|
|
932
|
+
*/
|
|
933
|
+
async _validateInput(input) {
|
|
934
|
+
return input;
|
|
935
|
+
}
|
|
936
|
+
/**
|
|
937
|
+
* Validates the context options for the graph.
|
|
938
|
+
* @param context - The context options to validate
|
|
939
|
+
* @returns The validated context options
|
|
940
|
+
* @internal
|
|
941
|
+
*/
|
|
942
|
+
async _validateContext(context) {
|
|
943
|
+
return context;
|
|
944
|
+
}
|
|
945
|
+
/**
|
|
946
|
+
* Internal iterator used by stream() to generate state updates.
|
|
947
|
+
* This method handles the core logic of graph execution and streaming.
|
|
948
|
+
*
|
|
949
|
+
* @param input - The input to start graph execution with
|
|
950
|
+
* @param options - Configuration options for streaming
|
|
951
|
+
* @returns AsyncGenerator yielding state updates
|
|
952
|
+
* @internal
|
|
953
|
+
*/
|
|
954
|
+
async *_streamIterator(input, options) {
|
|
955
|
+
const streamEncoding = "version" in (options ?? {}) ? void 0 : options?.encoding ?? void 0;
|
|
956
|
+
const streamSubgraphs = options?.subgraphs;
|
|
957
|
+
const inputConfig = ensureLangGraphConfig(this.config, options);
|
|
958
|
+
if (inputConfig.recursionLimit === void 0 || inputConfig.recursionLimit < 1) throw new Error(`Passed "recursionLimit" must be at least 1.`);
|
|
959
|
+
if (this.checkpointer !== void 0 && this.checkpointer !== false && inputConfig.configurable === void 0) throw new Error(`Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"`);
|
|
960
|
+
const validInput = await this._validateInput(input);
|
|
961
|
+
const { runId, ...restConfig } = inputConfig;
|
|
962
|
+
const [debug, streamMode, , outputKeys, config, interruptBefore, interruptAfter, checkpointer, store, streamModeSingle, cache, durability] = this._defaults(restConfig);
|
|
963
|
+
if (typeof config.context !== "undefined") config.context = await this._validateContext(config.context);
|
|
964
|
+
else config.configurable = await this._validateContext(config.configurable);
|
|
965
|
+
const stream = new IterableReadableWritableStream({ modes: new Set(streamMode) });
|
|
966
|
+
if (this.checkpointer === true) {
|
|
967
|
+
config.configurable ??= {};
|
|
968
|
+
const ns = config.configurable[CONFIG_KEY_CHECKPOINT_NS] ?? "";
|
|
969
|
+
config.configurable[CONFIG_KEY_CHECKPOINT_NS] = ns.split(CHECKPOINT_NAMESPACE_SEPARATOR).map((part) => part.split(CHECKPOINT_NAMESPACE_END)[0]).join(CHECKPOINT_NAMESPACE_SEPARATOR);
|
|
970
|
+
}
|
|
971
|
+
if (streamMode.includes("messages")) {
|
|
972
|
+
const messageStreamer = new StreamMessagesHandler((chunk) => stream.push(chunk));
|
|
973
|
+
const { callbacks } = config;
|
|
974
|
+
if (callbacks === void 0) config.callbacks = [messageStreamer];
|
|
975
|
+
else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat(messageStreamer);
|
|
976
|
+
else {
|
|
977
|
+
const copiedCallbacks = callbacks.copy();
|
|
978
|
+
copiedCallbacks.addHandler(messageStreamer, true);
|
|
979
|
+
config.callbacks = copiedCallbacks;
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
config.writer ??= (chunk) => {
|
|
983
|
+
if (!streamMode.includes("custom")) return;
|
|
984
|
+
const ns = (getConfig()?.configurable?.[CONFIG_KEY_CHECKPOINT_NS])?.split(CHECKPOINT_NAMESPACE_SEPARATOR).slice(0, -1);
|
|
985
|
+
stream.push([
|
|
986
|
+
ns ?? [],
|
|
987
|
+
"custom",
|
|
988
|
+
chunk
|
|
989
|
+
]);
|
|
990
|
+
};
|
|
991
|
+
config.interrupt ??= this.userInterrupt ?? interrupt;
|
|
992
|
+
const runManager = await (await getCallbackManagerForConfig(config))?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, void 0, void 0, void 0, config?.runName ?? this.getName());
|
|
993
|
+
const channelSpecs = getOnlyChannels(this.channels);
|
|
994
|
+
let loop;
|
|
995
|
+
let loopError;
|
|
996
|
+
/**
|
|
997
|
+
* The PregelLoop will yield events from concurrent tasks as soon as they are
|
|
998
|
+
* generated. Each task can push multiple events onto the stream in any order.
|
|
999
|
+
*
|
|
1000
|
+
* We use a separate background method and stream here in order to yield events
|
|
1001
|
+
* from the loop to the main stream and therefore back to the user as soon as
|
|
1002
|
+
* they are available.
|
|
1003
|
+
*/
|
|
1004
|
+
const createAndRunLoop = async () => {
|
|
1005
|
+
try {
|
|
1006
|
+
loop = await PregelLoop.initialize({
|
|
1007
|
+
input: validInput,
|
|
1008
|
+
config,
|
|
1009
|
+
checkpointer,
|
|
1010
|
+
nodes: this.nodes,
|
|
1011
|
+
channelSpecs,
|
|
1012
|
+
outputKeys,
|
|
1013
|
+
streamKeys: this.streamChannelsAsIs,
|
|
1014
|
+
store,
|
|
1015
|
+
cache,
|
|
1016
|
+
stream,
|
|
1017
|
+
interruptAfter,
|
|
1018
|
+
interruptBefore,
|
|
1019
|
+
manager: runManager,
|
|
1020
|
+
debug: this.debug,
|
|
1021
|
+
triggerToNodes: this.triggerToNodes,
|
|
1022
|
+
durability
|
|
1023
|
+
});
|
|
1024
|
+
const runner = new PregelRunner({
|
|
1025
|
+
loop,
|
|
1026
|
+
nodeFinished: config.configurable?.[CONFIG_KEY_NODE_FINISHED]
|
|
1027
|
+
});
|
|
1028
|
+
if (options?.subgraphs) loop.config.configurable = {
|
|
1029
|
+
...loop.config.configurable,
|
|
1030
|
+
[CONFIG_KEY_STREAM]: loop.stream
|
|
1031
|
+
};
|
|
1032
|
+
await this._runLoop({
|
|
1033
|
+
loop,
|
|
1034
|
+
runner,
|
|
1035
|
+
debug,
|
|
1036
|
+
config
|
|
1037
|
+
});
|
|
1038
|
+
if (durability === "sync") await Promise.all(loop?.checkpointerPromises ?? []);
|
|
1039
|
+
} catch (e) {
|
|
1040
|
+
loopError = e;
|
|
1041
|
+
} finally {
|
|
1042
|
+
try {
|
|
1043
|
+
if (loop) {
|
|
1044
|
+
await loop.store?.stop();
|
|
1045
|
+
await loop.cache?.stop();
|
|
1046
|
+
}
|
|
1047
|
+
await Promise.all(loop?.checkpointerPromises ?? []);
|
|
1048
|
+
} catch (e) {
|
|
1049
|
+
loopError = loopError ?? e;
|
|
1050
|
+
}
|
|
1051
|
+
if (loopError) stream.error(loopError);
|
|
1052
|
+
else stream.close();
|
|
1053
|
+
}
|
|
1054
|
+
};
|
|
1055
|
+
const runLoopPromise = createAndRunLoop();
|
|
1056
|
+
try {
|
|
1057
|
+
for await (const chunk of stream) {
|
|
1058
|
+
if (chunk === void 0) throw new Error("Data structure error.");
|
|
1059
|
+
const [namespace, mode, payload] = chunk;
|
|
1060
|
+
if (streamMode.includes(mode)) {
|
|
1061
|
+
if (streamEncoding === "text/event-stream") {
|
|
1062
|
+
if (streamSubgraphs) yield [
|
|
1063
|
+
namespace,
|
|
1064
|
+
mode,
|
|
1065
|
+
payload
|
|
1066
|
+
];
|
|
1067
|
+
else yield [
|
|
1068
|
+
null,
|
|
1069
|
+
mode,
|
|
1070
|
+
payload
|
|
1071
|
+
];
|
|
1072
|
+
continue;
|
|
1073
|
+
}
|
|
1074
|
+
if (streamSubgraphs && !streamModeSingle) yield [
|
|
1075
|
+
namespace,
|
|
1076
|
+
mode,
|
|
1077
|
+
payload
|
|
1078
|
+
];
|
|
1079
|
+
else if (!streamModeSingle) yield [mode, payload];
|
|
1080
|
+
else if (streamSubgraphs) yield [namespace, payload];
|
|
1081
|
+
else yield payload;
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
} catch (e) {
|
|
1085
|
+
await runManager?.handleChainError(loopError);
|
|
1086
|
+
throw e;
|
|
1087
|
+
} finally {
|
|
1088
|
+
await runLoopPromise;
|
|
1089
|
+
}
|
|
1090
|
+
await runManager?.handleChainEnd(loop?.output ?? {}, runId, void 0, void 0, void 0);
|
|
1091
|
+
}
|
|
1092
|
+
/**
|
|
1093
|
+
* Run the graph with a single input and config.
|
|
1094
|
+
* @param input The input to the graph.
|
|
1095
|
+
* @param options The configuration to use for the run.
|
|
1096
|
+
*/
|
|
1097
|
+
async invoke(input, options) {
|
|
1098
|
+
const streamMode = options?.streamMode ?? "values";
|
|
1099
|
+
const config = {
|
|
1100
|
+
...options,
|
|
1101
|
+
outputKeys: options?.outputKeys ?? this.outputChannels,
|
|
1102
|
+
streamMode,
|
|
1103
|
+
encoding: void 0
|
|
1104
|
+
};
|
|
1105
|
+
const chunks = [];
|
|
1106
|
+
const stream = await this.stream(input, config);
|
|
1107
|
+
const interruptChunks = [];
|
|
1108
|
+
let latest;
|
|
1109
|
+
for await (const chunk of stream) if (streamMode === "values") if (isInterrupted(chunk)) interruptChunks.push(chunk[INTERRUPT]);
|
|
1110
|
+
else latest = chunk;
|
|
1111
|
+
else chunks.push(chunk);
|
|
1112
|
+
if (streamMode === "values") {
|
|
1113
|
+
if (interruptChunks.length > 0) {
|
|
1114
|
+
const interrupts = interruptChunks.flat(1);
|
|
1115
|
+
if (latest == null) return { [INTERRUPT]: interrupts };
|
|
1116
|
+
if (typeof latest === "object") return {
|
|
1117
|
+
...latest,
|
|
1118
|
+
[INTERRUPT]: interrupts
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
return latest;
|
|
1122
|
+
}
|
|
1123
|
+
return chunks;
|
|
1124
|
+
}
|
|
1125
|
+
async _runLoop(params) {
|
|
1126
|
+
const { loop, runner, debug, config } = params;
|
|
1127
|
+
let tickError;
|
|
1128
|
+
try {
|
|
1129
|
+
while (await loop.tick({ inputKeys: this.inputChannels })) {
|
|
1130
|
+
for (const { task } of await loop._matchCachedWrites()) loop._outputWrites(task.id, task.writes, true);
|
|
1131
|
+
if (debug) printStepCheckpoint(loop.checkpointMetadata.step, loop.channels, this.streamChannelsList);
|
|
1132
|
+
if (debug) printStepTasks(loop.step, Object.values(loop.tasks));
|
|
1133
|
+
await runner.tick({
|
|
1134
|
+
timeout: this.stepTimeout,
|
|
1135
|
+
retryPolicy: this.retryPolicy,
|
|
1136
|
+
onStepWrite: (step, writes) => {
|
|
1137
|
+
if (debug) printStepWrites(step, writes, this.streamChannelsList);
|
|
1138
|
+
},
|
|
1139
|
+
maxConcurrency: config.maxConcurrency,
|
|
1140
|
+
signal: config.signal
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
if (loop.status === "out_of_steps") throw new GraphRecursionError([
|
|
1144
|
+
`Recursion limit of ${config.recursionLimit} reached`,
|
|
1145
|
+
"without hitting a stop condition. You can increase the",
|
|
1146
|
+
`limit by setting the "recursionLimit" config key.`
|
|
1147
|
+
].join(" "), { lc_error_code: "GRAPH_RECURSION_LIMIT" });
|
|
1148
|
+
} catch (e) {
|
|
1149
|
+
tickError = e;
|
|
1150
|
+
if (!await loop.finishAndHandleError(tickError)) throw e;
|
|
1151
|
+
} finally {
|
|
1152
|
+
if (tickError === void 0) await loop.finishAndHandleError();
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
async clearCache() {
|
|
1156
|
+
await this.cache?.clear([]);
|
|
1157
|
+
}
|
|
1158
|
+
};
|
|
1159
|
+
|
|
1160
|
+
//#endregion
|
|
1161
|
+
export { Channel, Pregel };
|
|
1162
|
+
//# sourceMappingURL=index.js.map
|