@langchain/langgraph 1.3.2 → 1.3.4
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/README.md +30 -93
- package/dist/constants.cjs +9 -5
- package/dist/constants.cjs.map +1 -1
- package/dist/constants.js +9 -5
- package/dist/constants.js.map +1 -1
- package/dist/graph/state.cjs +5 -1
- package/dist/graph/state.cjs.map +1 -1
- package/dist/graph/state.d.cts.map +1 -1
- package/dist/graph/state.d.ts.map +1 -1
- package/dist/graph/state.js +5 -1
- package/dist/graph/state.js.map +1 -1
- package/dist/pregel/remote.cjs +43 -19
- package/dist/pregel/remote.cjs.map +1 -1
- package/dist/pregel/remote.d.cts +3 -1
- package/dist/pregel/remote.d.cts.map +1 -1
- package/dist/pregel/remote.d.ts +3 -1
- package/dist/pregel/remote.d.ts.map +1 -1
- package/dist/pregel/remote.js +43 -19
- package/dist/pregel/remote.js.map +1 -1
- package/dist/pregel/runnable_types.d.cts.map +1 -1
- package/dist/pregel/runnable_types.d.ts.map +1 -1
- package/dist/pregel/stream.cjs +6 -1
- package/dist/pregel/stream.cjs.map +1 -1
- package/dist/pregel/stream.js +6 -1
- package/dist/pregel/stream.js.map +1 -1
- package/dist/pregel/types.cjs.map +1 -1
- package/dist/pregel/types.d.cts +1 -1
- package/dist/pregel/types.d.cts.map +1 -1
- package/dist/pregel/types.d.ts +1 -1
- package/dist/pregel/types.d.ts.map +1 -1
- package/dist/pregel/types.js.map +1 -1
- package/package.json +7 -7
package/dist/graph/state.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.js","names":[],"sources":["../../src/graph/state.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-use-before-define */\nimport { _coerceToRunnable, Runnable } from \"@langchain/core/runnables\";\nimport {\n All,\n type BaseCache,\n BaseCheckpointSaver,\n BaseStore,\n} from \"@langchain/langgraph-checkpoint\";\nimport {\n type InteropZodObject,\n interopParse,\n interopZodObjectPartial,\n isInteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport type {\n RunnableLike,\n LangGraphRunnableConfig,\n Runtime,\n} from \"../pregel/runnable_types.js\";\nimport { BaseChannel } from \"../channels/base.js\";\nimport {\n CompiledGraph,\n Graph,\n Branch,\n AddNodeOptions,\n NodeSpec,\n} from \"./graph.js\";\nimport {\n ChannelWrite,\n ChannelWriteEntry,\n ChannelWriteTupleEntry,\n PASSTHROUGH,\n} from \"../pregel/write.js\";\nimport { ChannelRead, PregelNode } from \"../pregel/read.js\";\nimport {\n NamedBarrierValue,\n NamedBarrierValueAfterFinish,\n} from \"../channels/named_barrier_value.js\";\nimport { EphemeralValue } from \"../channels/ephemeral_value.js\";\nimport { RunnableCallable } from \"../utils.js\";\nimport {\n isCommand,\n _isSend,\n CHECKPOINT_NAMESPACE_END,\n CHECKPOINT_NAMESPACE_SEPARATOR,\n Command,\n SELF,\n Send,\n START,\n END,\n TAG_HIDDEN,\n CommandInstance,\n isInterrupted,\n Interrupt,\n INTERRUPT,\n} from \"../constants.js\";\nimport {\n InvalidUpdateError,\n ParentCommand,\n StateGraphInputError,\n} from \"../errors.js\";\nimport {\n AnnotationRoot,\n getChannel,\n SingleReducer,\n StateDefinition,\n StateType,\n} from \"./annotation.js\";\nimport { StateSchema } from \"../state/index.js\";\nimport type { CachePolicy, RetryPolicy } from \"../pregel/utils/index.js\";\nimport { isPregelLike } from \"../pregel/utils/subgraph.js\";\nimport { LastValueAfterFinish } from \"../channels/last_value.js\";\nimport { type SchemaMetaRegistry, schemaMetaRegistry } from \"./zod/meta.js\";\nimport type {\n InferInterruptResumeType,\n InferInterruptInputType,\n} from \"../interrupt.js\";\nimport type { InferWriterType } from \"../writer.js\";\nimport type { AnyStateSchema } from \"../state/schema.js\";\nimport {\n ContextSchemaInit,\n ExtractStateType,\n ExtractUpdateType,\n isStateDefinitionInit,\n isStateGraphInit,\n StateGraphInit,\n StateGraphOptions,\n ToStateDefinition,\n type StateDefinitionInit,\n} from \"./types.js\";\nimport type { StreamTransformer } from \"../stream/types.js\";\n\nconst ROOT = \"__root__\";\n\nexport type ChannelReducers<Channels extends object> = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof Channels]: SingleReducer<Channels[K], any>;\n};\n\nexport interface StateGraphArgs<Channels extends object | unknown> {\n channels: Channels extends object\n ? Channels extends unknown[]\n ? ChannelReducers<{ __root__: Channels }>\n : ChannelReducers<Channels>\n : ChannelReducers<{ __root__: Channels }>;\n}\n\nexport type StateGraphNodeSpec<RunInput, RunOutput> = NodeSpec<\n RunInput,\n RunOutput\n> & {\n input?: StateDefinition;\n retryPolicy?: RetryPolicy;\n cachePolicy?: CachePolicy;\n};\n\n/**\n * Options for StateGraph.addNode() method.\n *\n * @template Nodes - Node name constraints\n * @template InputSchema - Per-node input schema type (inferred from options.input)\n */\nexport type StateGraphAddNodeOptions<\n Nodes extends string = string,\n InputSchema extends StateDefinitionInit | undefined =\n | StateDefinitionInit\n | undefined,\n> = {\n retryPolicy?: RetryPolicy;\n cachePolicy?: CachePolicy | boolean;\n input?: InputSchema;\n} & AddNodeOptions<Nodes>;\n\nexport type StateGraphArgsWithStateSchema<\n SD extends StateDefinition,\n I extends StateDefinition,\n O extends StateDefinition,\n> = {\n stateSchema: AnnotationRoot<SD>;\n input?: AnnotationRoot<I>;\n output?: AnnotationRoot<O>;\n};\n\nexport type StateGraphArgsWithInputOutputSchemas<\n SD extends StateDefinition,\n O extends StateDefinition = SD,\n> = {\n input: AnnotationRoot<SD>;\n output: AnnotationRoot<O>;\n};\n\ntype ExtractStateDefinition<T> = T extends AnyStateSchema\n ? T // Keep StateSchema as-is to preserve type information\n : T extends StateDefinitionInit\n ? ToStateDefinition<T>\n : StateDefinition;\n\ntype NodeAction<\n S,\n U,\n C extends StateDefinitionInit,\n InterruptType,\n WriterType,\n> = RunnableLike<\n S,\n U extends object ? U & Record<string, any> : U, // eslint-disable-line @typescript-eslint/no-explicit-any\n Runtime<StateType<ToStateDefinition<C>>, InterruptType, WriterType>\n>;\n\ntype StrictNodeAction<\n S,\n U,\n C extends StateDefinitionInit,\n Nodes extends string,\n InterruptType,\n WriterType,\n> = RunnableLike<\n Prettify<S>,\n | U\n | Command<\n InferInterruptResumeType<InterruptType>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n U & Record<string, any>,\n Nodes\n >,\n Runtime<StateType<ToStateDefinition<C>>, InterruptType, WriterType>\n>;\n\nconst PartialStateSchema = Symbol.for(\"langgraph.state.partial\");\ntype PartialStateSchema = typeof PartialStateSchema;\n\ntype MergeReturnType<Prev, Curr> = Prev & Curr extends infer T\n ? { [K in keyof T]: T[K] } & unknown\n : never;\n\ntype Prettify<T> = {\n [K in keyof T]: T[K];\n // eslint-disable-next-line @typescript-eslint/ban-types\n} & {};\n\n/**\n * A graph whose nodes communicate by reading and writing to a shared state.\n * Each node takes a defined `State` as input and returns a `Partial<State>`.\n *\n * Each state key can optionally be annotated with a reducer function that\n * will be used to aggregate the values of that key received from multiple nodes.\n * The signature of a reducer function is (left: Value, right: UpdateValue) => Value.\n *\n * See {@link Annotation} for more on defining state.\n *\n * After adding nodes and edges to your graph, you must call `.compile()` on it before\n * you can use it.\n *\n * @typeParam SD - The state definition used to construct the graph. Can be an\n * {@link AnnotationRoot}, {@link StateSchema}, or Zod object schema. This is the\n * primary generic from which `S` and `U` are derived.\n *\n * @typeParam S - The full state type representing the complete shape of your graph's\n * state after all reducers have been applied. Automatically inferred from `SD`.\n *\n * @typeParam U - The update type representing what nodes can return to modify state.\n * Typically a partial of the state type. Automatically inferred from `SD`.\n *\n * @typeParam N - Union of all node names in the graph (e.g., `\"agent\" | \"tool\"`).\n * Accumulated as you call `.addNode()`. Used for type-safe routing.\n *\n * @typeParam I - The input schema definition. Set via the `input` option in the\n * constructor to restrict what data the graph accepts when invoked.\n *\n * @typeParam O - The output schema definition. Set via the `output` option in the\n * constructor to restrict what data the graph returns after execution.\n *\n * @typeParam C - The config/context schema definition. Set via the `context` option\n * to define additional configuration passed at runtime.\n *\n * @typeParam NodeReturnType - Constrains what types nodes in this graph can return.\n *\n * @typeParam InterruptType - The type for {@link interrupt} resume values. Set via\n * the `interrupt` option for typed human-in-the-loop patterns.\n *\n * @typeParam WriterType - The type for custom stream writers. Set via the `writer`\n * option to enable typed custom streaming from within nodes.\n *\n * @example\n * ```ts\n * import {\n * type BaseMessage,\n * AIMessage,\n * HumanMessage,\n * } from \"@langchain/core/messages\";\n * import { StateGraph, Annotation } from \"@langchain/langgraph\";\n *\n * // Define a state with a single key named \"messages\" that will\n * // combine a returned BaseMessage or arrays of BaseMessages\n * const StateAnnotation = Annotation.Root({\n * sentiment: Annotation<string>,\n * messages: Annotation<BaseMessage[]>({\n * reducer: (left: BaseMessage[], right: BaseMessage | BaseMessage[]) => {\n * if (Array.isArray(right)) {\n * return left.concat(right);\n * }\n * return left.concat([right]);\n * },\n * default: () => [],\n * }),\n * });\n *\n * const graphBuilder = new StateGraph(StateAnnotation);\n *\n * // A node in the graph that returns an object with a \"messages\" key\n * // will update the state by combining the existing value with the returned one.\n * const myNode = (state: typeof StateAnnotation.State) => {\n * return {\n * messages: [new AIMessage(\"Some new response\")],\n * sentiment: \"positive\",\n * };\n * };\n *\n * const graph = graphBuilder\n * .addNode(\"myNode\", myNode)\n * .addEdge(\"__start__\", \"myNode\")\n * .addEdge(\"myNode\", \"__end__\")\n * .compile();\n *\n * await graph.invoke({ messages: [new HumanMessage(\"how are you?\")] });\n *\n * // {\n * // messages: [HumanMessage(\"how are you?\"), AIMessage(\"Some new response\")],\n * // sentiment: \"positive\",\n * // }\n * ```\n */\nexport class StateGraph<\n SD extends StateDefinitionInit | unknown,\n S = ExtractStateType<SD>,\n U = ExtractUpdateType<SD, S>,\n N extends string = typeof START,\n I extends StateDefinitionInit = ExtractStateDefinition<SD>,\n O extends StateDefinitionInit = ExtractStateDefinition<SD>,\n C extends StateDefinitionInit = StateDefinition,\n NodeReturnType = unknown,\n InterruptType = unknown,\n WriterType = unknown,\n> extends Graph<N, S, U, StateGraphNodeSpec<S, U>, ToStateDefinition<C>> {\n channels: Record<string, BaseChannel> = {};\n\n // TODO: this doesn't dedupe edges as in py, so worth fixing at some point\n waitingEdges: Set<[N[], N]> = new Set();\n\n /** @internal */\n _schemaDefinition: StateDefinition;\n\n /** @internal */\n _schemaRuntimeDefinition: InteropZodObject | AnyStateSchema | undefined;\n\n /** @internal */\n _inputDefinition: I;\n\n /** @internal */\n _inputRuntimeDefinition:\n | InteropZodObject\n | AnyStateSchema\n | PartialStateSchema\n | undefined;\n\n /** @internal */\n _outputDefinition: O;\n\n /** @internal */\n _outputRuntimeDefinition: InteropZodObject | AnyStateSchema | undefined;\n\n /**\n * Map schemas to managed values\n * @internal\n */\n _schemaDefinitions = new Map();\n\n /** @internal */\n _metaRegistry: SchemaMetaRegistry = schemaMetaRegistry;\n\n /** @internal Used only for typing. */\n _configSchema: ToStateDefinition<C> | undefined;\n\n /** @internal */\n _configRuntimeSchema: InteropZodObject | undefined;\n\n /** @internal */\n _interrupt: InterruptType;\n\n /** @internal */\n _writer: WriterType;\n\n declare Node: StrictNodeAction<S, U, C, N, InterruptType, WriterType>;\n\n /**\n * Create a new StateGraph for building stateful, multi-step workflows.\n *\n * Accepts state definitions via `Annotation.Root`, `StateSchema`, or Zod schemas.\n *\n * @example Direct schema\n * ```ts\n * const StateAnnotation = Annotation.Root({\n * messages: Annotation<string[]>({ reducer: (a, b) => [...a, ...b] }),\n * });\n * const graph = new StateGraph(StateAnnotation);\n * ```\n *\n * @example Direct schema with input/output filtering\n * ```ts\n * const graph = new StateGraph(StateAnnotation, {\n * input: InputSchema,\n * output: OutputSchema,\n * });\n * ```\n *\n * @example Object pattern with state, input, output\n * ```ts\n * const graph = new StateGraph({\n * state: FullStateSchema,\n * input: InputSchema,\n * output: OutputSchema,\n * });\n * ```\n *\n * @example Input/output only (state inferred from input)\n * ```ts\n * const graph = new StateGraph({\n * input: InputAnnotation,\n * output: OutputAnnotation,\n * });\n * ```\n */\n constructor(\n state: SD extends StateDefinitionInit ? SD : never,\n options?:\n | C\n | AnnotationRoot<ToStateDefinition<C>>\n | StateGraphOptions<I, O, C, N, InterruptType, WriterType>\n );\n\n constructor(\n fields: SD extends StateDefinition\n ? StateGraphArgsWithInputOutputSchemas<SD, ToStateDefinition<O>>\n : never,\n contextSchema?: C | AnnotationRoot<ToStateDefinition<C>>\n );\n\n constructor(\n fields: SD extends StateDefinition\n ?\n | AnnotationRoot<SD>\n | StateGraphArgsWithStateSchema<\n SD,\n ToStateDefinition<I>,\n ToStateDefinition<O>\n >\n : never,\n contextSchema?: C | AnnotationRoot<ToStateDefinition<C>>\n );\n\n constructor(\n init: Omit<\n StateGraphInit<\n SD extends StateDefinitionInit ? SD : StateDefinitionInit,\n SD extends StateDefinitionInit ? SD : StateDefinitionInit,\n O,\n C extends ContextSchemaInit ? C : undefined,\n N,\n InterruptType,\n WriterType\n >,\n \"state\" | \"stateSchema\" | \"input\"\n > & {\n input: SD extends StateDefinitionInit ? SD : never;\n state?: never;\n stateSchema?: never;\n },\n contextSchema?: C | AnnotationRoot<ToStateDefinition<C>>\n );\n\n constructor(\n init: StateGraphInit<\n SD extends StateDefinitionInit ? SD : StateDefinitionInit,\n I,\n O,\n C extends ContextSchemaInit ? C : undefined,\n N,\n InterruptType,\n WriterType\n >\n );\n\n /** @deprecated Use `Annotation.Root`, `StateSchema`, or Zod schemas instead. */\n constructor(\n fields: StateGraphArgs<S>,\n contextSchema?: C | AnnotationRoot<ToStateDefinition<C>>\n );\n\n constructor(\n stateOrInit:\n | StateDefinitionInit\n | StateGraphInit<StateDefinitionInit, I, O>\n | StateGraphArgs<S>,\n options?:\n | C\n | AnnotationRoot<ToStateDefinition<C>>\n | StateGraphOptions<\n I,\n O,\n C extends ContextSchemaInit ? C : undefined,\n N,\n InterruptType,\n WriterType\n >\n ) {\n super();\n\n // Normalize all input patterns to StateGraphInit format\n const init = this._normalizeToStateGraphInit(stateOrInit, options);\n\n // Resolve state schema: state > stateSchema (deprecated) > input\n const stateSchema = init.state ?? init.stateSchema ?? init.input;\n if (!stateSchema) {\n throw new StateGraphInputError();\n }\n\n // Get channel definitions from the schema (may contain channel factories)\n const stateChannelDef = this._getChannelsFromSchema(stateSchema);\n\n // Set schema definitions (these may contain channel factories)\n this._schemaDefinition = stateChannelDef;\n\n // Set runtime definitions for validation\n if (StateSchema.isInstance(stateSchema)) {\n this._schemaRuntimeDefinition = stateSchema;\n } else if (isInteropZodObject(stateSchema)) {\n this._schemaRuntimeDefinition = stateSchema;\n }\n\n // Set input runtime definition\n if (init.input) {\n if (StateSchema.isInstance(init.input)) {\n this._inputRuntimeDefinition = init.input;\n } else if (isInteropZodObject(init.input)) {\n this._inputRuntimeDefinition = init.input;\n } else {\n this._inputRuntimeDefinition = PartialStateSchema;\n }\n } else {\n this._inputRuntimeDefinition = PartialStateSchema;\n }\n\n // Set output runtime definition\n if (init.output) {\n if (StateSchema.isInstance(init.output)) {\n this._outputRuntimeDefinition = init.output;\n } else if (isInteropZodObject(init.output)) {\n this._outputRuntimeDefinition = init.output;\n } else {\n this._outputRuntimeDefinition = this._schemaRuntimeDefinition;\n }\n } else {\n this._outputRuntimeDefinition = this._schemaRuntimeDefinition;\n }\n\n // Set input/output definitions (default to state)\n const inputChannelDef = init.input\n ? this._getChannelsFromSchema(init.input)\n : stateChannelDef;\n const outputChannelDef = init.output\n ? (this._getChannelsFromSchema(init.output) as O)\n : stateChannelDef;\n this._inputDefinition = inputChannelDef as I;\n this._outputDefinition = outputChannelDef as O;\n\n // Add all schemas (_addSchema instantiates channel factories and populates this.channels)\n this._addSchema(this._schemaDefinition);\n this._addSchema(this._inputDefinition);\n this._addSchema(this._outputDefinition);\n\n // Handle context schema\n if (init.context) {\n if (isInteropZodObject(init.context)) {\n this._configRuntimeSchema = init.context;\n }\n }\n\n // Handle interrupt and writer\n this._interrupt = init.interrupt as InterruptType;\n this._writer = init.writer as WriterType;\n }\n\n /**\n * Normalize all constructor input patterns to a unified StateGraphInit object.\n * @internal\n */\n private _normalizeToStateGraphInit(\n stateOrInit: unknown,\n options?: unknown\n ): StateGraphInit<StateDefinitionInit, I, O, C> {\n // Check if already StateGraphInit format\n if (isStateGraphInit(stateOrInit)) {\n // Second arg can be either a direct context schema or an options object\n if (isInteropZodObject(options) || AnnotationRoot.isInstance(options)) {\n return {\n ...stateOrInit,\n context: options as C,\n };\n }\n // Merge any 2nd arg options\n const opts = options as StateGraphOptions<I, O> | undefined;\n return {\n ...stateOrInit,\n input: stateOrInit.input ?? opts?.input,\n output: stateOrInit.output ?? opts?.output,\n context: stateOrInit.context ?? opts?.context,\n interrupt: stateOrInit.interrupt ?? opts?.interrupt,\n writer: stateOrInit.writer ?? opts?.writer,\n nodes: stateOrInit.nodes ?? opts?.nodes,\n } as StateGraphInit<StateDefinitionInit, I, O, C>;\n }\n\n // Check if direct schema (StateSchema, Zod, Annotation, StateDefinition)\n if (isStateDefinitionInit(stateOrInit)) {\n // Second arg can be either a direct context schema or an options object\n if (isInteropZodObject(options) || AnnotationRoot.isInstance(options)) {\n return {\n state: stateOrInit,\n context: options as C,\n };\n }\n const opts = options as StateGraphOptions<I, O> | undefined;\n return {\n state: stateOrInit as StateDefinitionInit,\n input: opts?.input as I,\n output: opts?.output as O,\n context: opts?.context,\n interrupt: opts?.interrupt,\n writer: opts?.writer,\n nodes: opts?.nodes,\n };\n }\n\n // Check for legacy { channels } format\n if (isStateGraphArgs(stateOrInit as StateGraphArgs<S>)) {\n const legacyArgs = stateOrInit as StateGraphArgs<S>;\n const spec = _getChannels(legacyArgs.channels);\n return {\n state: spec as StateDefinitionInit,\n };\n }\n\n throw new StateGraphInputError();\n }\n\n /**\n * Convert any supported schema type to a StateDefinition (channel map).\n * @internal\n */\n private _getChannelsFromSchema(schema: StateDefinitionInit): StateDefinition {\n if (StateSchema.isInstance(schema)) {\n return schema.getChannels();\n }\n\n if (isInteropZodObject(schema)) {\n return this._metaRegistry.getChannelsForSchema(schema);\n }\n\n // AnnotationRoot - has .spec property that is the StateDefinition\n if (\n typeof schema === \"object\" &&\n \"lc_graph_name\" in schema &&\n (schema as { lc_graph_name: unknown }).lc_graph_name === \"AnnotationRoot\"\n ) {\n return (schema as AnnotationRoot<StateDefinition>).spec;\n }\n\n // StateDefinition (raw channel map) - return as-is\n if (\n typeof schema === \"object\" &&\n !Array.isArray(schema) &&\n Object.keys(schema).length > 0\n ) {\n return schema as StateDefinition;\n }\n\n throw new StateGraphInputError(\n \"Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.\"\n );\n }\n\n get allEdges(): Set<[string, string]> {\n return new Set([\n ...this.edges,\n ...Array.from(this.waitingEdges).flatMap(([starts, end]) =>\n starts.map((start) => [start, end] as [string, string])\n ),\n ]);\n }\n\n _addSchema(stateDefinition: StateDefinitionInit) {\n if (this._schemaDefinitions.has(stateDefinition)) {\n return;\n }\n // TODO: Support managed values\n this._schemaDefinitions.set(stateDefinition, stateDefinition);\n for (const [key, val] of Object.entries(stateDefinition)) {\n let channel;\n if (typeof val === \"function\") {\n channel = val();\n } else {\n channel = val;\n }\n if (this.channels[key] !== undefined) {\n if (!this.channels[key].equals(channel)) {\n if (channel.lc_graph_name !== \"LastValue\") {\n throw new Error(\n `Channel \"${key}\" already exists with a different type.`\n );\n }\n }\n } else {\n this.channels[key] = channel;\n }\n }\n }\n\n override addNode<\n K extends string,\n NodeMap extends Record<K, NodeAction<S, U, C, InterruptType, WriterType>>,\n >(\n nodes: NodeMap\n ): StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<\n NodeReturnType,\n {\n [key in keyof NodeMap]: NodeMap[key] extends NodeAction<\n S,\n infer U,\n C,\n InterruptType,\n WriterType\n >\n ? U\n : never;\n }\n >\n >;\n\n override addNode<K extends string, NodeInput = S, NodeOutput extends U = U>(\n nodes: [\n key: K,\n action: NodeAction<NodeInput, NodeOutput, C, InterruptType, WriterType>,\n options?: StateGraphAddNodeOptions,\n ][]\n ): StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<NodeReturnType, { [key in K]: NodeOutput }>\n >;\n\n override addNode<\n K extends string,\n InputSchema extends StateDefinitionInit,\n NodeOutput extends U = U,\n >(\n key: K,\n action: NodeAction<\n ExtractStateType<InputSchema>,\n NodeOutput,\n C,\n InterruptType,\n WriterType\n >,\n options: StateGraphAddNodeOptions<N | K, InputSchema>\n ): StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<NodeReturnType, { [key in K]: NodeOutput }>\n >;\n\n override addNode<\n K extends string,\n InputSchema extends StateDefinitionInit,\n NodeOutput extends U = U,\n >(\n key: K,\n action: NodeAction<\n ExtractStateType<InputSchema>,\n NodeOutput,\n C,\n InterruptType,\n WriterType\n >,\n options: StateGraphAddNodeOptions<N | K, InputSchema>\n ): StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<NodeReturnType, { [key in K]: NodeOutput }>\n >;\n\n override addNode<K extends string, NodeInput = S, NodeOutput extends U = U>(\n key: K,\n action: NodeAction<NodeInput, NodeOutput, C, InterruptType, WriterType>,\n options?: StateGraphAddNodeOptions\n ): StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<NodeReturnType, { [key in K]: NodeOutput }>\n >;\n\n override addNode<K extends string, NodeInput = S>(\n key: K,\n action: NodeAction<NodeInput, U, C, InterruptType, WriterType>,\n options?: StateGraphAddNodeOptions\n ): StateGraph<SD, S, U, N | K, I, O, C, NodeReturnType>;\n\n override addNode<K extends string, NodeInput = S, NodeOutput extends U = U>(\n ...args:\n | [\n key: K,\n action: NodeAction<\n NodeInput,\n NodeOutput,\n C,\n InterruptType,\n WriterType\n >,\n options?: StateGraphAddNodeOptions,\n ]\n | [\n nodes:\n | Record<K, NodeAction<NodeInput, U, C, InterruptType, WriterType>>\n | [\n key: K,\n action: NodeAction<NodeInput, U, C, InterruptType, WriterType>,\n options?: StateGraphAddNodeOptions,\n ][],\n ]\n ): StateGraph<SD, S, U, N | K, I, O, C> {\n function isMultipleNodes(\n args: unknown[]\n ): args is [\n nodes:\n | Record<K, NodeAction<NodeInput, U, C, InterruptType, WriterType>>\n | [\n key: K,\n action: NodeAction<NodeInput, U, C, InterruptType, WriterType>,\n options?: AddNodeOptions,\n ][],\n ] {\n return args.length >= 1 && typeof args[0] !== \"string\";\n }\n\n const nodes = (\n isMultipleNodes(args) // eslint-disable-line no-nested-ternary\n ? Array.isArray(args[0])\n ? args[0]\n : Object.entries(args[0]).map(([key, action]) => [key, action])\n : [[args[0], args[1], args[2]]]\n ) as [\n K,\n NodeAction<NodeInput, U, C, InterruptType, WriterType>,\n StateGraphAddNodeOptions | undefined,\n ][];\n\n if (nodes.length === 0) {\n throw new Error(\"No nodes provided in `addNode`\");\n }\n\n for (const [key, action, options] of nodes) {\n if (key in this.channels) {\n throw new Error(\n `${key} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`\n );\n }\n\n for (const reservedChar of [\n CHECKPOINT_NAMESPACE_SEPARATOR,\n CHECKPOINT_NAMESPACE_END,\n ]) {\n if (key.includes(reservedChar)) {\n throw new Error(\n `\"${reservedChar}\" is a reserved character and is not allowed in node names.`\n );\n }\n }\n this.warnIfCompiled(\n `Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`\n );\n\n if (key in this.nodes) {\n throw new Error(`Node \\`${key}\\` already present.`);\n }\n if (key === END || key === START) {\n throw new Error(`Node \\`${key}\\` is reserved.`);\n }\n\n let inputSpec: StateDefinition = this._schemaDefinition;\n if (options?.input !== undefined) {\n inputSpec = this._getChannelsFromSchema(options.input);\n }\n this._addSchema(inputSpec);\n\n let runnable;\n if (Runnable.isRunnable(action)) {\n runnable = action;\n } else if (typeof action === \"function\") {\n runnable = new RunnableCallable({\n func: action,\n name: key,\n trace: false,\n });\n } else {\n runnable = _coerceToRunnable(action);\n }\n\n let cachePolicy = options?.cachePolicy;\n if (typeof cachePolicy === \"boolean\") {\n cachePolicy = cachePolicy ? {} : undefined;\n }\n\n const nodeSpec: StateGraphNodeSpec<S, U> = {\n runnable: runnable as unknown as Runnable<S, U>,\n retryPolicy: options?.retryPolicy,\n cachePolicy,\n metadata: options?.metadata,\n input: inputSpec ?? this._schemaDefinition,\n subgraphs: isPregelLike(runnable)\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [runnable as any]\n : options?.subgraphs,\n ends: options?.ends,\n defer: options?.defer,\n };\n\n this.nodes[key as unknown as N] = nodeSpec;\n }\n\n return this as StateGraph<SD, S, U, N | K, I, O, C>;\n }\n\n override addEdge(\n startKey: typeof START | N | N[],\n endKey: N | typeof END\n ): this {\n if (typeof startKey === \"string\") {\n return super.addEdge(startKey, endKey);\n }\n\n if (this.compiled) {\n console.warn(\n \"Adding an edge to a graph that has already been compiled. This will \" +\n \"not be reflected in the compiled graph.\"\n );\n }\n\n for (const start of startKey) {\n if (start === END) {\n throw new Error(\"END cannot be a start node\");\n }\n if (!Object.keys(this.nodes).some((node) => node === start)) {\n throw new Error(`Need to add a node named \"${start}\" first`);\n }\n }\n if (endKey === END) {\n throw new Error(\"END cannot be an end node\");\n }\n if (!Object.keys(this.nodes).some((node) => node === endKey)) {\n throw new Error(`Need to add a node named \"${endKey}\" first`);\n }\n\n this.waitingEdges.add([startKey, endKey]);\n\n return this;\n }\n\n addSequence<K extends string, NodeInput = S, NodeOutput extends U = U>(\n nodes: [\n key: K,\n action: NodeAction<NodeInput, NodeOutput, C, InterruptType, WriterType>,\n options?: StateGraphAddNodeOptions,\n ][]\n ): StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<NodeReturnType, { [key in K]: NodeOutput }>\n >;\n\n addSequence<\n K extends string,\n NodeMap extends Record<K, NodeAction<S, U, C, InterruptType, WriterType>>,\n >(\n nodes: NodeMap\n ): StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<\n NodeReturnType,\n {\n [key in keyof NodeMap]: NodeMap[key] extends NodeAction<\n S,\n infer U,\n C,\n InterruptType,\n WriterType\n >\n ? U\n : never;\n }\n >\n >;\n\n addSequence<K extends string, NodeInput = S, NodeOutput extends U = U>(\n nodes:\n | [\n key: K,\n action: NodeAction<\n NodeInput,\n NodeOutput,\n C,\n InterruptType,\n WriterType\n >,\n options?: StateGraphAddNodeOptions,\n ][]\n | Record<\n K,\n NodeAction<NodeInput, NodeOutput, C, InterruptType, WriterType>\n >\n ): StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<NodeReturnType, { [key in K]: NodeOutput }>\n > {\n const parsedNodes = Array.isArray(nodes) ? nodes : Object.entries(nodes);\n\n if (parsedNodes.length === 0) {\n throw new Error(\"Sequence requires at least one node.\");\n }\n\n let previousNode: N | undefined;\n for (const [key, action, options] of parsedNodes) {\n if (key in this.nodes) {\n throw new Error(\n `Node names must be unique: node with the name \"${key}\" already exists.`\n );\n }\n\n const validKey = key as unknown as N;\n this.addNode(\n validKey,\n action as NodeAction<S, U, C, InterruptType, WriterType>,\n options\n );\n if (previousNode != null) {\n this.addEdge(previousNode, validKey);\n }\n\n previousNode = validKey;\n }\n\n return this as StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<NodeReturnType, { [key in K]: NodeOutput }>\n >;\n }\n\n override compile<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const TTransformers extends ReadonlyArray<() => StreamTransformer<any>> =\n [],\n >({\n checkpointer,\n store,\n cache,\n interruptBefore,\n interruptAfter,\n name,\n description,\n transformers,\n }: {\n checkpointer?: BaseCheckpointSaver | boolean;\n store?: BaseStore;\n cache?: BaseCache;\n interruptBefore?: N[] | All;\n interruptAfter?: N[] | All;\n name?: string;\n description?: string;\n /**\n * Stream transformer factories baked into the compiled graph. These run\n * automatically for every `streamEvents(..., { version: \"v3\" })` call,\n * before any call-site transformers.\n */\n transformers?: TTransformers;\n } = {}): CompiledStateGraph<\n Prettify<S>,\n Prettify<U>,\n N,\n I,\n O,\n C,\n NodeReturnType,\n InterruptType,\n WriterType,\n TTransformers\n > {\n // validate the graph\n this.validate([\n ...(Array.isArray(interruptBefore) ? interruptBefore : []),\n ...(Array.isArray(interruptAfter) ? interruptAfter : []),\n ]);\n\n // prepare output channels\n const outputKeys = Object.keys(\n this._schemaDefinitions.get(this._outputDefinition)\n );\n const outputChannels =\n outputKeys.length === 1 && outputKeys[0] === ROOT ? ROOT : outputKeys;\n\n const streamKeys = Object.keys(this.channels);\n const streamChannels =\n streamKeys.length === 1 && streamKeys[0] === ROOT ? ROOT : streamKeys;\n\n const userInterrupt = this._interrupt;\n // create empty compiled graph\n const compiled = new CompiledStateGraph<\n S,\n U,\n N,\n I,\n O,\n C,\n NodeReturnType,\n InterruptType,\n WriterType,\n TTransformers\n >({\n builder: this,\n checkpointer,\n interruptAfter,\n interruptBefore,\n autoValidate: false,\n nodes: {} as Record<N | typeof START, PregelNode<S, U>>,\n channels: {\n ...this.channels,\n [START]: new EphemeralValue(),\n } as Record<N | typeof START | typeof END | string, BaseChannel>,\n inputChannels: START,\n outputChannels,\n streamChannels,\n streamMode: \"updates\",\n store,\n cache,\n name,\n description,\n userInterrupt,\n streamTransformers: transformers,\n });\n\n // attach nodes, edges and branches\n compiled.attachNode(START);\n for (const [key, node] of Object.entries<StateGraphNodeSpec<S, U>>(\n this.nodes\n )) {\n compiled.attachNode(key as N, node);\n }\n compiled.attachBranch(START, SELF, _getControlBranch() as Branch<S, N>, {\n withReader: false,\n });\n for (const [key] of Object.entries<StateGraphNodeSpec<S, U>>(this.nodes)) {\n compiled.attachBranch(\n key as N,\n SELF,\n _getControlBranch() as Branch<S, N>,\n {\n withReader: false,\n }\n );\n }\n for (const [start, end] of this.edges) {\n compiled.attachEdge(start, end);\n }\n for (const [starts, end] of this.waitingEdges) {\n compiled.attachEdge(starts, end);\n }\n for (const [start, branches] of Object.entries(this.branches)) {\n for (const [name, branch] of Object.entries(branches)) {\n compiled.attachBranch(start as N, name, branch);\n }\n }\n\n return compiled.validate();\n }\n}\n\nfunction _getChannels<Channels extends Record<string, unknown> | unknown>(\n schema: StateGraphArgs<Channels>[\"channels\"]\n): Record<string, BaseChannel> {\n const channels: Record<string, BaseChannel> = {};\n for (const [name, val] of Object.entries(schema)) {\n if (name === ROOT) {\n channels[name] = getChannel<Channels>(val as SingleReducer<Channels>);\n } else {\n const key = name as keyof Channels;\n channels[name] = getChannel<Channels[typeof key]>(\n val as SingleReducer<Channels[typeof key]>\n );\n }\n }\n return channels;\n}\n\n/**\n * Final result from building and compiling a {@link StateGraph}.\n * Should not be instantiated directly, only using the StateGraph `.compile()`\n * instance method.\n *\n * @typeParam S - The full state type representing the complete shape of your graph's\n * state after all reducers have been applied. This is the type you receive when\n * reading state in nodes or after invoking the graph.\n *\n * @typeParam U - The update type representing what nodes can return to modify state.\n * Typically a partial of the state type, allowing nodes to update only specific fields.\n * Can also include {@link Command} objects for advanced control flow.\n *\n * @typeParam N - Union of all node names in the graph (e.g., `\"agent\" | \"tool\"`).\n * Used for type-safe routing with {@link Command.goto} and edge definitions.\n *\n * @typeParam I - The input schema definition. Determines what shape of data the graph\n * accepts when invoked. Defaults to the main state schema if not explicitly set.\n *\n * @typeParam O - The output schema definition. Determines what shape of data the graph\n * returns after execution. Defaults to the main state schema if not explicitly set.\n *\n * @typeParam C - The config/context schema definition. Defines additional configuration\n * that can be passed to the graph at runtime via {@link LangGraphRunnableConfig}.\n *\n * @typeParam NodeReturnType - Constrains what types nodes in this graph can return.\n * Useful for enforcing consistent return patterns across all nodes.\n *\n * @typeParam InterruptType - The type of values that can be passed when resuming from\n * an {@link interrupt}. Used with human-in-the-loop patterns.\n *\n * @typeParam WriterType - The type for custom stream writers. Used with the `writer`\n * option to enable typed custom streaming from within nodes.\n */\nexport class CompiledStateGraph<\n S,\n U,\n N extends string = typeof START,\n I extends StateDefinitionInit = StateDefinition,\n O extends StateDefinitionInit = StateDefinition,\n C extends StateDefinitionInit = StateDefinition,\n NodeReturnType = unknown,\n InterruptType = unknown,\n WriterType = unknown,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TStreamTransformers extends ReadonlyArray<() => StreamTransformer<any>> = [],\n> extends CompiledGraph<\n N,\n S,\n U,\n ExtractStateType<C>,\n ExtractUpdateType<I, ExtractStateType<I>>,\n ExtractStateType<O>,\n NodeReturnType,\n CommandInstance<InferInterruptResumeType<InterruptType>, Prettify<U>, N>,\n InferWriterType<WriterType>,\n TStreamTransformers\n> {\n declare builder: StateGraph<unknown, S, U, N, I, O, C, NodeReturnType>;\n\n /**\n * The description of the compiled graph.\n * This is used by the supervisor agent to describe the handoff to the agent.\n */\n description?: string;\n\n /** @internal */\n _metaRegistry: SchemaMetaRegistry = schemaMetaRegistry;\n\n constructor({\n description,\n ...rest\n }: { description?: string } & ConstructorParameters<\n typeof CompiledGraph<\n N,\n S,\n U,\n ExtractStateType<C>,\n ExtractUpdateType<I, ExtractStateType<I>>,\n ExtractStateType<O>,\n NodeReturnType,\n CommandInstance<InferInterruptResumeType<InterruptType>, Prettify<U>, N>,\n InferWriterType<WriterType>,\n TStreamTransformers\n >\n >[0]) {\n super(rest);\n this.description = description;\n }\n\n attachNode(key: typeof START, node?: never): void;\n\n attachNode(key: N, node: StateGraphNodeSpec<S, U>): void;\n\n attachNode(key: N | typeof START, node?: StateGraphNodeSpec<S, U>): void {\n let outputKeys: string[];\n if (key === START) {\n // Get input schema keys excluding managed values\n outputKeys = Object.entries(\n this.builder._schemaDefinitions.get(this.builder._inputDefinition)\n ).map(([k]) => k);\n } else {\n outputKeys = Object.keys(this.builder.channels);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function _getRoot(input: unknown): [string, any][] | null {\n if (isCommand(input)) {\n if (input.graph === Command.PARENT) {\n return null;\n }\n return input._updateAsTuples();\n } else if (\n Array.isArray(input) &&\n input.length > 0 &&\n input.some((i) => isCommand(i))\n ) {\n const updates: [string, unknown][] = [];\n for (const i of input) {\n if (isCommand(i)) {\n if (i.graph === Command.PARENT) {\n continue;\n }\n updates.push(...i._updateAsTuples());\n } else {\n updates.push([ROOT, i]);\n }\n }\n return updates;\n } else if (input != null) {\n return [[ROOT, input]];\n }\n return null;\n }\n\n // to avoid name collision below\n const nodeKey = key;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function _getUpdates(input: U): [string, any][] | null {\n if (!input) {\n return null;\n } else if (isCommand(input)) {\n if (input.graph === Command.PARENT) {\n return null;\n }\n return input._updateAsTuples().filter(([k]) => outputKeys.includes(k));\n } else if (\n Array.isArray(input) &&\n input.length > 0 &&\n input.some(isCommand)\n ) {\n const updates: [string, unknown][] = [];\n for (const item of input) {\n if (isCommand(item)) {\n if (item.graph === Command.PARENT) {\n continue;\n }\n updates.push(\n ...item._updateAsTuples().filter(([k]) => outputKeys.includes(k))\n );\n } else {\n const itemUpdates = _getUpdates(item);\n if (itemUpdates) {\n updates.push(...(itemUpdates ?? []));\n }\n }\n }\n return updates;\n } else if (typeof input === \"object\" && !Array.isArray(input)) {\n return Object.entries(input).filter(([k]) => outputKeys.includes(k));\n } else {\n const typeofInput = Array.isArray(input) ? \"array\" : typeof input;\n throw new InvalidUpdateError(\n `Expected node \"${nodeKey.toString()}\" to return an object or an array containing at least one Command object, received ${typeofInput}`,\n {\n lc_error_code: \"INVALID_GRAPH_NODE_RETURN_VALUE\",\n }\n );\n }\n }\n\n const stateWriteEntries: (ChannelWriteTupleEntry | ChannelWriteEntry)[] = [\n {\n value: PASSTHROUGH,\n mapper: new RunnableCallable({\n func:\n outputKeys.length && outputKeys[0] === ROOT\n ? _getRoot\n : _getUpdates,\n trace: false,\n recurse: false,\n }),\n },\n ];\n\n // add node and output channel\n if (key === START) {\n this.nodes[key] = new PregelNode<S, U>({\n tags: [TAG_HIDDEN],\n triggers: [START],\n channels: [START],\n writers: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])],\n });\n } else {\n const inputDefinition = node?.input ?? this.builder._schemaDefinition;\n const inputValues = Object.fromEntries(\n Object.keys(this.builder._schemaDefinitions.get(inputDefinition)).map(\n (k) => [k, k]\n )\n );\n const isSingleInput =\n Object.keys(inputValues).length === 1 && ROOT in inputValues;\n const branchChannel = `branch:to:${key}` as string | N;\n this.channels[branchChannel] = node?.defer\n ? new LastValueAfterFinish()\n : new EphemeralValue(false);\n this.nodes[key] = new PregelNode<S, U>({\n triggers: [branchChannel],\n // read state keys\n channels: isSingleInput ? Object.keys(inputValues) : inputValues,\n // publish to state keys\n writers: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])],\n mapper: isSingleInput\n ? undefined\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (input: Record<string, any>) => {\n return Object.fromEntries(\n Object.entries(input).filter(([k]) => k in inputValues)\n );\n },\n bound: node?.runnable,\n metadata: node?.metadata,\n retryPolicy: node?.retryPolicy,\n cachePolicy: node?.cachePolicy,\n subgraphs: node?.subgraphs,\n ends: node?.ends,\n });\n }\n }\n\n attachEdge(starts: N | N[] | \"__start__\", end: N | \"__end__\"): void {\n if (end === END) return;\n if (typeof starts === \"string\") {\n this.nodes[starts].writers.push(\n new ChannelWrite(\n [{ channel: `branch:to:${end}`, value: null }],\n [TAG_HIDDEN]\n )\n );\n } else if (Array.isArray(starts)) {\n const channelName = `join:${starts.join(\"+\")}:${end}`;\n // register channel\n this.channels[channelName as string | N] = this.builder.nodes[end].defer\n ? new NamedBarrierValueAfterFinish(new Set(starts))\n : new NamedBarrierValue(new Set(starts));\n // subscribe to channel\n this.nodes[end].triggers.push(channelName);\n // publish to channel\n for (const start of starts) {\n this.nodes[start].writers.push(\n new ChannelWrite(\n [{ channel: channelName, value: start }],\n [TAG_HIDDEN]\n )\n );\n }\n }\n }\n\n attachBranch(\n start: N | typeof START,\n _: string,\n branch: Branch<S, N>,\n options: { withReader?: boolean } = { withReader: true }\n ): void {\n const branchWriter = async (\n packets: (string | Send)[],\n config: LangGraphRunnableConfig\n ) => {\n const filteredPackets = packets.filter((p) => p !== END);\n if (!filteredPackets.length) return;\n\n const writes: (ChannelWriteEntry | Send)[] = filteredPackets.map((p) => {\n if (_isSend(p)) return p;\n return { channel: p === END ? p : `branch:to:${p}`, value: start };\n });\n await ChannelWrite.doWrite(\n { ...config, tags: (config.tags ?? []).concat([TAG_HIDDEN]) },\n writes\n );\n };\n // attach branch publisher\n this.nodes[start].writers.push(\n branch.run(\n branchWriter,\n // reader\n options.withReader\n ? (config) =>\n ChannelRead.doRead<S>(\n config,\n this.streamChannels ?? this.outputChannels,\n true\n )\n : undefined\n )\n );\n }\n\n protected async _validateInput(\n input: ExtractUpdateType<I, ExtractStateType<I>>\n ): Promise<ExtractUpdateType<I, ExtractStateType<I>>> {\n if (input == null) return input;\n\n const inputDef = this.builder._inputRuntimeDefinition;\n const schemaDef = this.builder._schemaRuntimeDefinition;\n\n // Determine which schema to use for validation\n // Priority: inputDef (if it's a validatable schema), otherwise fall back to schemaDef\n\n // Handle StateSchema validation for input schema\n if (StateSchema.isInstance(inputDef)) {\n if (isCommand(input)) {\n const parsedInput = input;\n if (input.update) {\n parsedInput.update = await inputDef.validateInput(\n Array.isArray(input.update)\n ? Object.fromEntries(input.update)\n : input.update\n );\n }\n return parsedInput;\n }\n return await inputDef.validateInput(input);\n }\n\n // Handle StateSchema validation for state schema (when input is partial state)\n if (inputDef === PartialStateSchema && StateSchema.isInstance(schemaDef)) {\n if (isCommand(input)) {\n const parsedInput = input;\n if (input.update) {\n parsedInput.update = await schemaDef.validateInput(\n Array.isArray(input.update)\n ? Object.fromEntries(input.update)\n : input.update\n );\n }\n return parsedInput;\n }\n return await schemaDef.validateInput(input);\n }\n\n // Handle InteropZodObject validation\n const schema = (() => {\n const apply = (schema: InteropZodObject | undefined) => {\n if (schema == null) return undefined;\n return this._metaRegistry.getExtendedChannelSchemas(schema, {\n withReducerSchema: true,\n });\n };\n\n if (isInteropZodObject(inputDef)) return apply(inputDef);\n if (inputDef === PartialStateSchema) {\n if (isInteropZodObject(schemaDef)) {\n return interopZodObjectPartial(apply(schemaDef)!);\n }\n return undefined;\n }\n return undefined;\n })();\n\n if (isCommand(input)) {\n const parsedInput = input;\n if (input.update && schema != null)\n parsedInput.update = interopParse(schema, input.update);\n return parsedInput;\n }\n if (schema != null) return interopParse(schema, input);\n return input;\n }\n\n public isInterrupted(input: unknown): input is {\n [INTERRUPT]: Interrupt<InferInterruptInputType<InterruptType>>[];\n } {\n return isInterrupted(input);\n }\n\n protected async _validateContext(\n config: Partial<Record<string, unknown>>\n ): Promise<Partial<Record<string, unknown>>> {\n const configSchema = this.builder._configRuntimeSchema;\n if (isInteropZodObject(configSchema)) interopParse(configSchema, config);\n return config;\n }\n}\n\n/**\n * Check if value is a legacy StateGraphArgs with channels.\n * @internal\n * @deprecated Use StateGraphInit instead\n */\nfunction isStateGraphArgs<Channels extends object | unknown>(\n obj: unknown | StateGraphArgs<Channels>\n): obj is StateGraphArgs<Channels> {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n (obj as StateGraphArgs<Channels>).channels !== undefined\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _controlBranch(value: any): (string | Send)[] {\n if (_isSend(value)) {\n return [value];\n }\n const commands = [];\n if (isCommand(value)) {\n commands.push(value);\n } else if (Array.isArray(value)) {\n commands.push(...value.filter(isCommand));\n }\n const destinations: (string | Send)[] = [];\n\n for (const command of commands) {\n if (command.graph === Command.PARENT) {\n throw new ParentCommand(command);\n }\n\n if (_isSend(command.goto)) {\n destinations.push(command.goto);\n } else if (typeof command.goto === \"string\") {\n destinations.push(command.goto);\n } else {\n if (Array.isArray(command.goto)) {\n destinations.push(...command.goto);\n }\n }\n }\n return destinations;\n}\n\nfunction _getControlBranch() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const CONTROL_BRANCH_PATH = new RunnableCallable<any, (string | Send)[]>({\n func: _controlBranch,\n tags: [TAG_HIDDEN],\n trace: false,\n recurse: false,\n name: \"<control_branch>\",\n });\n return new Branch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AS,aAAa,QAAQ,MAAM,OAAO;AACzD,UAAO;;AAET,MAAI,UAAU,KAAM,QAAO,aAAa,QAAQ,MAAM;AACtD,SAAO;;CAGT,cAAqB,OAEnB;AACA,SAAO,cAAc,MAAM;;CAG7B,MAAgB,iBACd,QAC2C;EAC3C,MAAM,eAAe,KAAK,QAAQ;AAClC,MAAI,mBAAmB,aAAa,CAAE,cAAa,cAAc,OAAO;AACxE,SAAO;;;;;;;;AASX,SAAS,iBACP,KACiC;AACjC,QACE,OAAO,QAAQ,YACf,QAAQ,QACP,IAAiC,aAAa,KAAA;;AAKnD,SAAS,eAAe,OAA+B;AACrD,KAAI,QAAQ,MAAM,CAChB,QAAO,CAAC,MAAM;CAEhB,MAAM,WAAW,EAAE;AACnB,KAAI,UAAU,MAAM,CAClB,UAAS,KAAK,MAAM;UACX,MAAM,QAAQ,MAAM,CAC7B,UAAS,KAAK,GAAG,MAAM,OAAO,UAAU,CAAC;CAE3C,MAAM,eAAkC,EAAE;AAE1C,MAAK,MAAM,WAAW,UAAU;AAC9B,MAAI,QAAQ,UAAU,QAAQ,OAC5B,OAAM,IAAI,cAAc,QAAQ;AAGlC,MAAI,QAAQ,QAAQ,KAAK,CACvB,cAAa,KAAK,QAAQ,KAAK;WACtB,OAAO,QAAQ,SAAS,SACjC,cAAa,KAAK,QAAQ,KAAK;WAE3B,MAAM,QAAQ,QAAQ,KAAK,CAC7B,cAAa,KAAK,GAAG,QAAQ,KAAK;;AAIxC,QAAO;;AAGT,SAAS,oBAAoB;AAS3B,QAAO,IAAI,OAAO,EAChB,MAR0B,IAAI,iBAAyC;EACvE,MAAM;EACN,MAAM,CAAC,WAAW;EAClB,OAAO;EACP,SAAS;EACT,MAAM;EACP,CAAC,EAGD,CAAC"}
|
|
1
|
+
{"version":3,"file":"state.js","names":[],"sources":["../../src/graph/state.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-use-before-define */\nimport { _coerceToRunnable, Runnable } from \"@langchain/core/runnables\";\nimport {\n All,\n type BaseCache,\n BaseCheckpointSaver,\n BaseStore,\n} from \"@langchain/langgraph-checkpoint\";\nimport {\n type InteropZodObject,\n interopParse,\n interopZodObjectPartial,\n isInteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport type {\n RunnableLike,\n LangGraphRunnableConfig,\n Runtime,\n} from \"../pregel/runnable_types.js\";\nimport { BaseChannel } from \"../channels/base.js\";\nimport {\n CompiledGraph,\n Graph,\n Branch,\n AddNodeOptions,\n NodeSpec,\n} from \"./graph.js\";\nimport {\n ChannelWrite,\n ChannelWriteEntry,\n ChannelWriteTupleEntry,\n PASSTHROUGH,\n} from \"../pregel/write.js\";\nimport { ChannelRead, PregelNode } from \"../pregel/read.js\";\nimport {\n NamedBarrierValue,\n NamedBarrierValueAfterFinish,\n} from \"../channels/named_barrier_value.js\";\nimport { EphemeralValue } from \"../channels/ephemeral_value.js\";\nimport { RunnableCallable } from \"../utils.js\";\nimport {\n isCommand,\n _isSend,\n CHECKPOINT_NAMESPACE_END,\n CHECKPOINT_NAMESPACE_SEPARATOR,\n Command,\n SELF,\n Send,\n START,\n END,\n TAG_HIDDEN,\n CommandInstance,\n isInterrupted,\n Interrupt,\n INTERRUPT,\n} from \"../constants.js\";\nimport {\n InvalidUpdateError,\n ParentCommand,\n StateGraphInputError,\n} from \"../errors.js\";\nimport {\n AnnotationRoot,\n getChannel,\n SingleReducer,\n StateDefinition,\n StateType,\n} from \"./annotation.js\";\nimport { StateSchema } from \"../state/index.js\";\nimport type { CachePolicy, RetryPolicy } from \"../pregel/utils/index.js\";\nimport { isPregelLike } from \"../pregel/utils/subgraph.js\";\nimport { LastValueAfterFinish } from \"../channels/last_value.js\";\nimport { type SchemaMetaRegistry, schemaMetaRegistry } from \"./zod/meta.js\";\nimport type {\n InferInterruptResumeType,\n InferInterruptInputType,\n} from \"../interrupt.js\";\nimport type { InferWriterType } from \"../writer.js\";\nimport type { AnyStateSchema } from \"../state/schema.js\";\nimport {\n ContextSchemaInit,\n ExtractStateType,\n ExtractUpdateType,\n isStateDefinitionInit,\n isStateGraphInit,\n StateGraphInit,\n StateGraphOptions,\n ToStateDefinition,\n type StateDefinitionInit,\n} from \"./types.js\";\nimport type { StreamTransformer } from \"../stream/types.js\";\n\nconst ROOT = \"__root__\";\n\nexport type ChannelReducers<Channels extends object> = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof Channels]: SingleReducer<Channels[K], any>;\n};\n\nexport interface StateGraphArgs<Channels extends object | unknown> {\n channels: Channels extends object\n ? Channels extends unknown[]\n ? ChannelReducers<{ __root__: Channels }>\n : ChannelReducers<Channels>\n : ChannelReducers<{ __root__: Channels }>;\n}\n\nexport type StateGraphNodeSpec<RunInput, RunOutput> = NodeSpec<\n RunInput,\n RunOutput\n> & {\n input?: StateDefinition;\n retryPolicy?: RetryPolicy;\n cachePolicy?: CachePolicy;\n};\n\n/**\n * Options for StateGraph.addNode() method.\n *\n * @template Nodes - Node name constraints\n * @template InputSchema - Per-node input schema type (inferred from options.input)\n */\nexport type StateGraphAddNodeOptions<\n Nodes extends string = string,\n InputSchema extends StateDefinitionInit | undefined =\n | StateDefinitionInit\n | undefined,\n> = {\n retryPolicy?: RetryPolicy;\n cachePolicy?: CachePolicy | boolean;\n input?: InputSchema;\n} & AddNodeOptions<Nodes>;\n\nexport type StateGraphArgsWithStateSchema<\n SD extends StateDefinition,\n I extends StateDefinition,\n O extends StateDefinition,\n> = {\n stateSchema: AnnotationRoot<SD>;\n input?: AnnotationRoot<I>;\n output?: AnnotationRoot<O>;\n};\n\nexport type StateGraphArgsWithInputOutputSchemas<\n SD extends StateDefinition,\n O extends StateDefinition = SD,\n> = {\n input: AnnotationRoot<SD>;\n output: AnnotationRoot<O>;\n};\n\ntype ExtractStateDefinition<T> = T extends AnyStateSchema\n ? T // Keep StateSchema as-is to preserve type information\n : T extends StateDefinitionInit\n ? ToStateDefinition<T>\n : StateDefinition;\n\ntype NodeAction<\n S,\n U,\n C extends StateDefinitionInit,\n InterruptType,\n WriterType,\n> = RunnableLike<\n S,\n U extends object ? U & Record<string, any> : U, // eslint-disable-line @typescript-eslint/no-explicit-any\n Runtime<StateType<ToStateDefinition<C>>, InterruptType, WriterType>\n>;\n\ntype StrictNodeAction<\n S,\n U,\n C extends StateDefinitionInit,\n Nodes extends string,\n InterruptType,\n WriterType,\n> = RunnableLike<\n Prettify<S>,\n | U\n | Command<\n InferInterruptResumeType<InterruptType>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n U & Record<string, any>,\n Nodes\n >,\n Runtime<StateType<ToStateDefinition<C>>, InterruptType, WriterType>\n>;\n\nconst PartialStateSchema = Symbol.for(\"langgraph.state.partial\");\ntype PartialStateSchema = typeof PartialStateSchema;\n\ntype MergeReturnType<Prev, Curr> = Prev & Curr extends infer T\n ? { [K in keyof T]: T[K] } & unknown\n : never;\n\ntype Prettify<T> = {\n [K in keyof T]: T[K];\n // eslint-disable-next-line @typescript-eslint/ban-types\n} & {};\n\n/**\n * A graph whose nodes communicate by reading and writing to a shared state.\n * Each node takes a defined `State` as input and returns a `Partial<State>`.\n *\n * Each state key can optionally be annotated with a reducer function that\n * will be used to aggregate the values of that key received from multiple nodes.\n * The signature of a reducer function is (left: Value, right: UpdateValue) => Value.\n *\n * See {@link Annotation} for more on defining state.\n *\n * After adding nodes and edges to your graph, you must call `.compile()` on it before\n * you can use it.\n *\n * @typeParam SD - The state definition used to construct the graph. Can be an\n * {@link AnnotationRoot}, {@link StateSchema}, or Zod object schema. This is the\n * primary generic from which `S` and `U` are derived.\n *\n * @typeParam S - The full state type representing the complete shape of your graph's\n * state after all reducers have been applied. Automatically inferred from `SD`.\n *\n * @typeParam U - The update type representing what nodes can return to modify state.\n * Typically a partial of the state type. Automatically inferred from `SD`.\n *\n * @typeParam N - Union of all node names in the graph (e.g., `\"agent\" | \"tool\"`).\n * Accumulated as you call `.addNode()`. Used for type-safe routing.\n *\n * @typeParam I - The input schema definition. Set via the `input` option in the\n * constructor to restrict what data the graph accepts when invoked.\n *\n * @typeParam O - The output schema definition. Set via the `output` option in the\n * constructor to restrict what data the graph returns after execution.\n *\n * @typeParam C - The config/context schema definition. Set via the `context` option\n * to define additional configuration passed at runtime.\n *\n * @typeParam NodeReturnType - Constrains what types nodes in this graph can return.\n *\n * @typeParam InterruptType - The type for {@link interrupt} resume values. Set via\n * the `interrupt` option for typed human-in-the-loop patterns.\n *\n * @typeParam WriterType - The type for custom stream writers. Set via the `writer`\n * option to enable typed custom streaming from within nodes.\n *\n * @example\n * ```ts\n * import {\n * type BaseMessage,\n * AIMessage,\n * HumanMessage,\n * } from \"@langchain/core/messages\";\n * import { StateGraph, Annotation } from \"@langchain/langgraph\";\n *\n * // Define a state with a single key named \"messages\" that will\n * // combine a returned BaseMessage or arrays of BaseMessages\n * const StateAnnotation = Annotation.Root({\n * sentiment: Annotation<string>,\n * messages: Annotation<BaseMessage[]>({\n * reducer: (left: BaseMessage[], right: BaseMessage | BaseMessage[]) => {\n * if (Array.isArray(right)) {\n * return left.concat(right);\n * }\n * return left.concat([right]);\n * },\n * default: () => [],\n * }),\n * });\n *\n * const graphBuilder = new StateGraph(StateAnnotation);\n *\n * // A node in the graph that returns an object with a \"messages\" key\n * // will update the state by combining the existing value with the returned one.\n * const myNode = (state: typeof StateAnnotation.State) => {\n * return {\n * messages: [new AIMessage(\"Some new response\")],\n * sentiment: \"positive\",\n * };\n * };\n *\n * const graph = graphBuilder\n * .addNode(\"myNode\", myNode)\n * .addEdge(\"__start__\", \"myNode\")\n * .addEdge(\"myNode\", \"__end__\")\n * .compile();\n *\n * await graph.invoke({ messages: [new HumanMessage(\"how are you?\")] });\n *\n * // {\n * // messages: [HumanMessage(\"how are you?\"), AIMessage(\"Some new response\")],\n * // sentiment: \"positive\",\n * // }\n * ```\n */\nexport class StateGraph<\n SD extends StateDefinitionInit | unknown,\n S = ExtractStateType<SD>,\n U = ExtractUpdateType<SD, S>,\n N extends string = typeof START,\n I extends StateDefinitionInit = ExtractStateDefinition<SD>,\n O extends StateDefinitionInit = ExtractStateDefinition<SD>,\n C extends StateDefinitionInit = StateDefinition,\n NodeReturnType = unknown,\n InterruptType = unknown,\n WriterType = unknown,\n> extends Graph<N, S, U, StateGraphNodeSpec<S, U>, ToStateDefinition<C>> {\n channels: Record<string, BaseChannel> = {};\n\n // TODO: this doesn't dedupe edges as in py, so worth fixing at some point\n waitingEdges: Set<[N[], N]> = new Set();\n\n /** @internal */\n _schemaDefinition: StateDefinition;\n\n /** @internal */\n _schemaRuntimeDefinition: InteropZodObject | AnyStateSchema | undefined;\n\n /** @internal */\n _inputDefinition: I;\n\n /** @internal */\n _inputRuntimeDefinition:\n | InteropZodObject\n | AnyStateSchema\n | PartialStateSchema\n | undefined;\n\n /** @internal */\n _outputDefinition: O;\n\n /** @internal */\n _outputRuntimeDefinition: InteropZodObject | AnyStateSchema | undefined;\n\n /**\n * Map schemas to managed values\n * @internal\n */\n _schemaDefinitions = new Map();\n\n /** @internal */\n _metaRegistry: SchemaMetaRegistry = schemaMetaRegistry;\n\n /** @internal Used only for typing. */\n _configSchema: ToStateDefinition<C> | undefined;\n\n /** @internal */\n _configRuntimeSchema: InteropZodObject | undefined;\n\n /** @internal */\n _interrupt: InterruptType;\n\n /** @internal */\n _writer: WriterType;\n\n declare Node: StrictNodeAction<S, U, C, N, InterruptType, WriterType>;\n\n /**\n * Create a new StateGraph for building stateful, multi-step workflows.\n *\n * Accepts state definitions via `Annotation.Root`, `StateSchema`, or Zod schemas.\n *\n * @example Direct schema\n * ```ts\n * const StateAnnotation = Annotation.Root({\n * messages: Annotation<string[]>({ reducer: (a, b) => [...a, ...b] }),\n * });\n * const graph = new StateGraph(StateAnnotation);\n * ```\n *\n * @example Direct schema with input/output filtering\n * ```ts\n * const graph = new StateGraph(StateAnnotation, {\n * input: InputSchema,\n * output: OutputSchema,\n * });\n * ```\n *\n * @example Object pattern with state, input, output\n * ```ts\n * const graph = new StateGraph({\n * state: FullStateSchema,\n * input: InputSchema,\n * output: OutputSchema,\n * });\n * ```\n *\n * @example Input/output only (state inferred from input)\n * ```ts\n * const graph = new StateGraph({\n * input: InputAnnotation,\n * output: OutputAnnotation,\n * });\n * ```\n */\n constructor(\n state: SD extends StateDefinitionInit ? SD : never,\n options?:\n | C\n | AnnotationRoot<ToStateDefinition<C>>\n | StateGraphOptions<I, O, C, N, InterruptType, WriterType>\n );\n\n constructor(\n fields: SD extends StateDefinition\n ? StateGraphArgsWithInputOutputSchemas<SD, ToStateDefinition<O>>\n : never,\n contextSchema?: C | AnnotationRoot<ToStateDefinition<C>>\n );\n\n constructor(\n fields: SD extends StateDefinition\n ?\n | AnnotationRoot<SD>\n | StateGraphArgsWithStateSchema<\n SD,\n ToStateDefinition<I>,\n ToStateDefinition<O>\n >\n : never,\n contextSchema?: C | AnnotationRoot<ToStateDefinition<C>>\n );\n\n constructor(\n init: Omit<\n StateGraphInit<\n SD extends StateDefinitionInit ? SD : StateDefinitionInit,\n SD extends StateDefinitionInit ? SD : StateDefinitionInit,\n O,\n C extends ContextSchemaInit ? C : undefined,\n N,\n InterruptType,\n WriterType\n >,\n \"state\" | \"stateSchema\" | \"input\"\n > & {\n input: SD extends StateDefinitionInit ? SD : never;\n state?: never;\n stateSchema?: never;\n },\n contextSchema?: C | AnnotationRoot<ToStateDefinition<C>>\n );\n\n constructor(\n init: StateGraphInit<\n SD extends StateDefinitionInit ? SD : StateDefinitionInit,\n I,\n O,\n C extends ContextSchemaInit ? C : undefined,\n N,\n InterruptType,\n WriterType\n >\n );\n\n /** @deprecated Use `Annotation.Root`, `StateSchema`, or Zod schemas instead. */\n constructor(\n fields: StateGraphArgs<S>,\n contextSchema?: C | AnnotationRoot<ToStateDefinition<C>>\n );\n\n constructor(\n stateOrInit:\n | StateDefinitionInit\n | StateGraphInit<StateDefinitionInit, I, O>\n | StateGraphArgs<S>,\n options?:\n | C\n | AnnotationRoot<ToStateDefinition<C>>\n | StateGraphOptions<\n I,\n O,\n C extends ContextSchemaInit ? C : undefined,\n N,\n InterruptType,\n WriterType\n >\n ) {\n super();\n\n // Normalize all input patterns to StateGraphInit format\n const init = this._normalizeToStateGraphInit(stateOrInit, options);\n\n // Resolve state schema: state > stateSchema (deprecated) > input\n const stateSchema = init.state ?? init.stateSchema ?? init.input;\n if (!stateSchema) {\n throw new StateGraphInputError();\n }\n\n // Get channel definitions from the schema (may contain channel factories)\n const stateChannelDef = this._getChannelsFromSchema(stateSchema);\n\n // Set schema definitions (these may contain channel factories)\n this._schemaDefinition = stateChannelDef;\n\n // Set runtime definitions for validation\n if (StateSchema.isInstance(stateSchema)) {\n this._schemaRuntimeDefinition = stateSchema;\n } else if (isInteropZodObject(stateSchema)) {\n this._schemaRuntimeDefinition = stateSchema;\n }\n\n // Set input runtime definition\n if (init.input) {\n if (StateSchema.isInstance(init.input)) {\n this._inputRuntimeDefinition = init.input;\n } else if (isInteropZodObject(init.input)) {\n this._inputRuntimeDefinition = init.input;\n } else {\n this._inputRuntimeDefinition = PartialStateSchema;\n }\n } else {\n this._inputRuntimeDefinition = PartialStateSchema;\n }\n\n // Set output runtime definition\n if (init.output) {\n if (StateSchema.isInstance(init.output)) {\n this._outputRuntimeDefinition = init.output;\n } else if (isInteropZodObject(init.output)) {\n this._outputRuntimeDefinition = init.output;\n } else {\n this._outputRuntimeDefinition = this._schemaRuntimeDefinition;\n }\n } else {\n this._outputRuntimeDefinition = this._schemaRuntimeDefinition;\n }\n\n // Set input/output definitions (default to state)\n const inputChannelDef = init.input\n ? this._getChannelsFromSchema(init.input)\n : stateChannelDef;\n const outputChannelDef = init.output\n ? (this._getChannelsFromSchema(init.output) as O)\n : stateChannelDef;\n this._inputDefinition = inputChannelDef as I;\n this._outputDefinition = outputChannelDef as O;\n\n // Add all schemas (_addSchema instantiates channel factories and populates this.channels)\n this._addSchema(this._schemaDefinition);\n this._addSchema(this._inputDefinition);\n this._addSchema(this._outputDefinition);\n\n // Handle context schema\n if (init.context) {\n if (isInteropZodObject(init.context)) {\n this._configRuntimeSchema = init.context;\n }\n }\n\n // Handle interrupt and writer\n this._interrupt = init.interrupt as InterruptType;\n this._writer = init.writer as WriterType;\n }\n\n /**\n * Normalize all constructor input patterns to a unified StateGraphInit object.\n * @internal\n */\n private _normalizeToStateGraphInit(\n stateOrInit: unknown,\n options?: unknown\n ): StateGraphInit<StateDefinitionInit, I, O, C> {\n // Check if already StateGraphInit format\n if (isStateGraphInit(stateOrInit)) {\n // Second arg can be either a direct context schema or an options object\n if (isInteropZodObject(options) || AnnotationRoot.isInstance(options)) {\n return {\n ...stateOrInit,\n context: options as C,\n };\n }\n // Merge any 2nd arg options\n const opts = options as StateGraphOptions<I, O> | undefined;\n return {\n ...stateOrInit,\n input: stateOrInit.input ?? opts?.input,\n output: stateOrInit.output ?? opts?.output,\n context: stateOrInit.context ?? opts?.context,\n interrupt: stateOrInit.interrupt ?? opts?.interrupt,\n writer: stateOrInit.writer ?? opts?.writer,\n nodes: stateOrInit.nodes ?? opts?.nodes,\n } as StateGraphInit<StateDefinitionInit, I, O, C>;\n }\n\n // Check if direct schema (StateSchema, Zod, Annotation, StateDefinition)\n if (isStateDefinitionInit(stateOrInit)) {\n // Second arg can be either a direct context schema or an options object\n if (isInteropZodObject(options) || AnnotationRoot.isInstance(options)) {\n return {\n state: stateOrInit,\n context: options as C,\n };\n }\n const opts = options as StateGraphOptions<I, O> | undefined;\n return {\n state: stateOrInit as StateDefinitionInit,\n input: opts?.input as I,\n output: opts?.output as O,\n context: opts?.context,\n interrupt: opts?.interrupt,\n writer: opts?.writer,\n nodes: opts?.nodes,\n };\n }\n\n // Check for legacy { channels } format\n if (isStateGraphArgs(stateOrInit as StateGraphArgs<S>)) {\n const legacyArgs = stateOrInit as StateGraphArgs<S>;\n const spec = _getChannels(legacyArgs.channels);\n return {\n state: spec as StateDefinitionInit,\n };\n }\n\n throw new StateGraphInputError();\n }\n\n /**\n * Convert any supported schema type to a StateDefinition (channel map).\n * @internal\n */\n private _getChannelsFromSchema(schema: StateDefinitionInit): StateDefinition {\n if (StateSchema.isInstance(schema)) {\n return schema.getChannels();\n }\n\n if (isInteropZodObject(schema)) {\n return this._metaRegistry.getChannelsForSchema(schema);\n }\n\n // AnnotationRoot - has .spec property that is the StateDefinition\n if (\n typeof schema === \"object\" &&\n \"lc_graph_name\" in schema &&\n (schema as { lc_graph_name: unknown }).lc_graph_name === \"AnnotationRoot\"\n ) {\n return (schema as AnnotationRoot<StateDefinition>).spec;\n }\n\n // StateDefinition (raw channel map) - return as-is\n if (\n typeof schema === \"object\" &&\n !Array.isArray(schema) &&\n Object.keys(schema).length > 0\n ) {\n return schema as StateDefinition;\n }\n\n throw new StateGraphInputError(\n \"Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.\"\n );\n }\n\n get allEdges(): Set<[string, string]> {\n return new Set([\n ...this.edges,\n ...Array.from(this.waitingEdges).flatMap(([starts, end]) =>\n starts.map((start) => [start, end] as [string, string])\n ),\n ]);\n }\n\n _addSchema(stateDefinition: StateDefinitionInit) {\n if (this._schemaDefinitions.has(stateDefinition)) {\n return;\n }\n // TODO: Support managed values\n this._schemaDefinitions.set(stateDefinition, stateDefinition);\n for (const [key, val] of Object.entries(stateDefinition)) {\n let channel;\n if (typeof val === \"function\") {\n channel = val();\n } else {\n channel = val;\n }\n if (this.channels[key] !== undefined) {\n if (!this.channels[key].equals(channel)) {\n if (channel.lc_graph_name !== \"LastValue\") {\n throw new Error(\n `Channel \"${key}\" already exists with a different type.`\n );\n }\n }\n } else {\n this.channels[key] = channel;\n }\n }\n }\n\n override addNode<\n K extends string,\n NodeMap extends Record<K, NodeAction<S, U, C, InterruptType, WriterType>>,\n >(\n nodes: NodeMap\n ): StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<\n NodeReturnType,\n {\n [key in keyof NodeMap]: NodeMap[key] extends NodeAction<\n S,\n infer U,\n C,\n InterruptType,\n WriterType\n >\n ? U\n : never;\n }\n >\n >;\n\n override addNode<K extends string, NodeInput = S, NodeOutput extends U = U>(\n nodes: [\n key: K,\n action: NodeAction<NodeInput, NodeOutput, C, InterruptType, WriterType>,\n options?: StateGraphAddNodeOptions,\n ][]\n ): StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<NodeReturnType, { [key in K]: NodeOutput }>\n >;\n\n override addNode<\n K extends string,\n InputSchema extends StateDefinitionInit,\n NodeOutput extends U = U,\n >(\n key: K,\n action: NodeAction<\n ExtractStateType<InputSchema>,\n NodeOutput,\n C,\n InterruptType,\n WriterType\n >,\n options: StateGraphAddNodeOptions<N | K, InputSchema>\n ): StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<NodeReturnType, { [key in K]: NodeOutput }>\n >;\n\n override addNode<\n K extends string,\n InputSchema extends StateDefinitionInit,\n NodeOutput extends U = U,\n >(\n key: K,\n action: NodeAction<\n ExtractStateType<InputSchema>,\n NodeOutput,\n C,\n InterruptType,\n WriterType\n >,\n options: StateGraphAddNodeOptions<N | K, InputSchema>\n ): StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<NodeReturnType, { [key in K]: NodeOutput }>\n >;\n\n override addNode<K extends string, NodeInput = S, NodeOutput extends U = U>(\n key: K,\n action: NodeAction<NodeInput, NodeOutput, C, InterruptType, WriterType>,\n options?: StateGraphAddNodeOptions\n ): StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<NodeReturnType, { [key in K]: NodeOutput }>\n >;\n\n override addNode<K extends string, NodeInput = S>(\n key: K,\n action: NodeAction<NodeInput, U, C, InterruptType, WriterType>,\n options?: StateGraphAddNodeOptions\n ): StateGraph<SD, S, U, N | K, I, O, C, NodeReturnType>;\n\n override addNode<K extends string, NodeInput = S, NodeOutput extends U = U>(\n ...args:\n | [\n key: K,\n action: NodeAction<\n NodeInput,\n NodeOutput,\n C,\n InterruptType,\n WriterType\n >,\n options?: StateGraphAddNodeOptions,\n ]\n | [\n nodes:\n | Record<K, NodeAction<NodeInput, U, C, InterruptType, WriterType>>\n | [\n key: K,\n action: NodeAction<NodeInput, U, C, InterruptType, WriterType>,\n options?: StateGraphAddNodeOptions,\n ][],\n ]\n ): StateGraph<SD, S, U, N | K, I, O, C> {\n function isMultipleNodes(\n args: unknown[]\n ): args is [\n nodes:\n | Record<K, NodeAction<NodeInput, U, C, InterruptType, WriterType>>\n | [\n key: K,\n action: NodeAction<NodeInput, U, C, InterruptType, WriterType>,\n options?: AddNodeOptions,\n ][],\n ] {\n return args.length >= 1 && typeof args[0] !== \"string\";\n }\n\n const nodes = (\n isMultipleNodes(args) // eslint-disable-line no-nested-ternary\n ? Array.isArray(args[0])\n ? args[0]\n : Object.entries(args[0]).map(([key, action]) => [key, action])\n : [[args[0], args[1], args[2]]]\n ) as [\n K,\n NodeAction<NodeInput, U, C, InterruptType, WriterType>,\n StateGraphAddNodeOptions | undefined,\n ][];\n\n if (nodes.length === 0) {\n throw new Error(\"No nodes provided in `addNode`\");\n }\n\n for (const [key, action, options] of nodes) {\n if (key in this.channels) {\n throw new Error(\n `${key} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`\n );\n }\n\n for (const reservedChar of [\n CHECKPOINT_NAMESPACE_SEPARATOR,\n CHECKPOINT_NAMESPACE_END,\n ]) {\n if (key.includes(reservedChar)) {\n throw new Error(\n `\"${reservedChar}\" is a reserved character and is not allowed in node names.`\n );\n }\n }\n this.warnIfCompiled(\n `Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`\n );\n\n if (key in this.nodes) {\n throw new Error(`Node \\`${key}\\` already present.`);\n }\n if (key === END || key === START) {\n throw new Error(`Node \\`${key}\\` is reserved.`);\n }\n\n let inputSpec: StateDefinition = this._schemaDefinition;\n if (options?.input !== undefined) {\n inputSpec = this._getChannelsFromSchema(options.input);\n }\n this._addSchema(inputSpec);\n\n let runnable;\n if (Runnable.isRunnable(action)) {\n runnable = action;\n } else if (typeof action === \"function\") {\n runnable = new RunnableCallable({\n func: action,\n name: key,\n trace: false,\n });\n } else {\n runnable = _coerceToRunnable(action);\n }\n\n let cachePolicy = options?.cachePolicy;\n if (typeof cachePolicy === \"boolean\") {\n cachePolicy = cachePolicy ? {} : undefined;\n }\n\n const nodeSpec: StateGraphNodeSpec<S, U> = {\n runnable: runnable as unknown as Runnable<S, U>,\n retryPolicy: options?.retryPolicy,\n cachePolicy,\n metadata: options?.metadata,\n input: inputSpec ?? this._schemaDefinition,\n subgraphs: isPregelLike(runnable)\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [runnable as any]\n : options?.subgraphs,\n ends: options?.ends,\n defer: options?.defer,\n };\n\n this.nodes[key as unknown as N] = nodeSpec;\n }\n\n return this as StateGraph<SD, S, U, N | K, I, O, C>;\n }\n\n override addEdge(\n startKey: typeof START | N | N[],\n endKey: N | typeof END\n ): this {\n if (typeof startKey === \"string\") {\n return super.addEdge(startKey, endKey);\n }\n\n if (this.compiled) {\n console.warn(\n \"Adding an edge to a graph that has already been compiled. This will \" +\n \"not be reflected in the compiled graph.\"\n );\n }\n\n for (const start of startKey) {\n if (start === END) {\n throw new Error(\"END cannot be a start node\");\n }\n if (!Object.keys(this.nodes).some((node) => node === start)) {\n throw new Error(`Need to add a node named \"${start}\" first`);\n }\n }\n if (endKey === END) {\n throw new Error(\"END cannot be an end node\");\n }\n if (!Object.keys(this.nodes).some((node) => node === endKey)) {\n throw new Error(`Need to add a node named \"${endKey}\" first`);\n }\n\n this.waitingEdges.add([startKey, endKey]);\n\n return this;\n }\n\n addSequence<K extends string, NodeInput = S, NodeOutput extends U = U>(\n nodes: [\n key: K,\n action: NodeAction<NodeInput, NodeOutput, C, InterruptType, WriterType>,\n options?: StateGraphAddNodeOptions,\n ][]\n ): StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<NodeReturnType, { [key in K]: NodeOutput }>\n >;\n\n addSequence<\n K extends string,\n NodeMap extends Record<K, NodeAction<S, U, C, InterruptType, WriterType>>,\n >(\n nodes: NodeMap\n ): StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<\n NodeReturnType,\n {\n [key in keyof NodeMap]: NodeMap[key] extends NodeAction<\n S,\n infer U,\n C,\n InterruptType,\n WriterType\n >\n ? U\n : never;\n }\n >\n >;\n\n addSequence<K extends string, NodeInput = S, NodeOutput extends U = U>(\n nodes:\n | [\n key: K,\n action: NodeAction<\n NodeInput,\n NodeOutput,\n C,\n InterruptType,\n WriterType\n >,\n options?: StateGraphAddNodeOptions,\n ][]\n | Record<\n K,\n NodeAction<NodeInput, NodeOutput, C, InterruptType, WriterType>\n >\n ): StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<NodeReturnType, { [key in K]: NodeOutput }>\n > {\n const parsedNodes = Array.isArray(nodes) ? nodes : Object.entries(nodes);\n\n if (parsedNodes.length === 0) {\n throw new Error(\"Sequence requires at least one node.\");\n }\n\n let previousNode: N | undefined;\n for (const [key, action, options] of parsedNodes) {\n if (key in this.nodes) {\n throw new Error(\n `Node names must be unique: node with the name \"${key}\" already exists.`\n );\n }\n\n const validKey = key as unknown as N;\n this.addNode(\n validKey,\n action as NodeAction<S, U, C, InterruptType, WriterType>,\n options\n );\n if (previousNode != null) {\n this.addEdge(previousNode, validKey);\n }\n\n previousNode = validKey;\n }\n\n return this as StateGraph<\n SD,\n S,\n U,\n N | K,\n I,\n O,\n C,\n MergeReturnType<NodeReturnType, { [key in K]: NodeOutput }>\n >;\n }\n\n override compile<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const TTransformers extends ReadonlyArray<() => StreamTransformer<any>> =\n [],\n >({\n checkpointer,\n store,\n cache,\n interruptBefore,\n interruptAfter,\n name,\n description,\n transformers,\n }: {\n checkpointer?: BaseCheckpointSaver | boolean;\n store?: BaseStore;\n cache?: BaseCache;\n interruptBefore?: N[] | All;\n interruptAfter?: N[] | All;\n name?: string;\n description?: string;\n /**\n * Stream transformer factories baked into the compiled graph. These run\n * automatically for every `streamEvents(..., { version: \"v3\" })` call,\n * before any call-site transformers.\n */\n transformers?: TTransformers;\n } = {}): CompiledStateGraph<\n Prettify<S>,\n Prettify<U>,\n N,\n I,\n O,\n C,\n NodeReturnType,\n InterruptType,\n WriterType,\n TTransformers\n > {\n // validate the graph\n this.validate([\n ...(Array.isArray(interruptBefore) ? interruptBefore : []),\n ...(Array.isArray(interruptAfter) ? interruptAfter : []),\n ]);\n\n // prepare output channels\n const outputKeys = Object.keys(\n this._schemaDefinitions.get(this._outputDefinition)\n );\n const outputChannels =\n outputKeys.length === 1 && outputKeys[0] === ROOT ? ROOT : outputKeys;\n\n const streamKeys = Object.keys(this.channels);\n const streamChannels =\n streamKeys.length === 1 && streamKeys[0] === ROOT ? ROOT : streamKeys;\n\n const userInterrupt = this._interrupt;\n // create empty compiled graph\n const compiled = new CompiledStateGraph<\n S,\n U,\n N,\n I,\n O,\n C,\n NodeReturnType,\n InterruptType,\n WriterType,\n TTransformers\n >({\n builder: this,\n checkpointer,\n interruptAfter,\n interruptBefore,\n autoValidate: false,\n nodes: {} as Record<N | typeof START, PregelNode<S, U>>,\n channels: {\n ...this.channels,\n [START]: new EphemeralValue(),\n } as Record<N | typeof START | typeof END | string, BaseChannel>,\n inputChannels: START,\n outputChannels,\n streamChannels,\n streamMode: \"updates\",\n store,\n cache,\n name,\n description,\n userInterrupt,\n streamTransformers: transformers,\n });\n\n // attach nodes, edges and branches\n compiled.attachNode(START);\n for (const [key, node] of Object.entries<StateGraphNodeSpec<S, U>>(\n this.nodes\n )) {\n compiled.attachNode(key as N, node);\n }\n compiled.attachBranch(START, SELF, _getControlBranch() as Branch<S, N>, {\n withReader: false,\n });\n for (const [key] of Object.entries<StateGraphNodeSpec<S, U>>(this.nodes)) {\n compiled.attachBranch(\n key as N,\n SELF,\n _getControlBranch() as Branch<S, N>,\n {\n withReader: false,\n }\n );\n }\n for (const [start, end] of this.edges) {\n compiled.attachEdge(start, end);\n }\n for (const [starts, end] of this.waitingEdges) {\n compiled.attachEdge(starts, end);\n }\n for (const [start, branches] of Object.entries(this.branches)) {\n for (const [name, branch] of Object.entries(branches)) {\n compiled.attachBranch(start as N, name, branch);\n }\n }\n\n return compiled.validate();\n }\n}\n\nfunction _getChannels<Channels extends Record<string, unknown> | unknown>(\n schema: StateGraphArgs<Channels>[\"channels\"]\n): Record<string, BaseChannel> {\n const channels: Record<string, BaseChannel> = {};\n for (const [name, val] of Object.entries(schema)) {\n if (name === ROOT) {\n channels[name] = getChannel<Channels>(val as SingleReducer<Channels>);\n } else {\n const key = name as keyof Channels;\n channels[name] = getChannel<Channels[typeof key]>(\n val as SingleReducer<Channels[typeof key]>\n );\n }\n }\n return channels;\n}\n\n/**\n * Final result from building and compiling a {@link StateGraph}.\n * Should not be instantiated directly, only using the StateGraph `.compile()`\n * instance method.\n *\n * @typeParam S - The full state type representing the complete shape of your graph's\n * state after all reducers have been applied. This is the type you receive when\n * reading state in nodes or after invoking the graph.\n *\n * @typeParam U - The update type representing what nodes can return to modify state.\n * Typically a partial of the state type, allowing nodes to update only specific fields.\n * Can also include {@link Command} objects for advanced control flow.\n *\n * @typeParam N - Union of all node names in the graph (e.g., `\"agent\" | \"tool\"`).\n * Used for type-safe routing with {@link Command.goto} and edge definitions.\n *\n * @typeParam I - The input schema definition. Determines what shape of data the graph\n * accepts when invoked. Defaults to the main state schema if not explicitly set.\n *\n * @typeParam O - The output schema definition. Determines what shape of data the graph\n * returns after execution. Defaults to the main state schema if not explicitly set.\n *\n * @typeParam C - The config/context schema definition. Defines additional configuration\n * that can be passed to the graph at runtime via {@link LangGraphRunnableConfig}.\n *\n * @typeParam NodeReturnType - Constrains what types nodes in this graph can return.\n * Useful for enforcing consistent return patterns across all nodes.\n *\n * @typeParam InterruptType - The type of values that can be passed when resuming from\n * an {@link interrupt}. Used with human-in-the-loop patterns.\n *\n * @typeParam WriterType - The type for custom stream writers. Used with the `writer`\n * option to enable typed custom streaming from within nodes.\n */\nexport class CompiledStateGraph<\n S,\n U,\n N extends string = typeof START,\n I extends StateDefinitionInit = StateDefinition,\n O extends StateDefinitionInit = StateDefinition,\n C extends StateDefinitionInit = StateDefinition,\n NodeReturnType = unknown,\n InterruptType = unknown,\n WriterType = unknown,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TStreamTransformers extends ReadonlyArray<() => StreamTransformer<any>> = [],\n> extends CompiledGraph<\n N,\n S,\n U,\n ExtractStateType<C>,\n ExtractUpdateType<I, ExtractStateType<I>>,\n ExtractStateType<O>,\n NodeReturnType,\n CommandInstance<InferInterruptResumeType<InterruptType>, Prettify<U>, N>,\n InferWriterType<WriterType>,\n TStreamTransformers\n> {\n declare builder: StateGraph<unknown, S, U, N, I, O, C, NodeReturnType>;\n\n /**\n * The description of the compiled graph.\n * This is used by the supervisor agent to describe the handoff to the agent.\n */\n description?: string;\n\n /** @internal */\n _metaRegistry: SchemaMetaRegistry = schemaMetaRegistry;\n\n constructor({\n description,\n ...rest\n }: { description?: string } & ConstructorParameters<\n typeof CompiledGraph<\n N,\n S,\n U,\n ExtractStateType<C>,\n ExtractUpdateType<I, ExtractStateType<I>>,\n ExtractStateType<O>,\n NodeReturnType,\n CommandInstance<InferInterruptResumeType<InterruptType>, Prettify<U>, N>,\n InferWriterType<WriterType>,\n TStreamTransformers\n >\n >[0]) {\n super(rest);\n this.description = description;\n }\n\n attachNode(key: typeof START, node?: never): void;\n\n attachNode(key: N, node: StateGraphNodeSpec<S, U>): void;\n\n attachNode(key: N | typeof START, node?: StateGraphNodeSpec<S, U>): void {\n let outputKeys: string[];\n if (key === START) {\n // Get input schema keys excluding managed values\n outputKeys = Object.entries(\n this.builder._schemaDefinitions.get(this.builder._inputDefinition)\n ).map(([k]) => k);\n } else {\n outputKeys = Object.keys(this.builder.channels);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function _getRoot(input: unknown): [string, any][] | null {\n if (isCommand(input)) {\n if (input.graph === Command.PARENT) {\n return null;\n }\n return input._updateAsTuples();\n } else if (\n Array.isArray(input) &&\n input.length > 0 &&\n input.some((i) => isCommand(i))\n ) {\n const updates: [string, unknown][] = [];\n for (const i of input) {\n if (isCommand(i)) {\n if (i.graph === Command.PARENT) {\n continue;\n }\n updates.push(...i._updateAsTuples());\n } else {\n updates.push([ROOT, i]);\n }\n }\n return updates;\n } else if (input != null) {\n return [[ROOT, input]];\n }\n return null;\n }\n\n // to avoid name collision below\n const nodeKey = key;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function _getUpdates(input: U): [string, any][] | null {\n if (!input) {\n return null;\n } else if (isCommand(input)) {\n if (input.graph === Command.PARENT) {\n return null;\n }\n return input._updateAsTuples().filter(([k]) => outputKeys.includes(k));\n } else if (\n Array.isArray(input) &&\n input.length > 0 &&\n input.some(isCommand)\n ) {\n const updates: [string, unknown][] = [];\n for (const item of input) {\n if (isCommand(item)) {\n if (item.graph === Command.PARENT) {\n continue;\n }\n updates.push(\n ...item._updateAsTuples().filter(([k]) => outputKeys.includes(k))\n );\n } else {\n const itemUpdates = _getUpdates(item);\n if (itemUpdates) {\n updates.push(...(itemUpdates ?? []));\n }\n }\n }\n return updates;\n } else if (typeof input === \"object\" && !Array.isArray(input)) {\n return Object.entries(input).filter(([k]) => outputKeys.includes(k));\n } else {\n const typeofInput = Array.isArray(input) ? \"array\" : typeof input;\n throw new InvalidUpdateError(\n `Expected node \"${nodeKey.toString()}\" to return an object or an array containing at least one Command object, received ${typeofInput}`,\n {\n lc_error_code: \"INVALID_GRAPH_NODE_RETURN_VALUE\",\n }\n );\n }\n }\n\n const stateWriteEntries: (ChannelWriteTupleEntry | ChannelWriteEntry)[] = [\n {\n value: PASSTHROUGH,\n mapper: new RunnableCallable({\n func:\n outputKeys.length && outputKeys[0] === ROOT\n ? _getRoot\n : _getUpdates,\n trace: false,\n recurse: false,\n }),\n },\n ];\n\n // add node and output channel\n if (key === START) {\n this.nodes[key] = new PregelNode<S, U>({\n tags: [TAG_HIDDEN],\n triggers: [START],\n channels: [START],\n writers: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])],\n });\n } else {\n const inputDefinition = node?.input ?? this.builder._schemaDefinition;\n const inputValues = Object.fromEntries(\n Object.keys(this.builder._schemaDefinitions.get(inputDefinition)).map(\n (k) => [k, k]\n )\n );\n const isSingleInput =\n Object.keys(inputValues).length === 1 && ROOT in inputValues;\n const branchChannel = `branch:to:${key}` as string | N;\n this.channels[branchChannel] = node?.defer\n ? new LastValueAfterFinish()\n : new EphemeralValue(false);\n this.nodes[key] = new PregelNode<S, U>({\n triggers: [branchChannel],\n // read state keys\n channels: isSingleInput ? Object.keys(inputValues) : inputValues,\n // publish to state keys\n writers: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])],\n mapper: isSingleInput\n ? undefined\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (input: Record<string, any>) => {\n return Object.fromEntries(\n Object.entries(input).filter(([k]) => k in inputValues)\n );\n },\n bound: node?.runnable,\n metadata: node?.metadata,\n retryPolicy: node?.retryPolicy,\n cachePolicy: node?.cachePolicy,\n subgraphs: node?.subgraphs,\n ends: node?.ends,\n });\n }\n }\n\n attachEdge(starts: N | N[] | \"__start__\", end: N | \"__end__\"): void {\n if (end === END) return;\n if (typeof starts === \"string\") {\n this.nodes[starts].writers.push(\n new ChannelWrite(\n [{ channel: `branch:to:${end}`, value: null }],\n [TAG_HIDDEN]\n )\n );\n } else if (Array.isArray(starts)) {\n const channelName = `join:${starts.join(\"+\")}:${end}`;\n // register channel\n this.channels[channelName as string | N] = this.builder.nodes[end].defer\n ? new NamedBarrierValueAfterFinish(new Set(starts))\n : new NamedBarrierValue(new Set(starts));\n // subscribe to channel\n this.nodes[end].triggers.push(channelName);\n // publish to channel\n for (const start of starts) {\n this.nodes[start].writers.push(\n new ChannelWrite(\n [{ channel: channelName, value: start }],\n [TAG_HIDDEN]\n )\n );\n }\n }\n }\n\n attachBranch(\n start: N | typeof START,\n _: string,\n branch: Branch<S, N>,\n options: { withReader?: boolean } = { withReader: true }\n ): void {\n const branchWriter = async (\n packets: (string | Send)[],\n config: LangGraphRunnableConfig\n ) => {\n const filteredPackets = packets.filter((p) => p !== END);\n if (!filteredPackets.length) return;\n\n const writes: (ChannelWriteEntry | Send)[] = filteredPackets.map((p) => {\n if (_isSend(p)) return p;\n return { channel: p === END ? p : `branch:to:${p}`, value: start };\n });\n await ChannelWrite.doWrite(\n { ...config, tags: (config.tags ?? []).concat([TAG_HIDDEN]) },\n writes\n );\n };\n // attach branch publisher\n this.nodes[start].writers.push(\n branch.run(\n branchWriter,\n // reader\n options.withReader\n ? (config) =>\n ChannelRead.doRead<S>(\n config,\n this.streamChannels ?? this.outputChannels,\n true\n )\n : undefined\n )\n );\n }\n\n protected async _validateInput(\n input: ExtractUpdateType<I, ExtractStateType<I>>\n ): Promise<ExtractUpdateType<I, ExtractStateType<I>>> {\n if (input == null) return input;\n\n const inputDef = this.builder._inputRuntimeDefinition;\n const schemaDef = this.builder._schemaRuntimeDefinition;\n\n // Determine which schema to use for validation\n // Priority: inputDef (if it's a validatable schema), otherwise fall back to schemaDef\n\n // Handle StateSchema validation for input schema\n if (StateSchema.isInstance(inputDef)) {\n if (isCommand(input)) {\n const parsedInput = input;\n if (input.update) {\n parsedInput.update = await inputDef.validateInput(\n Array.isArray(input.update)\n ? Object.fromEntries(input.update)\n : input.update\n );\n }\n return parsedInput;\n }\n return await inputDef.validateInput(input);\n }\n\n // Handle StateSchema validation for state schema (when input is partial state)\n if (inputDef === PartialStateSchema && StateSchema.isInstance(schemaDef)) {\n if (isCommand(input)) {\n const parsedInput = input;\n if (input.update) {\n parsedInput.update = await schemaDef.validateInput(\n Array.isArray(input.update)\n ? Object.fromEntries(input.update)\n : input.update\n );\n }\n return parsedInput;\n }\n return await schemaDef.validateInput(input);\n }\n\n // Handle InteropZodObject validation\n const schema = (() => {\n const apply = (schema: InteropZodObject | undefined) => {\n if (schema == null) return undefined;\n return this._metaRegistry.getExtendedChannelSchemas(schema, {\n withReducerSchema: true,\n });\n };\n\n if (isInteropZodObject(inputDef)) return apply(inputDef);\n if (inputDef === PartialStateSchema) {\n if (isInteropZodObject(schemaDef)) {\n return interopZodObjectPartial(apply(schemaDef)!);\n }\n return undefined;\n }\n return undefined;\n })();\n\n if (isCommand(input)) {\n const parsedInput = input;\n if (input.update && schema != null) {\n const updateObj = Array.isArray(input.update)\n ? Object.fromEntries(input.update)\n : input.update;\n const parsed = interopParse(schema, updateObj);\n parsedInput.update = Object.fromEntries(\n Object.keys(updateObj).map((k) => [k, parsed[k]])\n );\n }\n return parsedInput;\n }\n if (schema != null) return interopParse(schema, input);\n return input;\n }\n\n public isInterrupted(input: unknown): input is {\n [INTERRUPT]: Interrupt<InferInterruptInputType<InterruptType>>[];\n } {\n return isInterrupted(input);\n }\n\n protected async _validateContext(\n config: Partial<Record<string, unknown>>\n ): Promise<Partial<Record<string, unknown>>> {\n const configSchema = this.builder._configRuntimeSchema;\n if (isInteropZodObject(configSchema)) interopParse(configSchema, config);\n return config;\n }\n}\n\n/**\n * Check if value is a legacy StateGraphArgs with channels.\n * @internal\n * @deprecated Use StateGraphInit instead\n */\nfunction isStateGraphArgs<Channels extends object | unknown>(\n obj: unknown | StateGraphArgs<Channels>\n): obj is StateGraphArgs<Channels> {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n (obj as StateGraphArgs<Channels>).channels !== undefined\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _controlBranch(value: any): (string | Send)[] {\n if (_isSend(value)) {\n return [value];\n }\n const commands = [];\n if (isCommand(value)) {\n commands.push(value);\n } else if (Array.isArray(value)) {\n commands.push(...value.filter(isCommand));\n }\n const destinations: (string | Send)[] = [];\n\n for (const command of commands) {\n if (command.graph === Command.PARENT) {\n throw new ParentCommand(command);\n }\n\n if (_isSend(command.goto)) {\n destinations.push(command.goto);\n } else if (typeof command.goto === \"string\") {\n destinations.push(command.goto);\n } else {\n if (Array.isArray(command.goto)) {\n destinations.push(...command.goto);\n }\n }\n }\n return destinations;\n}\n\nfunction _getControlBranch() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const CONTROL_BRANCH_PATH = new RunnableCallable<any, (string | Send)[]>({\n func: _controlBranch,\n tags: [TAG_HIDDEN],\n trace: false,\n recurse: false,\n name: \"<control_branch>\",\n });\n return new Branch({\n path: CONTROL_BRANCH_PATH,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4FA,MAAM,OAAO;AAgGb,MAAM,qBAAqB,OAAO,IAAI,0BAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwGhE,IAAa,aAAb,cAWU,MAA+D;CACvE,WAAwC,EAAE;CAG1C,+BAA8B,IAAI,KAAK;;CAGvC;;CAGA;;CAGA;;CAGA;;CAOA;;CAGA;;;;;CAMA,qCAAqB,IAAI,KAAK;;CAG9B,gBAAoC;;CAGpC;;CAGA;;CAGA;;CAGA;CA4GA,YACE,aAIA,SAWA;AACA,SAAO;EAGP,MAAM,OAAO,KAAK,2BAA2B,aAAa,QAAQ;EAGlE,MAAM,cAAc,KAAK,SAAS,KAAK,eAAe,KAAK;AAC3D,MAAI,CAAC,YACH,OAAM,IAAI,sBAAsB;EAIlC,MAAM,kBAAkB,KAAK,uBAAuB,YAAY;AAGhE,OAAK,oBAAoB;AAGzB,MAAI,YAAY,WAAW,YAAY,CACrC,MAAK,2BAA2B;WACvB,mBAAmB,YAAY,CACxC,MAAK,2BAA2B;AAIlC,MAAI,KAAK,MACP,KAAI,YAAY,WAAW,KAAK,MAAM,CACpC,MAAK,0BAA0B,KAAK;WAC3B,mBAAmB,KAAK,MAAM,CACvC,MAAK,0BAA0B,KAAK;MAEpC,MAAK,0BAA0B;MAGjC,MAAK,0BAA0B;AAIjC,MAAI,KAAK,OACP,KAAI,YAAY,WAAW,KAAK,OAAO,CACrC,MA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Q,KAAK;WAE3B,MAAM,QAAQ,QAAQ,KAAK,CAC7B,cAAa,KAAK,GAAG,QAAQ,KAAK;;AAIxC,QAAO;;AAGT,SAAS,oBAAoB;AAS3B,QAAO,IAAI,OAAO,EAChB,MAR0B,IAAI,iBAAyC;EACvE,MAAM;EACN,MAAM,CAAC,WAAW;EAClB,OAAO;EACP,SAAS;EACT,MAAM;EACP,CAAC,EAGD,CAAC"}
|
package/dist/pregel/remote.cjs
CHANGED
|
@@ -157,6 +157,27 @@ var RemoteGraph = class extends _langchain_core_runnables.Runnable {
|
|
|
157
157
|
recursion_limit: sanitizedConfig.recursionLimit
|
|
158
158
|
};
|
|
159
159
|
}
|
|
160
|
+
/**
|
|
161
|
+
* Prepare config and thread ID for remote run API calls.
|
|
162
|
+
*
|
|
163
|
+
* `thread_id` is passed via the URL path, not in `config.configurable`, so the
|
|
164
|
+
* server can accept a separate `context` payload for stateful runs.
|
|
165
|
+
*/
|
|
166
|
+
#prepareRunRequest(mergedConfig) {
|
|
167
|
+
const context = mergedConfig.context;
|
|
168
|
+
const sanitizedConfig = this._sanitizeConfig(mergedConfig);
|
|
169
|
+
const configurable = { ...sanitizedConfig.configurable };
|
|
170
|
+
const threadId = configurable.thread_id;
|
|
171
|
+
delete configurable.thread_id;
|
|
172
|
+
return {
|
|
173
|
+
threadId,
|
|
174
|
+
context,
|
|
175
|
+
config: {
|
|
176
|
+
...sanitizedConfig,
|
|
177
|
+
configurable
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
}
|
|
160
181
|
_getConfig(checkpoint) {
|
|
161
182
|
return { configurable: {
|
|
162
183
|
thread_id: checkpoint.thread_id,
|
|
@@ -165,6 +186,16 @@ var RemoteGraph = class extends _langchain_core_runnables.Runnable {
|
|
|
165
186
|
checkpoint_map: checkpoint.checkpoint_map ?? {}
|
|
166
187
|
} };
|
|
167
188
|
}
|
|
189
|
+
_checkpointToConfig(checkpoint, fallbackConfig) {
|
|
190
|
+
const resolvedCheckpoint = checkpoint ?? this._getCheckpoint(fallbackConfig);
|
|
191
|
+
if (resolvedCheckpoint == null) return { configurable: {} };
|
|
192
|
+
const configurable = {};
|
|
193
|
+
if (resolvedCheckpoint.thread_id !== void 0) configurable.thread_id = resolvedCheckpoint.thread_id;
|
|
194
|
+
if (resolvedCheckpoint.checkpoint_ns !== void 0) configurable.checkpoint_ns = resolvedCheckpoint.checkpoint_ns;
|
|
195
|
+
if (resolvedCheckpoint.checkpoint_id !== void 0) configurable.checkpoint_id = resolvedCheckpoint.checkpoint_id;
|
|
196
|
+
if (resolvedCheckpoint.checkpoint_ns !== void 0 || resolvedCheckpoint.checkpoint_id !== void 0 || resolvedCheckpoint.checkpoint_map !== void 0) configurable.checkpoint_map = resolvedCheckpoint.checkpoint_map ?? {};
|
|
197
|
+
return { configurable };
|
|
198
|
+
}
|
|
168
199
|
_getCheckpoint(config) {
|
|
169
200
|
if (config?.configurable === void 0) return;
|
|
170
201
|
const checkpoint = Object.fromEntries([
|
|
@@ -175,7 +206,7 @@ var RemoteGraph = class extends _langchain_core_runnables.Runnable {
|
|
|
175
206
|
].map((key) => [key, config.configurable[key]]).filter(([_, value]) => value !== void 0));
|
|
176
207
|
return Object.keys(checkpoint).length > 0 ? checkpoint : void 0;
|
|
177
208
|
}
|
|
178
|
-
_createStateSnapshot(state) {
|
|
209
|
+
_createStateSnapshot(state, fallbackConfig) {
|
|
179
210
|
const tasks = state.tasks.map((task) => {
|
|
180
211
|
return {
|
|
181
212
|
id: task.id,
|
|
@@ -185,27 +216,17 @@ var RemoteGraph = class extends _langchain_core_runnables.Runnable {
|
|
|
185
216
|
interrupt_id: id,
|
|
186
217
|
...rest
|
|
187
218
|
})),
|
|
188
|
-
state: task.state ? this._createStateSnapshot(task.state) : task.checkpoint ? { configurable: task.checkpoint } : void 0,
|
|
219
|
+
state: task.state ? this._createStateSnapshot(task.state, task.checkpoint ? this._checkpointToConfig(task.checkpoint) : fallbackConfig) : task.checkpoint ? { configurable: task.checkpoint } : void 0,
|
|
189
220
|
result: task.result
|
|
190
221
|
};
|
|
191
222
|
});
|
|
192
223
|
return {
|
|
193
224
|
values: state.values,
|
|
194
225
|
next: state.next ? [...state.next] : [],
|
|
195
|
-
config:
|
|
196
|
-
thread_id: state.checkpoint.thread_id,
|
|
197
|
-
checkpoint_ns: state.checkpoint.checkpoint_ns,
|
|
198
|
-
checkpoint_id: state.checkpoint.checkpoint_id,
|
|
199
|
-
checkpoint_map: state.checkpoint.checkpoint_map ?? {}
|
|
200
|
-
} },
|
|
226
|
+
config: this._checkpointToConfig(state.checkpoint, fallbackConfig),
|
|
201
227
|
metadata: state.metadata ? state.metadata : void 0,
|
|
202
228
|
createdAt: state.created_at ?? void 0,
|
|
203
|
-
parentConfig: state.parent_checkpoint ?
|
|
204
|
-
thread_id: state.parent_checkpoint.thread_id,
|
|
205
|
-
checkpoint_ns: state.parent_checkpoint.checkpoint_ns,
|
|
206
|
-
checkpoint_id: state.parent_checkpoint.checkpoint_id,
|
|
207
|
-
checkpoint_map: state.parent_checkpoint.checkpoint_map ?? {}
|
|
208
|
-
} } : void 0,
|
|
229
|
+
parentConfig: state.parent_checkpoint ? this._checkpointToConfig(state.parent_checkpoint) : void 0,
|
|
209
230
|
tasks
|
|
210
231
|
};
|
|
211
232
|
}
|
|
@@ -223,7 +244,7 @@ var RemoteGraph = class extends _langchain_core_runnables.Runnable {
|
|
|
223
244
|
}
|
|
224
245
|
async *_streamIterator(input, options) {
|
|
225
246
|
const mergedConfig = (0, _langchain_core_runnables.mergeConfigs)(this.config, options);
|
|
226
|
-
const sanitizedConfig = this
|
|
247
|
+
const { threadId, context, config: sanitizedConfig } = this.#prepareRunRequest(mergedConfig);
|
|
227
248
|
const streamProtocolInstance = options?.configurable?.[require_constants.CONFIG_KEY_STREAM];
|
|
228
249
|
const streamSubgraphs = options?.subgraphs ?? streamProtocolInstance !== void 0;
|
|
229
250
|
const interruptBefore = options?.interruptBefore ?? this.interruptBefore;
|
|
@@ -239,10 +260,11 @@ var RemoteGraph = class extends _langchain_core_runnables.Runnable {
|
|
|
239
260
|
command = input.toJSON();
|
|
240
261
|
serializedInput = void 0;
|
|
241
262
|
} else serializedInput = _serializeInputs(input);
|
|
242
|
-
|
|
263
|
+
const streamPayload = {
|
|
243
264
|
command,
|
|
244
265
|
input: serializedInput,
|
|
245
266
|
config: sanitizedConfig,
|
|
267
|
+
context,
|
|
246
268
|
streamMode: extendedStreamModes,
|
|
247
269
|
interruptBefore,
|
|
248
270
|
interruptAfter,
|
|
@@ -250,7 +272,9 @@ var RemoteGraph = class extends _langchain_core_runnables.Runnable {
|
|
|
250
272
|
ifNotExists: "create",
|
|
251
273
|
signal: mergedConfig.signal,
|
|
252
274
|
streamResumable: this.streamResumable
|
|
253
|
-
}
|
|
275
|
+
};
|
|
276
|
+
const runStream = threadId != null ? this.client.runs.stream(threadId, this.graphId, streamPayload) : this.client.runs.stream(null, this.graphId, streamPayload);
|
|
277
|
+
for await (const chunk of runStream) {
|
|
254
278
|
let mode;
|
|
255
279
|
let namespace;
|
|
256
280
|
if (chunk.event.includes("|")) {
|
|
@@ -300,7 +324,7 @@ var RemoteGraph = class extends _langchain_core_runnables.Runnable {
|
|
|
300
324
|
metadata: options?.filter,
|
|
301
325
|
checkpoint: this._getCheckpoint(mergedConfig)
|
|
302
326
|
});
|
|
303
|
-
for (const state of states) yield this._createStateSnapshot(state);
|
|
327
|
+
for (const state of states) yield this._createStateSnapshot(state, mergedConfig);
|
|
304
328
|
}
|
|
305
329
|
_getDrawableNodes(nodes) {
|
|
306
330
|
const nodesMap = {};
|
|
@@ -318,7 +342,7 @@ var RemoteGraph = class extends _langchain_core_runnables.Runnable {
|
|
|
318
342
|
async getState(config, options) {
|
|
319
343
|
const mergedConfig = (0, _langchain_core_runnables.mergeConfigs)(this.config, config);
|
|
320
344
|
const state = await this.client.threads.getState(mergedConfig.configurable?.thread_id, this._getCheckpoint(mergedConfig), options);
|
|
321
|
-
return this._createStateSnapshot(state);
|
|
345
|
+
return this._createStateSnapshot(state, mergedConfig);
|
|
322
346
|
}
|
|
323
347
|
/** @deprecated Use getGraphAsync instead. The async method will become the default in the next minor release. */
|
|
324
348
|
getGraph(_) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote.cjs","names":["BaseMessage","Runnable","Client","propagateConfigurableToMetadata","CONFIG_KEY_STREAM","isCommand","GraphInterrupt","INTERRUPT","RemoteException","DrawableGraph"],"sources":["../../src/pregel/remote.ts"],"sourcesContent":["import {\n Client,\n type Checkpoint,\n type ThreadState,\n} from \"@langchain/langgraph-sdk\";\nimport {\n Graph as DrawableGraph,\n Node as DrawableNode,\n} from \"@langchain/core/runnables/graph\";\nimport {\n mergeConfigs,\n Runnable,\n RunnableConfig,\n} from \"@langchain/core/runnables\";\nimport {\n All,\n CheckpointListOptions,\n CheckpointMetadata,\n} from \"@langchain/langgraph-checkpoint\";\nimport { StreamEvent } from \"@langchain/core/tracers/log_stream\";\nimport { IterableReadableStream } from \"@langchain/core/utils/stream\";\nimport { BaseMessage } from \"@langchain/core/messages\";\n\nimport {\n BaseChannel,\n GraphInterrupt,\n LangGraphRunnableConfig,\n RemoteException,\n} from \"../web.js\";\nimport { StrRecord } from \"./algo.js\";\nimport { PregelInputType, PregelOptions, PregelOutputType } from \"./index.js\";\nimport { PregelNode } from \"./read.js\";\nimport {\n PregelParams,\n PregelInterface,\n PregelTaskDescription,\n StateSnapshot,\n StreamMode,\n} from \"./types.js\";\nimport {\n CHECKPOINT_NAMESPACE_SEPARATOR,\n CONFIG_KEY_STREAM,\n INTERRUPT,\n isCommand,\n} from \"../constants.js\";\nimport { propagateConfigurableToMetadata } from \"./utils/config.js\";\n\nexport type RemoteGraphParams = Omit<\n PregelParams<StrRecord<string, PregelNode>, StrRecord<string, BaseChannel>>,\n \"channels\" | \"nodes\" | \"inputChannels\" | \"outputChannels\"\n> & {\n graphId: string;\n client?: Client;\n url?: string;\n apiKey?: string;\n headers?: Record<string, string>;\n streamResumable?: boolean;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst _serializeInputs = (obj: any): any => {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(_serializeInputs);\n }\n\n // Handle BaseMessage instances by converting them to a serializable format\n if (BaseMessage.isInstance(obj)) {\n const dict = obj.toDict();\n return {\n ...dict.data,\n role: obj.getType(),\n };\n }\n\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => [key, _serializeInputs(value)])\n );\n};\n\n/**\n * Return a tuple of the final list of stream modes sent to the\n * remote graph and a boolean flag indicating if only one stream mode was\n * originally requested and whether stream mode 'updates'\n * was present in the original list of stream modes.\n *\n * 'updates' mode is always added to the list of stream modes so that interrupts\n * can be detected in the remote graph.\n */\nconst getStreamModes = (\n streamMode?: StreamMode | StreamMode[],\n defaultStreamMode: StreamMode = \"updates\"\n) => {\n const updatedStreamModes: StreamMode[] = [];\n let reqUpdates = false;\n let reqSingle = true;\n\n if (\n streamMode !== undefined &&\n (typeof streamMode === \"string\" ||\n (Array.isArray(streamMode) && streamMode.length > 0))\n ) {\n reqSingle = typeof streamMode === \"string\";\n const mapped = Array.isArray(streamMode) ? streamMode : [streamMode];\n updatedStreamModes.push(...mapped);\n } else {\n updatedStreamModes.push(defaultStreamMode);\n }\n if (updatedStreamModes.includes(\"updates\")) {\n reqUpdates = true;\n } else {\n updatedStreamModes.push(\"updates\");\n }\n return {\n updatedStreamModes,\n reqUpdates,\n reqSingle,\n };\n};\n\n/**\n * The `RemoteGraph` class is a client implementation for calling remote\n * APIs that implement the LangGraph Server API specification.\n *\n * For example, the `RemoteGraph` class can be used to call APIs from deployments\n * on LangSmith Deployment.\n *\n * `RemoteGraph` behaves the same way as a `StateGraph` and can be used directly as\n * a node in another `StateGraph`.\n *\n * @example\n * ```ts\n * import { RemoteGraph } from \"@langchain/langgraph/remote\";\n *\n * // Can also pass a LangGraph SDK client instance directly\n * const remoteGraph = new RemoteGraph({\n * graphId: process.env.LANGGRAPH_REMOTE_GRAPH_ID!,\n * apiKey: process.env.LANGGRAPH_REMOTE_GRAPH_API_KEY,\n * url: process.env.LANGGRAPH_REMOTE_GRAPH_API_URL,\n * });\n *\n * const input = {\n * messages: [\n * {\n * role: \"human\",\n * content: \"Hello world!\",\n * },\n * ],\n * };\n *\n * const config = {\n * configurable: { thread_id: \"threadId1\" },\n * };\n *\n * await remoteGraph.invoke(input, config);\n * ```\n */\nexport class RemoteGraph<\n Nn extends StrRecord<string, PregelNode> = StrRecord<string, PregelNode>,\n Cc extends StrRecord<string, BaseChannel> = StrRecord<string, BaseChannel>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ContextType extends Record<string, any> = StrRecord<string, any>,\n>\n extends Runnable<\n PregelInputType,\n PregelOutputType,\n PregelOptions<Nn, Cc, ContextType>\n >\n implements PregelInterface<Nn, Cc, ContextType>\n{\n static lc_name() {\n return \"RemoteGraph\";\n }\n\n lc_namespace = [\"langgraph\", \"pregel\"];\n\n lg_is_pregel = true;\n\n config?: RunnableConfig;\n\n graphId: string;\n\n protected client: Client;\n\n protected interruptBefore?: Array<keyof Nn> | All;\n\n protected interruptAfter?: Array<keyof Nn> | All;\n\n protected streamResumable?: boolean;\n\n constructor(params: RemoteGraphParams) {\n super(params);\n\n this.graphId = params.graphId;\n this.client =\n params.client ??\n new Client({\n apiUrl: params.url,\n apiKey: params.apiKey,\n defaultHeaders: params.headers,\n });\n this.config = params.config;\n this.interruptBefore = params.interruptBefore;\n this.interruptAfter = params.interruptAfter;\n this.streamResumable = params.streamResumable;\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore Remove ignore when we remove support for 0.2 versions of core\n override withConfig(config: RunnableConfig): typeof this {\n const mergedConfig = mergeConfigs(this.config, config);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new (this.constructor as any)({ ...this, config: mergedConfig });\n }\n\n protected _sanitizeConfig(config: RunnableConfig) {\n const reservedConfigurableKeys = new Set([\n \"callbacks\",\n \"checkpoint_map\",\n \"checkpoint_id\",\n \"checkpoint_ns\",\n ]);\n\n const sanitizeObj = <T>(obj: T): T => {\n try {\n // This will only throw if we're trying to serialize a circular reference\n // or trying to serialize a BigInt...\n JSON.stringify(obj);\n return obj;\n } catch {\n const seen = new WeakSet();\n return JSON.parse(\n JSON.stringify(obj, (_, value) => {\n if (typeof value === \"object\" && value != null) {\n if (seen.has(value)) return \"[Circular]\";\n seen.add(value);\n }\n\n if (typeof value === \"bigint\") return value.toString();\n return value;\n })\n );\n }\n };\n\n const propagateMetadataDefaults = (obj: unknown) => {\n const seen = new WeakSet<object>();\n const visit = (value: unknown) => {\n if (typeof value !== \"object\" || value == null) {\n return;\n }\n if (seen.has(value)) {\n return;\n }\n seen.add(value);\n const record = value as Record<string, unknown>;\n const configurable = record.configurable;\n if (\n typeof configurable === \"object\" &&\n configurable != null &&\n !Array.isArray(configurable)\n ) {\n const metadata =\n typeof record.metadata === \"object\" &&\n record.metadata != null &&\n !Array.isArray(record.metadata)\n ? (record.metadata as Record<string, unknown>)\n : undefined;\n record.metadata =\n propagateConfigurableToMetadata(\n configurable as Record<string, unknown>,\n metadata\n ) ?? record.metadata;\n }\n for (const nestedValue of Object.values(record)) {\n visit(nestedValue);\n }\n };\n visit(obj);\n };\n\n propagateMetadataDefaults(config);\n\n // Remove non-JSON serializable fields from the config\n const sanitizedConfig = sanitizeObj(config);\n\n // Only include configurable keys that are not reserved and\n // not starting with \"__pregel_\" prefix\n const newConfigurable = Object.fromEntries(\n Object.entries(sanitizedConfig.configurable ?? {}).filter(\n ([k]) => !reservedConfigurableKeys.has(k) && !k.startsWith(\"__pregel_\")\n )\n );\n\n return {\n tags: sanitizedConfig.tags ?? [],\n metadata: sanitizedConfig.metadata ?? {},\n configurable: newConfigurable,\n recursion_limit: sanitizedConfig.recursionLimit,\n };\n }\n\n protected _getConfig(checkpoint: Record<string, unknown>): RunnableConfig {\n return {\n configurable: {\n thread_id: checkpoint.thread_id,\n checkpoint_ns: checkpoint.checkpoint_ns,\n checkpoint_id: checkpoint.checkpoint_id,\n checkpoint_map: checkpoint.checkpoint_map ?? {},\n },\n };\n }\n\n protected _getCheckpoint(config?: RunnableConfig): Checkpoint | undefined {\n if (config?.configurable === undefined) {\n return undefined;\n }\n\n const checkpointKeys = [\n \"thread_id\",\n \"checkpoint_ns\",\n \"checkpoint_id\",\n \"checkpoint_map\",\n ] as const;\n\n const checkpoint = Object.fromEntries(\n checkpointKeys\n .map((key) => [key, config.configurable![key]])\n .filter(([_, value]) => value !== undefined)\n );\n\n return Object.keys(checkpoint).length > 0 ? checkpoint : undefined;\n }\n\n protected _createStateSnapshot(state: ThreadState): StateSnapshot {\n const tasks: PregelTaskDescription[] = state.tasks.map((task) => {\n return {\n id: task.id,\n name: task.name,\n error: task.error ? { message: task.error } : undefined,\n // TODO: remove in LangGraph.js 0.4\n interrupts: task.interrupts.map(({ id, ...rest }) => ({\n interrupt_id: id,\n ...rest,\n })),\n // eslint-disable-next-line no-nested-ternary\n state: task.state\n ? this._createStateSnapshot(task.state)\n : task.checkpoint\n ? { configurable: task.checkpoint }\n : undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n result: (task as any).result,\n };\n });\n\n return {\n values: state.values,\n next: state.next ? [...state.next] : [],\n config: {\n configurable: {\n thread_id: state.checkpoint.thread_id,\n checkpoint_ns: state.checkpoint.checkpoint_ns,\n checkpoint_id: state.checkpoint.checkpoint_id,\n checkpoint_map: state.checkpoint.checkpoint_map ?? {},\n },\n },\n metadata: state.metadata\n ? (state.metadata as CheckpointMetadata)\n : undefined,\n createdAt: state.created_at ?? undefined,\n parentConfig: state.parent_checkpoint\n ? {\n configurable: {\n thread_id: state.parent_checkpoint.thread_id,\n checkpoint_ns: state.parent_checkpoint.checkpoint_ns,\n checkpoint_id: state.parent_checkpoint.checkpoint_id,\n checkpoint_map: state.parent_checkpoint.checkpoint_map ?? {},\n },\n }\n : undefined,\n tasks,\n };\n }\n\n override async invoke(\n input: PregelInputType,\n options?: Partial<PregelOptions<Nn, Cc, ContextType>>\n ): Promise<PregelOutputType> {\n let lastValue;\n const stream = await this.stream(input, {\n ...options,\n streamMode: \"values\",\n });\n for await (const chunk of stream) {\n lastValue = chunk;\n }\n return lastValue;\n }\n\n override streamEvents(\n input: PregelInputType,\n options: Partial<PregelOptions<Nn, Cc, ContextType>> & {\n version: \"v1\" | \"v2\";\n }\n ): IterableReadableStream<StreamEvent>;\n\n override streamEvents(\n input: PregelInputType,\n options: Partial<PregelOptions<Nn, Cc, ContextType>> & {\n version: \"v1\" | \"v2\";\n encoding: never;\n }\n ): IterableReadableStream<never>;\n\n override streamEvents(\n _input: PregelInputType,\n _options: Partial<PregelOptions<Nn, Cc, ContextType>> & {\n version: \"v1\" | \"v2\";\n encoding?: never;\n }\n ): IterableReadableStream<StreamEvent> {\n throw new Error(\"Not implemented.\");\n }\n\n override async *_streamIterator(\n input: PregelInputType,\n options?: Partial<PregelOptions<Nn, Cc, ContextType>>\n ): AsyncGenerator<PregelOutputType> {\n const mergedConfig = mergeConfigs(this.config, options);\n const sanitizedConfig = this._sanitizeConfig(mergedConfig);\n\n const streamProtocolInstance = options?.configurable?.[CONFIG_KEY_STREAM];\n\n const streamSubgraphs =\n options?.subgraphs ?? streamProtocolInstance !== undefined;\n\n const interruptBefore = options?.interruptBefore ?? this.interruptBefore;\n const interruptAfter = options?.interruptAfter ?? this.interruptAfter;\n\n const { updatedStreamModes, reqSingle, reqUpdates } = getStreamModes(\n options?.streamMode\n );\n\n const extendedStreamModes = [\n ...new Set([\n ...updatedStreamModes,\n ...(streamProtocolInstance?.modes ?? new Set()),\n ]),\n ].map((mode) => {\n if (mode === \"messages\") return \"messages-tuple\";\n return mode;\n });\n\n let command;\n let serializedInput;\n if (isCommand(input)) {\n // TODO: Remove cast when SDK type fix gets merged\n command = input.toJSON() as Record<string, unknown>;\n serializedInput = undefined;\n } else {\n serializedInput = _serializeInputs(input);\n }\n\n for await (const chunk of this.client.runs.stream(\n sanitizedConfig.configurable.thread_id as string,\n this.graphId,\n {\n command,\n input: serializedInput,\n config: sanitizedConfig,\n streamMode: extendedStreamModes,\n interruptBefore: interruptBefore as string[],\n interruptAfter: interruptAfter as string[],\n streamSubgraphs,\n ifNotExists: \"create\",\n signal: mergedConfig.signal,\n streamResumable: this.streamResumable,\n }\n )) {\n let mode;\n let namespace: string[];\n if (chunk.event.includes(CHECKPOINT_NAMESPACE_SEPARATOR)) {\n const eventComponents = chunk.event.split(\n CHECKPOINT_NAMESPACE_SEPARATOR\n );\n // eslint-disable-next-line prefer-destructuring\n mode = eventComponents[0];\n namespace = eventComponents.slice(1);\n } else {\n mode = chunk.event;\n namespace = [];\n }\n const callerNamespace = options?.configurable?.checkpoint_ns;\n if (typeof callerNamespace === \"string\") {\n namespace = callerNamespace\n .split(CHECKPOINT_NAMESPACE_SEPARATOR)\n .concat(namespace);\n }\n if (\n streamProtocolInstance !== undefined &&\n streamProtocolInstance.modes?.has(chunk.event)\n ) {\n streamProtocolInstance.push([namespace, mode, chunk.data]);\n }\n if (chunk.event.startsWith(\"updates\")) {\n if (\n typeof chunk.data === \"object\" &&\n chunk.data?.[INTERRUPT] !== undefined\n ) {\n throw new GraphInterrupt(chunk.data[INTERRUPT]);\n }\n if (!reqUpdates) {\n continue;\n }\n } else if (chunk.event?.startsWith(\"error\")) {\n throw new RemoteException(\n typeof chunk.data === \"string\"\n ? chunk.data\n : JSON.stringify(chunk.data)\n );\n }\n if (\n !updatedStreamModes.includes(\n chunk.event.split(CHECKPOINT_NAMESPACE_SEPARATOR)[0] as StreamMode\n )\n ) {\n continue;\n }\n if (options?.subgraphs) {\n if (reqSingle) {\n yield [namespace, chunk.data];\n } else {\n yield [namespace, mode, chunk.data];\n }\n } else if (reqSingle) {\n yield chunk.data;\n } else {\n yield [mode, chunk.data];\n }\n }\n }\n\n async updateState(\n inputConfig: LangGraphRunnableConfig,\n values: Record<string, unknown>,\n asNode?: string\n ): Promise<RunnableConfig> {\n const mergedConfig = mergeConfigs(this.config, inputConfig);\n const response = await this.client.threads.updateState(\n mergedConfig.configurable?.thread_id,\n { values, asNode, checkpoint: this._getCheckpoint(mergedConfig) }\n );\n // TODO: Fix SDK typing\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return this._getConfig((response as any).checkpoint);\n }\n\n async *getStateHistory(\n config: RunnableConfig,\n options?: CheckpointListOptions\n ): AsyncIterableIterator<StateSnapshot> {\n const mergedConfig = mergeConfigs(this.config, config);\n const states = await this.client.threads.getHistory(\n mergedConfig.configurable?.thread_id,\n {\n limit: options?.limit ?? 10,\n // TODO: Fix type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n before: this._getCheckpoint(options?.before) as any,\n metadata: options?.filter,\n checkpoint: this._getCheckpoint(mergedConfig),\n }\n );\n for (const state of states) {\n yield this._createStateSnapshot(state);\n }\n }\n\n protected _getDrawableNodes(\n nodes: Array<{\n id: string | number;\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data?: Record<string, any> | string;\n metadata?: unknown;\n }>\n ): Record<string, DrawableNode> {\n const nodesMap: Record<string, DrawableNode> = {};\n for (const node of nodes) {\n const nodeId = node.id;\n nodesMap[nodeId] = {\n id: nodeId.toString(),\n name:\n typeof node.data === \"string\" ? node.data : (node.data?.name ?? \"\"),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data: (node.data as any) ?? {},\n metadata:\n typeof node.data !== \"string\" ? (node.data?.metadata ?? {}) : {},\n };\n }\n return nodesMap;\n }\n\n async getState(\n config: RunnableConfig,\n options?: { subgraphs?: boolean }\n ): Promise<StateSnapshot> {\n const mergedConfig = mergeConfigs(this.config, config);\n\n const state = await this.client.threads.getState(\n mergedConfig.configurable?.thread_id,\n this._getCheckpoint(mergedConfig),\n options\n );\n return this._createStateSnapshot(state);\n }\n\n /** @deprecated Use getGraphAsync instead. The async method will become the default in the next minor release. */\n override getGraph(\n _?: RunnableConfig & { xray?: boolean | number }\n ): DrawableGraph {\n throw new Error(\n `The synchronous \"getGraph\" is not supported for this graph. Call \"getGraphAsync\" instead.`\n );\n }\n\n /**\n * Returns a drawable representation of the computation graph.\n */\n async getGraphAsync(config?: RunnableConfig & { xray?: boolean | number }) {\n const graph = await this.client.assistants.getGraph(this.graphId, {\n xray: config?.xray,\n });\n return new DrawableGraph({\n nodes: this._getDrawableNodes(graph.nodes),\n edges: graph.edges,\n });\n }\n\n /** @deprecated Use getSubgraphsAsync instead. The async method will become the default in the next minor release. */\n getSubgraphs(): Generator<[string, PregelInterface<Nn, Cc, ContextType>]> {\n throw new Error(\n `The synchronous \"getSubgraphs\" method is not supported for this graph. Call \"getSubgraphsAsync\" instead.`\n );\n }\n\n async *getSubgraphsAsync(\n namespace?: string,\n recurse = false\n ): AsyncGenerator<[string, PregelInterface<Nn, Cc, ContextType>]> {\n const subgraphs = await this.client.assistants.getSubgraphs(this.graphId, {\n namespace,\n recurse,\n });\n\n for (const [ns, graphSchema] of Object.entries(subgraphs)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const remoteSubgraph = new (this.constructor as any)({\n ...this,\n graphId: graphSchema.graph_id,\n });\n yield [ns, remoteSubgraph];\n }\n }\n}\n"],"mappings":";;;;;;;;;AA4DA,MAAM,oBAAoB,QAAkB;AAC1C,KAAI,QAAQ,QAAQ,OAAO,QAAQ,SACjC,QAAO;AAGT,KAAI,MAAM,QAAQ,IAAI,CACpB,QAAO,IAAI,IAAI,iBAAiB;AAIlC,KAAIA,yBAAAA,YAAY,WAAW,IAAI,CAE7B,QAAO;EACL,GAFW,IAAI,QAAQ,CAEf;EACR,MAAM,IAAI,SAAS;EACpB;AAGH,QAAO,OAAO,YACZ,OAAO,QAAQ,IAAI,CAAC,KAAK,CAAC,KAAK,WAAW,CAAC,KAAK,iBAAiB,MAAM,CAAC,CAAC,CAC1E;;;;;;;;;;;AAYH,MAAM,kBACJ,YACA,oBAAgC,cAC7B;CACH,MAAM,qBAAmC,EAAE;CAC3C,IAAI,a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AU,CAMvD,OAAM,CAAC,IAJgB,IAAK,KAAK,YAAoB;GACnD,GAAG;GACH,SAAS,YAAY;GACtB,CAAC,CACwB"}
|
|
1
|
+
{"version":3,"file":"remote.cjs","names":["BaseMessage","Runnable","Client","propagateConfigurableToMetadata","#prepareRunRequest","CONFIG_KEY_STREAM","isCommand","GraphInterrupt","INTERRUPT","RemoteException","DrawableGraph"],"sources":["../../src/pregel/remote.ts"],"sourcesContent":["import {\n Client,\n type Checkpoint,\n type ThreadState,\n} from \"@langchain/langgraph-sdk\";\nimport {\n Graph as DrawableGraph,\n Node as DrawableNode,\n} from \"@langchain/core/runnables/graph\";\nimport {\n mergeConfigs,\n Runnable,\n RunnableConfig,\n} from \"@langchain/core/runnables\";\nimport {\n All,\n CheckpointListOptions,\n CheckpointMetadata,\n} from \"@langchain/langgraph-checkpoint\";\nimport { StreamEvent } from \"@langchain/core/tracers/log_stream\";\nimport { IterableReadableStream } from \"@langchain/core/utils/stream\";\nimport { BaseMessage } from \"@langchain/core/messages\";\n\nimport {\n BaseChannel,\n GraphInterrupt,\n LangGraphRunnableConfig,\n RemoteException,\n} from \"../web.js\";\nimport { StrRecord } from \"./algo.js\";\nimport { PregelInputType, PregelOptions, PregelOutputType } from \"./index.js\";\nimport { PregelNode } from \"./read.js\";\nimport {\n PregelParams,\n PregelInterface,\n PregelTaskDescription,\n StateSnapshot,\n StreamMode,\n} from \"./types.js\";\nimport {\n CHECKPOINT_NAMESPACE_SEPARATOR,\n CONFIG_KEY_STREAM,\n INTERRUPT,\n isCommand,\n} from \"../constants.js\";\nimport { propagateConfigurableToMetadata } from \"./utils/config.js\";\n\nexport type RemoteGraphParams = Omit<\n PregelParams<StrRecord<string, PregelNode>, StrRecord<string, BaseChannel>>,\n \"channels\" | \"nodes\" | \"inputChannels\" | \"outputChannels\"\n> & {\n graphId: string;\n client?: Client;\n url?: string;\n apiKey?: string;\n headers?: Record<string, string>;\n streamResumable?: boolean;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst _serializeInputs = (obj: any): any => {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(_serializeInputs);\n }\n\n // Handle BaseMessage instances by converting them to a serializable format\n if (BaseMessage.isInstance(obj)) {\n const dict = obj.toDict();\n return {\n ...dict.data,\n role: obj.getType(),\n };\n }\n\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => [key, _serializeInputs(value)])\n );\n};\n\n/**\n * Return a tuple of the final list of stream modes sent to the\n * remote graph and a boolean flag indicating if only one stream mode was\n * originally requested and whether stream mode 'updates'\n * was present in the original list of stream modes.\n *\n * 'updates' mode is always added to the list of stream modes so that interrupts\n * can be detected in the remote graph.\n */\nconst getStreamModes = (\n streamMode?: StreamMode | StreamMode[],\n defaultStreamMode: StreamMode = \"updates\"\n) => {\n const updatedStreamModes: StreamMode[] = [];\n let reqUpdates = false;\n let reqSingle = true;\n\n if (\n streamMode !== undefined &&\n (typeof streamMode === \"string\" ||\n (Array.isArray(streamMode) && streamMode.length > 0))\n ) {\n reqSingle = typeof streamMode === \"string\";\n const mapped = Array.isArray(streamMode) ? streamMode : [streamMode];\n updatedStreamModes.push(...mapped);\n } else {\n updatedStreamModes.push(defaultStreamMode);\n }\n if (updatedStreamModes.includes(\"updates\")) {\n reqUpdates = true;\n } else {\n updatedStreamModes.push(\"updates\");\n }\n return {\n updatedStreamModes,\n reqUpdates,\n reqSingle,\n };\n};\n\n/**\n * The `RemoteGraph` class is a client implementation for calling remote\n * APIs that implement the LangGraph Server API specification.\n *\n * For example, the `RemoteGraph` class can be used to call APIs from deployments\n * on LangSmith Deployment.\n *\n * `RemoteGraph` behaves the same way as a `StateGraph` and can be used directly as\n * a node in another `StateGraph`.\n *\n * @example\n * ```ts\n * import { RemoteGraph } from \"@langchain/langgraph/remote\";\n *\n * // Can also pass a LangGraph SDK client instance directly\n * const remoteGraph = new RemoteGraph({\n * graphId: process.env.LANGGRAPH_REMOTE_GRAPH_ID!,\n * apiKey: process.env.LANGGRAPH_REMOTE_GRAPH_API_KEY,\n * url: process.env.LANGGRAPH_REMOTE_GRAPH_API_URL,\n * });\n *\n * const input = {\n * messages: [\n * {\n * role: \"human\",\n * content: \"Hello world!\",\n * },\n * ],\n * };\n *\n * const config = {\n * configurable: { thread_id: \"threadId1\" },\n * };\n *\n * await remoteGraph.invoke(input, config);\n * ```\n */\nexport class RemoteGraph<\n Nn extends StrRecord<string, PregelNode> = StrRecord<string, PregelNode>,\n Cc extends StrRecord<string, BaseChannel> = StrRecord<string, BaseChannel>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ContextType extends Record<string, any> = StrRecord<string, any>,\n>\n extends Runnable<\n PregelInputType,\n PregelOutputType,\n PregelOptions<Nn, Cc, ContextType>\n >\n implements PregelInterface<Nn, Cc, ContextType>\n{\n static lc_name() {\n return \"RemoteGraph\";\n }\n\n lc_namespace = [\"langgraph\", \"pregel\"];\n\n lg_is_pregel = true;\n\n config?: RunnableConfig;\n\n graphId: string;\n\n protected client: Client;\n\n protected interruptBefore?: Array<keyof Nn> | All;\n\n protected interruptAfter?: Array<keyof Nn> | All;\n\n protected streamResumable?: boolean;\n\n constructor(params: RemoteGraphParams) {\n super(params);\n\n this.graphId = params.graphId;\n this.client =\n params.client ??\n new Client({\n apiUrl: params.url,\n apiKey: params.apiKey,\n defaultHeaders: params.headers,\n });\n this.config = params.config;\n this.interruptBefore = params.interruptBefore;\n this.interruptAfter = params.interruptAfter;\n this.streamResumable = params.streamResumable;\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore Remove ignore when we remove support for 0.2 versions of core\n override withConfig(config: RunnableConfig): typeof this {\n const mergedConfig = mergeConfigs(this.config, config);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new (this.constructor as any)({ ...this, config: mergedConfig });\n }\n\n protected _sanitizeConfig(config: RunnableConfig) {\n const reservedConfigurableKeys = new Set([\n \"callbacks\",\n \"checkpoint_map\",\n \"checkpoint_id\",\n \"checkpoint_ns\",\n ]);\n\n const sanitizeObj = <T>(obj: T): T => {\n try {\n // This will only throw if we're trying to serialize a circular reference\n // or trying to serialize a BigInt...\n JSON.stringify(obj);\n return obj;\n } catch {\n const seen = new WeakSet();\n return JSON.parse(\n JSON.stringify(obj, (_, value) => {\n if (typeof value === \"object\" && value != null) {\n if (seen.has(value)) return \"[Circular]\";\n seen.add(value);\n }\n\n if (typeof value === \"bigint\") return value.toString();\n return value;\n })\n );\n }\n };\n\n const propagateMetadataDefaults = (obj: unknown) => {\n const seen = new WeakSet<object>();\n const visit = (value: unknown) => {\n if (typeof value !== \"object\" || value == null) {\n return;\n }\n if (seen.has(value)) {\n return;\n }\n seen.add(value);\n const record = value as Record<string, unknown>;\n const configurable = record.configurable;\n if (\n typeof configurable === \"object\" &&\n configurable != null &&\n !Array.isArray(configurable)\n ) {\n const metadata =\n typeof record.metadata === \"object\" &&\n record.metadata != null &&\n !Array.isArray(record.metadata)\n ? (record.metadata as Record<string, unknown>)\n : undefined;\n record.metadata =\n propagateConfigurableToMetadata(\n configurable as Record<string, unknown>,\n metadata\n ) ?? record.metadata;\n }\n for (const nestedValue of Object.values(record)) {\n visit(nestedValue);\n }\n };\n visit(obj);\n };\n\n propagateMetadataDefaults(config);\n\n // Remove non-JSON serializable fields from the config\n const sanitizedConfig = sanitizeObj(config);\n\n // Only include configurable keys that are not reserved and\n // not starting with \"__pregel_\" prefix\n const newConfigurable = Object.fromEntries(\n Object.entries(sanitizedConfig.configurable ?? {}).filter(\n ([k]) => !reservedConfigurableKeys.has(k) && !k.startsWith(\"__pregel_\")\n )\n );\n\n return {\n tags: sanitizedConfig.tags ?? [],\n metadata: sanitizedConfig.metadata ?? {},\n configurable: newConfigurable,\n recursion_limit: sanitizedConfig.recursionLimit,\n };\n }\n\n /**\n * Prepare config and thread ID for remote run API calls.\n *\n * `thread_id` is passed via the URL path, not in `config.configurable`, so the\n * server can accept a separate `context` payload for stateful runs.\n */\n #prepareRunRequest(mergedConfig: LangGraphRunnableConfig): {\n threadId: string | undefined;\n context: unknown;\n config: ReturnType<RemoteGraph[\"_sanitizeConfig\"]>;\n } {\n const context = mergedConfig.context;\n const sanitizedConfig = this._sanitizeConfig(mergedConfig);\n const configurable = { ...sanitizedConfig.configurable };\n const threadId = configurable.thread_id as string | undefined;\n delete configurable.thread_id;\n\n return {\n threadId,\n context,\n config: {\n ...sanitizedConfig,\n configurable,\n },\n };\n }\n\n protected _getConfig(checkpoint: Record<string, unknown>): RunnableConfig {\n return {\n configurable: {\n thread_id: checkpoint.thread_id,\n checkpoint_ns: checkpoint.checkpoint_ns,\n checkpoint_id: checkpoint.checkpoint_id,\n checkpoint_map: checkpoint.checkpoint_map ?? {},\n },\n };\n }\n\n protected _checkpointToConfig(\n checkpoint?: Partial<Checkpoint> | null,\n fallbackConfig?: RunnableConfig\n ): RunnableConfig {\n const resolvedCheckpoint =\n checkpoint ?? this._getCheckpoint(fallbackConfig);\n if (resolvedCheckpoint == null) {\n return { configurable: {} };\n }\n\n const configurable: Record<string, unknown> = {};\n if (resolvedCheckpoint.thread_id !== undefined) {\n configurable.thread_id = resolvedCheckpoint.thread_id;\n }\n if (resolvedCheckpoint.checkpoint_ns !== undefined) {\n configurable.checkpoint_ns = resolvedCheckpoint.checkpoint_ns;\n }\n if (resolvedCheckpoint.checkpoint_id !== undefined) {\n configurable.checkpoint_id = resolvedCheckpoint.checkpoint_id;\n }\n\n const hasCheckpointFields =\n resolvedCheckpoint.checkpoint_ns !== undefined ||\n resolvedCheckpoint.checkpoint_id !== undefined ||\n resolvedCheckpoint.checkpoint_map !== undefined;\n if (hasCheckpointFields) {\n configurable.checkpoint_map = resolvedCheckpoint.checkpoint_map ?? {};\n }\n\n return { configurable };\n }\n\n protected _getCheckpoint(config?: RunnableConfig): Checkpoint | undefined {\n if (config?.configurable === undefined) {\n return undefined;\n }\n\n const checkpointKeys = [\n \"thread_id\",\n \"checkpoint_ns\",\n \"checkpoint_id\",\n \"checkpoint_map\",\n ] as const;\n\n const checkpoint = Object.fromEntries(\n checkpointKeys\n .map((key) => [key, config.configurable![key]])\n .filter(([_, value]) => value !== undefined)\n );\n\n return Object.keys(checkpoint).length > 0 ? checkpoint : undefined;\n }\n\n protected _createStateSnapshot(\n state: ThreadState,\n fallbackConfig?: RunnableConfig\n ): StateSnapshot {\n const tasks: PregelTaskDescription[] = state.tasks.map((task) => {\n return {\n id: task.id,\n name: task.name,\n error: task.error ? { message: task.error } : undefined,\n // TODO: remove in LangGraph.js 0.4\n interrupts: task.interrupts.map(({ id, ...rest }) => ({\n interrupt_id: id,\n ...rest,\n })),\n // eslint-disable-next-line no-nested-ternary\n state: task.state\n ? this._createStateSnapshot(\n task.state,\n task.checkpoint\n ? this._checkpointToConfig(task.checkpoint)\n : fallbackConfig\n )\n : task.checkpoint\n ? { configurable: task.checkpoint }\n : undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n result: (task as any).result,\n };\n });\n\n return {\n values: state.values,\n next: state.next ? [...state.next] : [],\n // TODO: Fix SDK typing. `ThreadState.checkpoint` is typed as non-null,\n // but deployments can return `null` (e.g. a thread that exists but has\n // not produced a checkpoint yet). See #2328.\n config: this._checkpointToConfig(\n state.checkpoint as Checkpoint | null,\n fallbackConfig\n ),\n metadata: state.metadata\n ? (state.metadata as CheckpointMetadata)\n : undefined,\n createdAt: state.created_at ?? undefined,\n parentConfig: state.parent_checkpoint\n ? this._checkpointToConfig(state.parent_checkpoint)\n : undefined,\n tasks,\n };\n }\n\n override async invoke(\n input: PregelInputType,\n options?: Partial<PregelOptions<Nn, Cc, ContextType>>\n ): Promise<PregelOutputType> {\n let lastValue;\n const stream = await this.stream(input, {\n ...options,\n streamMode: \"values\",\n });\n for await (const chunk of stream) {\n lastValue = chunk;\n }\n return lastValue;\n }\n\n override streamEvents(\n input: PregelInputType,\n options: Partial<PregelOptions<Nn, Cc, ContextType>> & {\n version: \"v1\" | \"v2\";\n }\n ): IterableReadableStream<StreamEvent>;\n\n override streamEvents(\n input: PregelInputType,\n options: Partial<PregelOptions<Nn, Cc, ContextType>> & {\n version: \"v1\" | \"v2\";\n encoding: never;\n }\n ): IterableReadableStream<never>;\n\n override streamEvents(\n _input: PregelInputType,\n _options: Partial<PregelOptions<Nn, Cc, ContextType>> & {\n version: \"v1\" | \"v2\";\n encoding?: never;\n }\n ): IterableReadableStream<StreamEvent> {\n throw new Error(\"Not implemented.\");\n }\n\n override async *_streamIterator(\n input: PregelInputType,\n options?: Partial<PregelOptions<Nn, Cc, ContextType>>\n ): AsyncGenerator<PregelOutputType> {\n const mergedConfig = mergeConfigs(\n this.config,\n options\n ) as LangGraphRunnableConfig;\n const {\n threadId,\n context,\n config: sanitizedConfig,\n } = this.#prepareRunRequest(mergedConfig);\n\n const streamProtocolInstance = options?.configurable?.[CONFIG_KEY_STREAM];\n\n const streamSubgraphs =\n options?.subgraphs ?? streamProtocolInstance !== undefined;\n\n const interruptBefore = options?.interruptBefore ?? this.interruptBefore;\n const interruptAfter = options?.interruptAfter ?? this.interruptAfter;\n\n const { updatedStreamModes, reqSingle, reqUpdates } = getStreamModes(\n options?.streamMode\n );\n\n const extendedStreamModes = [\n ...new Set([\n ...updatedStreamModes,\n ...(streamProtocolInstance?.modes ?? new Set()),\n ]),\n ].map((mode) => {\n if (mode === \"messages\") return \"messages-tuple\";\n return mode;\n });\n\n let command;\n let serializedInput;\n if (isCommand(input)) {\n // TODO: Remove cast when SDK type fix gets merged\n command = input.toJSON() as Record<string, unknown>;\n serializedInput = undefined;\n } else {\n serializedInput = _serializeInputs(input);\n }\n\n const streamPayload = {\n command,\n input: serializedInput,\n config: sanitizedConfig,\n context,\n streamMode: extendedStreamModes,\n interruptBefore: interruptBefore as string[],\n interruptAfter: interruptAfter as string[],\n streamSubgraphs,\n ifNotExists: \"create\" as const,\n signal: mergedConfig.signal,\n streamResumable: this.streamResumable,\n };\n\n const runStream =\n threadId != null\n ? this.client.runs.stream(threadId, this.graphId, streamPayload)\n : this.client.runs.stream(null, this.graphId, streamPayload);\n\n for await (const chunk of runStream) {\n let mode;\n let namespace: string[];\n if (chunk.event.includes(CHECKPOINT_NAMESPACE_SEPARATOR)) {\n const eventComponents = chunk.event.split(\n CHECKPOINT_NAMESPACE_SEPARATOR\n );\n // eslint-disable-next-line prefer-destructuring\n mode = eventComponents[0];\n namespace = eventComponents.slice(1);\n } else {\n mode = chunk.event;\n namespace = [];\n }\n const callerNamespace = options?.configurable?.checkpoint_ns;\n if (typeof callerNamespace === \"string\") {\n namespace = callerNamespace\n .split(CHECKPOINT_NAMESPACE_SEPARATOR)\n .concat(namespace);\n }\n if (\n streamProtocolInstance !== undefined &&\n streamProtocolInstance.modes?.has(chunk.event)\n ) {\n streamProtocolInstance.push([namespace, mode, chunk.data]);\n }\n if (chunk.event.startsWith(\"updates\")) {\n if (\n typeof chunk.data === \"object\" &&\n chunk.data?.[INTERRUPT] !== undefined\n ) {\n throw new GraphInterrupt(chunk.data[INTERRUPT]);\n }\n if (!reqUpdates) {\n continue;\n }\n } else if (chunk.event?.startsWith(\"error\")) {\n throw new RemoteException(\n typeof chunk.data === \"string\"\n ? chunk.data\n : JSON.stringify(chunk.data)\n );\n }\n if (\n !updatedStreamModes.includes(\n chunk.event.split(CHECKPOINT_NAMESPACE_SEPARATOR)[0] as StreamMode\n )\n ) {\n continue;\n }\n if (options?.subgraphs) {\n if (reqSingle) {\n yield [namespace, chunk.data];\n } else {\n yield [namespace, mode, chunk.data];\n }\n } else if (reqSingle) {\n yield chunk.data;\n } else {\n yield [mode, chunk.data];\n }\n }\n }\n\n async updateState(\n inputConfig: LangGraphRunnableConfig,\n values: Record<string, unknown>,\n asNode?: string\n ): Promise<RunnableConfig> {\n const mergedConfig = mergeConfigs(this.config, inputConfig);\n const response = await this.client.threads.updateState(\n mergedConfig.configurable?.thread_id,\n { values, asNode, checkpoint: this._getCheckpoint(mergedConfig) }\n );\n // TODO: Fix SDK typing\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return this._getConfig((response as any).checkpoint);\n }\n\n async *getStateHistory(\n config: RunnableConfig,\n options?: CheckpointListOptions\n ): AsyncIterableIterator<StateSnapshot> {\n const mergedConfig = mergeConfigs(this.config, config);\n const states = await this.client.threads.getHistory(\n mergedConfig.configurable?.thread_id,\n {\n limit: options?.limit ?? 10,\n // TODO: Fix type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n before: this._getCheckpoint(options?.before) as any,\n metadata: options?.filter,\n checkpoint: this._getCheckpoint(mergedConfig),\n }\n );\n for (const state of states) {\n yield this._createStateSnapshot(state, mergedConfig);\n }\n }\n\n protected _getDrawableNodes(\n nodes: Array<{\n id: string | number;\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data?: Record<string, any> | string;\n metadata?: unknown;\n }>\n ): Record<string, DrawableNode> {\n const nodesMap: Record<string, DrawableNode> = {};\n for (const node of nodes) {\n const nodeId = node.id;\n nodesMap[nodeId] = {\n id: nodeId.toString(),\n name:\n typeof node.data === \"string\" ? node.data : (node.data?.name ?? \"\"),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data: (node.data as any) ?? {},\n metadata:\n typeof node.data !== \"string\" ? (node.data?.metadata ?? {}) : {},\n };\n }\n return nodesMap;\n }\n\n async getState(\n config: RunnableConfig,\n options?: { subgraphs?: boolean }\n ): Promise<StateSnapshot> {\n const mergedConfig = mergeConfigs(this.config, config);\n\n const state = await this.client.threads.getState(\n mergedConfig.configurable?.thread_id,\n this._getCheckpoint(mergedConfig),\n options\n );\n return this._createStateSnapshot(state, mergedConfig);\n }\n\n /** @deprecated Use getGraphAsync instead. The async method will become the default in the next minor release. */\n override getGraph(\n _?: RunnableConfig & { xray?: boolean | number }\n ): DrawableGraph {\n throw new Error(\n `The synchronous \"getGraph\" is not supported for this graph. Call \"getGraphAsync\" instead.`\n );\n }\n\n /**\n * Returns a drawable representation of the computation graph.\n */\n async getGraphAsync(config?: RunnableConfig & { xray?: boolean | number }) {\n const graph = await this.client.assistants.getGraph(this.graphId, {\n xray: config?.xray,\n });\n return new DrawableGraph({\n nodes: this._getDrawableNodes(graph.nodes),\n edges: graph.edges,\n });\n }\n\n /** @deprecated Use getSubgraphsAsync instead. The async method will become the default in the next minor release. */\n getSubgraphs(): Generator<[string, PregelInterface<Nn, Cc, ContextType>]> {\n throw new Error(\n `The synchronous \"getSubgraphs\" method is not supported for this graph. Call \"getSubgraphsAsync\" instead.`\n );\n }\n\n async *getSubgraphsAsync(\n namespace?: string,\n recurse = false\n ): AsyncGenerator<[string, PregelInterface<Nn, Cc, ContextType>]> {\n const subgraphs = await this.client.assistants.getSubgraphs(this.graphId, {\n namespace,\n recurse,\n });\n\n for (const [ns, graphSchema] of Object.entries(subgraphs)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const remoteSubgraph = new (this.constructor as any)({\n ...this,\n graphId: graphSchema.graph_id,\n });\n yield [ns, remoteSubgraph];\n }\n }\n}\n"],"mappings":";;;;;;;;;AA4DA,MAAM,oBAAoB,QAAkB;AAC1C,KAAI,QAAQ,QAAQ,OAAO,QAAQ,SACjC,QAAO;AAGT,KAAI,MAAM,QAAQ,IAAI,CACpB,QAAO,IAAI,IAAI,iBAAiB;AAIlC,KAAIA,yBAAAA,YAAY,WAAW,IAAI,CAE7B,QAAO;EACL,GAFW,IAAI,QAAQ,CAEf;EACR,MAAM,IAAI,SAAS;EACpB;AAGH,QAAO,OAAO,YACZ,OAAO,QAAQ,IAAI,CAAC,KAAK,CAAC,KAAK,WAAW,CAAC,KAAK,iBAAiB,MAAM,CAAC,CAAC,CAC1E;;;;;;;;;;;AAYH,MAAM,kBACJ,YACA,oBAAgC,cAC7B;CACH,MAAM,qBAAmC,EAAE;CAC3C,IAAI,aAAa;CACjB,IAAI,YAAY;AAEhB,KACE,eAAe,KAAA,MACd,OAAO,eAAe,YACpB,MAAM,QAAQ,WAAW,IAAI,WAAW,SAAS,IACpD;AACA,cAAY,OAAO,eAAe;EAClC,MAAM,SAAS,M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,EACjC,QACD;AACD,SAAO,KAAK,qBAAqB,OAAO,aAAa;;;CAIvD,SACE,GACe;AACf,QAAM,IAAI,MACR,4FACD;;;;;CAMH,MAAM,cAAc,QAAuD;EACzE,MAAM,QAAQ,MAAM,KAAK,OAAO,WAAW,SAAS,KAAK,SAAS,EAChE,MAAM,QAAQ,MACf,CAAC;AACF,SAAO,IAAIC,gCAAAA,MAAc;GACvB,OAAO,KAAK,kBAAkB,MAAM,MAAM;GAC1C,OAAO,MAAM;GACd,CAAC;;;CAIJ,eAA0E;AACxE,QAAM,IAAI,MACR,2GACD;;CAGH,OAAO,kBACL,WACA,UAAU,OACsD;EAChE,MAAM,YAAY,MAAM,KAAK,OAAO,WAAW,aAAa,KAAK,SAAS;GACxE;GACA;GACD,CAAC;AAEF,OAAK,MAAM,CAAC,IAAI,gBAAgB,OAAO,QAAQ,UAAU,CAMvD,OAAM,CAAC,IAJgB,IAAK,KAAK,YAAoB;GACnD,GAAG;GACH,SAAS,YAAY;GACtB,CAAC,CACwB"}
|
package/dist/pregel/remote.d.cts
CHANGED
|
@@ -57,6 +57,7 @@ type RemoteGraphParams = Omit<PregelParams<StrRecord<string, PregelNode>, StrRec
|
|
|
57
57
|
* ```
|
|
58
58
|
*/
|
|
59
59
|
declare class RemoteGraph<Nn extends StrRecord<string, PregelNode> = StrRecord<string, PregelNode>, Cc extends StrRecord<string, BaseChannel> = StrRecord<string, BaseChannel>, ContextType extends Record<string, any> = StrRecord<string, any>> extends Runnable<PregelInputType, PregelOutputType, PregelOptions<Nn, Cc, ContextType>> implements PregelInterface<Nn, Cc, ContextType> {
|
|
60
|
+
#private;
|
|
60
61
|
static lc_name(): string;
|
|
61
62
|
lc_namespace: string[];
|
|
62
63
|
lg_is_pregel: boolean;
|
|
@@ -77,8 +78,9 @@ declare class RemoteGraph<Nn extends StrRecord<string, PregelNode> = StrRecord<s
|
|
|
77
78
|
recursion_limit: number | undefined;
|
|
78
79
|
};
|
|
79
80
|
protected _getConfig(checkpoint: Record<string, unknown>): RunnableConfig;
|
|
81
|
+
protected _checkpointToConfig(checkpoint?: Partial<Checkpoint$1> | null, fallbackConfig?: RunnableConfig): RunnableConfig;
|
|
80
82
|
protected _getCheckpoint(config?: RunnableConfig): Checkpoint$1 | undefined;
|
|
81
|
-
protected _createStateSnapshot(state: ThreadState): StateSnapshot;
|
|
83
|
+
protected _createStateSnapshot(state: ThreadState, fallbackConfig?: RunnableConfig): StateSnapshot;
|
|
82
84
|
invoke(input: PregelInputType, options?: Partial<PregelOptions<Nn, Cc, ContextType>>): Promise<PregelOutputType>;
|
|
83
85
|
streamEvents(input: PregelInputType, options: Partial<PregelOptions<Nn, Cc, ContextType>> & {
|
|
84
86
|
version: "v1" | "v2";
|