import { BaseChannel } from "../channels/base.cjs"; import { TimeoutPolicy } from "../pregel/utils/timeout.cjs"; import { Command, CommandInstance, END, INTERRUPT, Interrupt, START } from "../constants.cjs"; import { SchemaMetaRegistry } from "./zod/meta.cjs"; import { RunnableLike, Runtime } from "../pregel/runnable_types.cjs"; import { AnnotationRoot, SingleReducer, StateDefinition, StateType } from "./annotation.cjs"; import { CachePolicy, RetryPolicy } from "../pregel/utils/index.cjs"; import { StreamTransformer } from "../stream/types.cjs"; import { AnyStateSchema } from "../state/schema.cjs"; import { ContextSchemaInit, ExtractStateType, ExtractUpdateType, StateDefinitionInit, StateGraphInit, StateGraphOptions, ToStateDefinition } from "./types.cjs"; import { AddNodeOptions, Branch, CompiledGraph, Graph, NodeErrorHandler, NodeSpec } from "./graph.cjs"; import { InferInterruptInputType, InferInterruptResumeType } from "../interrupt.cjs"; import { InferWriterType } from "../writer.cjs"; import { All, BaseCache, BaseCheckpointSaver, BaseStore } from "@langchain/langgraph-checkpoint"; import { InteropZodObject } from "@langchain/core/utils/types"; //#region src/graph/state.d.ts type ChannelReducers = { [K in keyof Channels]: SingleReducer }; interface StateGraphArgs { channels: Channels extends object ? Channels extends unknown[] ? ChannelReducers<{ __root__: Channels; }> : ChannelReducers : ChannelReducers<{ __root__: Channels; }>; } /** * Retry and cache policies configurable on graph nodes. * * Use with {@link StateGraph.addNode} for per-node overrides, or with * {@link StateGraph.setNodeDefaults} for graph-wide defaults applied at * `compile()` time. Per-node values always take precedence over defaults. * `setNodeDefaults` may be called before or after `addNode`, including as the * last step before `compile()`. */ type NodePolicyOptions = { /** * Retry policy controlling backoff, max attempts, and which errors trigger * a retry. * * @see {@link RetryPolicy} */ retryPolicy?: RetryPolicy; /** * Cache policy controlling how node results are keyed and how long they * persist. * * - Pass a {@link CachePolicy} object for fine-grained control (e.g. custom * `keyFunc`, `ttl`). * - Pass `true` to enable caching with default settings. * - Pass `false` to disable caching. * * @see {@link CachePolicy} */ cachePolicy?: CachePolicy | boolean; /** * Maximum duration for a single attempt of this node. Accepts a number of * milliseconds (a hard wall-clock cap) or a {@link TimeoutPolicy} for finer * control over run / idle timeouts. When exceeded, a {@link NodeTimeoutError} * is raised and the node's retry policy (if any) decides whether to retry. * * @see {@link TimeoutPolicy} */ timeout?: number | TimeoutPolicy; }; /** * Resolved retry and cache policies stored on a node after boolean * `cachePolicy` shorthand is normalized. * * @internal */ type NodePolicies = { retryPolicy?: RetryPolicy; /** `false` opts out of graph defaults set via {@link StateGraph.setNodeDefaults}. */ cachePolicy?: CachePolicy | false; /** Resolved timeout policy after the `number` shorthand is normalized. */ timeout?: TimeoutPolicy; }; /** * Graph-wide node defaults captured by {@link StateGraph.setNodeDefaults} and * resolved at {@link StateGraph.compile} time. * * @internal */ type ResolvedNodeDefaults = NodePolicies & { /** * Default error handler applied to every regular node that does not set its * own via `addNode(..., { errorHandler })`. Never applied to error-handler * nodes themselves — handlers must not catch their own failures. */ errorHandler?: NodeErrorHandler; }; type StateGraphNodeSpec = NodeSpec & NodePolicies & { input?: StateDefinition; }; /** * Options for StateGraph.addNode() method. * * @template Nodes - Node name constraints * @template InputSchema - Per-node input schema type (inferred from options.input) * @template HandlerState - State type passed to the node-level error handler * @template Update - The update type the error handler may return */ type StateGraphAddNodeOptions : unknown), Update = unknown> = { input?: InputSchema; /** * Optional node-level error handler. Runs only after this node's * {@link RetryPolicy} is exhausted. Receives a {@link NodeError} with the * failed node name and error, and may return a state update or `Command`. */ errorHandler?: NodeErrorHandler; } & NodePolicyOptions & AddNodeOptions; type StateGraphAddNodeOptionsWithNodeInput = StateGraphAddNodeOptions; type StateGraphArgsWithStateSchema = { stateSchema: AnnotationRoot; input?: AnnotationRoot; output?: AnnotationRoot; }; type StateGraphArgsWithInputOutputSchemas = { input: AnnotationRoot; output: AnnotationRoot; }; type ExtractStateDefinition = T extends AnyStateSchema ? T : T extends StateDefinitionInit ? ToStateDefinition : StateDefinition; type NodeAction = RunnableLike : U, Runtime>, InterruptType, WriterType>>; type StrictNodeAction = RunnableLike, U | Command, U & Record, Nodes>, Runtime>, InterruptType, WriterType>>; declare const PartialStateSchema: unique symbol; type PartialStateSchema = typeof PartialStateSchema; type MergeReturnType = Prev & Curr extends infer T ? { [K in keyof T]: T[K] } & unknown : never; type Prettify = { [K in keyof T]: T[K] } & {}; /** * A graph whose nodes communicate by reading and writing to a shared state. * Each node takes a defined `State` as input and returns a `Partial`. * * Each state key can optionally be annotated with a reducer function that * will be used to aggregate the values of that key received from multiple nodes. * The signature of a reducer function is (left: Value, right: UpdateValue) => Value. * * See {@link Annotation} for more on defining state. * * After adding nodes and edges to your graph, you must call `.compile()` on it before * you can use it. * * @typeParam SD - The state definition used to construct the graph. Can be an * {@link AnnotationRoot}, {@link StateSchema}, or Zod object schema. This is the * primary generic from which `S` and `U` are derived. * * @typeParam S - The full state type representing the complete shape of your graph's * state after all reducers have been applied. Automatically inferred from `SD`. * * @typeParam U - The update type representing what nodes can return to modify state. * Typically a partial of the state type. Automatically inferred from `SD`. * * @typeParam N - Union of all node names in the graph (e.g., `"agent" | "tool"`). * Accumulated as you call `.addNode()`. Used for type-safe routing. * * @typeParam I - The input schema definition. Set via the `input` option in the * constructor to restrict what data the graph accepts when invoked. * * @typeParam O - The output schema definition. Set via the `output` option in the * constructor to restrict what data the graph returns after execution. * * @typeParam C - The config/context schema definition. Set via the `context` option * to define additional configuration passed at runtime. * * @typeParam NodeReturnType - Constrains what types nodes in this graph can return. * * @typeParam InterruptType - The type for {@link interrupt} resume values. Set via * the `interrupt` option for typed human-in-the-loop patterns. * * @typeParam WriterType - The type for custom stream writers. Set via the `writer` * option to enable typed custom streaming from within nodes. * * @example * ```ts * import { * type BaseMessage, * AIMessage, * HumanMessage, * } from "@langchain/core/messages"; * import { StateGraph, Annotation } from "@langchain/langgraph"; * * // Define a state with a single key named "messages" that will * // combine a returned BaseMessage or arrays of BaseMessages * const StateAnnotation = Annotation.Root({ * sentiment: Annotation, * messages: Annotation({ * reducer: (left: BaseMessage[], right: BaseMessage | BaseMessage[]) => { * if (Array.isArray(right)) { * return left.concat(right); * } * return left.concat([right]); * }, * default: () => [], * }), * }); * * const graphBuilder = new StateGraph(StateAnnotation); * * // A node in the graph that returns an object with a "messages" key * // will update the state by combining the existing value with the returned one. * const myNode = (state: typeof StateAnnotation.State) => { * return { * messages: [new AIMessage("Some new response")], * sentiment: "positive", * }; * }; * * const graph = graphBuilder * .addNode("myNode", myNode) * .addEdge("__start__", "myNode") * .addEdge("myNode", "__end__") * .compile(); * * await graph.invoke({ messages: [new HumanMessage("how are you?")] }); * * // { * // messages: [HumanMessage("how are you?"), AIMessage("Some new response")], * // sentiment: "positive", * // } * ``` */ declare class StateGraph, U = ExtractUpdateType, N extends string = typeof START, I extends StateDefinitionInit = ExtractStateDefinition, O extends StateDefinitionInit = ExtractStateDefinition, C extends StateDefinitionInit = StateDefinition, NodeReturnType = unknown, InterruptType = unknown, WriterType = unknown> extends Graph, ToStateDefinition> { channels: Record; waitingEdges: Set<[N[], N]>; /** @internal */ _schemaDefinition: StateDefinition; /** @internal */ _schemaRuntimeDefinition: InteropZodObject | AnyStateSchema | undefined; /** @internal */ _inputDefinition: I; /** @internal */ _inputRuntimeDefinition: InteropZodObject | AnyStateSchema | PartialStateSchema | undefined; /** @internal */ _outputDefinition: O; /** @internal */ _outputRuntimeDefinition: InteropZodObject | AnyStateSchema | undefined; /** * Map schemas to managed values * @internal */ _schemaDefinitions: Map; /** @internal */ _metaRegistry: SchemaMetaRegistry; /** @internal Used only for typing. */ _configSchema: ToStateDefinition | undefined; /** @internal */ _configRuntimeSchema: InteropZodObject | undefined; /** @internal */ _interrupt: InterruptType; /** @internal */ _writer: WriterType; /** * Graph-wide default node policies, resolved at `compile()` time. * @internal */ _nodeDefaults: ResolvedNodeDefaults; Node: StrictNodeAction; /** * Create a new StateGraph for building stateful, multi-step workflows. * * Accepts state definitions via `Annotation.Root`, `StateSchema`, or Zod schemas. * * @example Direct schema * ```ts * const StateAnnotation = Annotation.Root({ * messages: Annotation({ reducer: (a, b) => [...a, ...b] }), * }); * const graph = new StateGraph(StateAnnotation); * ``` * * @example Direct schema with input/output filtering * ```ts * const graph = new StateGraph(StateAnnotation, { * input: InputSchema, * output: OutputSchema, * }); * ``` * * @example Object pattern with state, input, output * ```ts * const graph = new StateGraph({ * state: FullStateSchema, * input: InputSchema, * output: OutputSchema, * }); * ``` * * @example Input/output only (state inferred from input) * ```ts * const graph = new StateGraph({ * input: InputAnnotation, * output: OutputAnnotation, * }); * ``` */ constructor(state: SD extends StateDefinitionInit ? SD : never, options?: C | AnnotationRoot> | StateGraphOptions); constructor(fields: SD extends StateDefinition ? StateGraphArgsWithInputOutputSchemas> : never, contextSchema?: C | AnnotationRoot>); constructor(fields: SD extends StateDefinition ? AnnotationRoot | StateGraphArgsWithStateSchema, ToStateDefinition> : never, contextSchema?: C | AnnotationRoot>); constructor(init: Omit, "state" | "stateSchema" | "input"> & { input: SD extends StateDefinitionInit ? SD : never; state?: never; stateSchema?: never; }, contextSchema?: C | AnnotationRoot>); constructor(init: StateGraphInit); /** @deprecated Use `Annotation.Root`, `StateSchema`, or Zod schemas instead. */ constructor(fields: StateGraphArgs, contextSchema?: C | AnnotationRoot>); /** * Set graph-wide default node policies that apply to every node in this * graph. * * Per-node values passed to {@link addNode} always take precedence over these * defaults. Defaults are resolved at {@link compile} time, so call order does * not matter — you may call this before or after `addNode`, including as the * last step before `compile()`. Calling it multiple times merges the provided * fields, with later calls overriding earlier ones on a per-field basis. * * Policies set here are **not** inherited by subgraphs. * * `retryPolicy` and `timeout` defaults apply to **all** nodes, including * auto-generated error-handler nodes. `cachePolicy` and `errorHandler` * defaults apply to **regular nodes only** — caching an error-handler result * is unsafe, and a handler must never catch its own (or another handler's) * failure. * * @param defaults - The default node policies to apply. * @returns The builder instance, for chaining. * * @example Call before `addNode` * ```ts * const graph = new StateGraph(State) * .setNodeDefaults({ * retryPolicy: { maxAttempts: 3 }, * cachePolicy: { ttl: 60 }, * timeout: 60_000, * errorHandler: (state, { node, error }) => ({ lastError: error.message }), * }) * .addNode("a", nodeA) * .addNode("b", nodeB, { retryPolicy: { maxAttempts: 5 } }) // overrides default * .addEdge(START, "a") * .compile(); * ``` * * @example Call after `addNode`, immediately before `compile()` * ```ts * const graph = new StateGraph(State) * .addNode("a", nodeA) * .addNode("b", nodeB, { retryPolicy: { maxAttempts: 5 } }) // overrides default * .addEdge(START, "a") * .setNodeDefaults({ * retryPolicy: { maxAttempts: 3 }, * cachePolicy: { ttl: 60 }, * }) * .compile(); * ``` */ setNodeDefaults(defaults: NodePolicyOptions & { /** * Default node-level error handler invoked when any **regular** node * raises and does not have its own handler set via * `addNode(..., { errorHandler })`. Runs only after the failing node's * retry policy is exhausted. It is never invoked when an error-handler * node itself raises — handler failures fail the run. * * Because a single shared handler serves every node, its `state` * argument is typed as `unknown`: at runtime it receives the **failing * node's input** (see `addNode(..., { input })`), which may be a subset * of the graph state and differs per node. Narrow it yourself before * reading fields. The handler may still return a graph-level update (`U`) * or route via `new Command({ goto })` to any node (`N`). */ errorHandler?: NodeErrorHandler; }): this; /** * Build the shared spec for a graph-wide default error handler, or * `undefined` when {@link setNodeDefaults} did not configure one. The spec is * installed under {@link DEFAULT_ERROR_HANDLER_NODE} for the duration of a * single {@link compile} call and routes failures from every regular node * that lacks its own handler. * @internal */ protected _createDefaultErrorHandlerSpec(): StateGraphNodeSpec | undefined; /** * Normalize all constructor input patterns to a unified StateGraphInit object. * @internal */ private _normalizeToStateGraphInit; /** * Convert any supported schema type to a StateDefinition (channel map). * @internal */ private _getChannelsFromSchema; get allEdges(): Set<[string, string]>; _addSchema(stateDefinition: StateDefinitionInit): void; addNode>>(nodes: NodeMap): StateGraph ? U : never }>>; addNode(nodes: [key: K, action: NodeAction, options?: StateGraphAddNodeOptionsWithNodeInput][]): StateGraph>; addNode(key: K, action: NodeAction, NodeOutput, C, InterruptType, WriterType>, options: StateGraphAddNodeOptions, U>): StateGraph>; addNode(key: K, action: NodeAction, NodeOutput, C, InterruptType, WriterType>, options: StateGraphAddNodeOptions, U>): StateGraph>; addNode(key: K, action: NodeAction, options?: StateGraphAddNodeOptionsWithNodeInput): StateGraph>; addNode(key: K, action: NodeAction, options?: StateGraphAddNodeOptionsWithNodeInput): StateGraph; addEdge(startKey: typeof START | N | N[], endKey: N | typeof END): this; addSequence(nodes: [key: K, action: NodeAction, options?: StateGraphAddNodeOptionsWithNodeInput][]): StateGraph>; addSequence>>(nodes: NodeMap): StateGraph ? U : never }>>; compile StreamTransformer> = []>({ checkpointer, store, cache, interruptBefore, interruptAfter, name, description, transformers }?: { checkpointer?: BaseCheckpointSaver | boolean; store?: BaseStore; cache?: BaseCache; interruptBefore?: N[] | All; interruptAfter?: N[] | All; name?: string; description?: string; /** * Stream transformer factories baked into the compiled graph. These run * automatically for every `streamEvents(..., { version: "v3" })` call, * before any call-site transformers. */ transformers?: TTransformers; }): CompiledStateGraph, Prettify, N, I, O, C, NodeReturnType, InterruptType, WriterType, TTransformers>; /** @internal */ protected _compileResolved StreamTransformer> = []>({ checkpointer, store, cache, interruptBefore, interruptAfter, name, description, transformers, defaultErrorHandlerNode }: { checkpointer?: BaseCheckpointSaver | boolean; store?: BaseStore; cache?: BaseCache; interruptBefore?: N[] | All; interruptAfter?: N[] | All; name?: string; description?: string; transformers?: TTransformers; defaultErrorHandlerNode?: string; }): CompiledStateGraph, Prettify, N, I, O, C, NodeReturnType, InterruptType, WriterType, TTransformers>; } /** * Final result from building and compiling a {@link StateGraph}. * Should not be instantiated directly, only using the StateGraph `.compile()` * instance method. * * @typeParam S - The full state type representing the complete shape of your graph's * state after all reducers have been applied. This is the type you receive when * reading state in nodes or after invoking the graph. * * @typeParam U - The update type representing what nodes can return to modify state. * Typically a partial of the state type, allowing nodes to update only specific fields. * Can also include {@link Command} objects for advanced control flow. * * @typeParam N - Union of all node names in the graph (e.g., `"agent" | "tool"`). * Used for type-safe routing with {@link Command.goto} and edge definitions. * * @typeParam I - The input schema definition. Determines what shape of data the graph * accepts when invoked. Defaults to the main state schema if not explicitly set. * * @typeParam O - The output schema definition. Determines what shape of data the graph * returns after execution. Defaults to the main state schema if not explicitly set. * * @typeParam C - The config/context schema definition. Defines additional configuration * that can be passed to the graph at runtime via {@link LangGraphRunnableConfig}. * * @typeParam NodeReturnType - Constrains what types nodes in this graph can return. * Useful for enforcing consistent return patterns across all nodes. * * @typeParam InterruptType - The type of values that can be passed when resuming from * an {@link interrupt}. Used with human-in-the-loop patterns. * * @typeParam WriterType - The type for custom stream writers. Used with the `writer` * option to enable typed custom streaming from within nodes. * * @typeParam TStreamTransformers - Stream transformer factories registered at * compile time via the `transformers` option. Used to type extensions on * `streamEvents(..., { version: "v3" })`. */ declare class CompiledStateGraph StreamTransformer> = []> extends CompiledGraph, ExtractUpdateType>, ExtractStateType, NodeReturnType, CommandInstance, Prettify, N>, InferWriterType, TStreamTransformers> { builder: StateGraph; /** * The description of the compiled graph. * This is used by the supervisor agent to describe the handoff to the agent. */ description?: string; /** @internal */ _metaRegistry: SchemaMetaRegistry; constructor({ description, ...rest }: { description?: string; } & ConstructorParameters, ExtractUpdateType>, ExtractStateType, NodeReturnType, CommandInstance, Prettify, N>, InferWriterType, TStreamTransformers>>[0]); attachNode(key: typeof START, node?: never): void; attachNode(key: N, node: StateGraphNodeSpec): void; attachEdge(starts: N | N[] | "__start__", end: N | "__end__"): void; attachBranch(start: N | typeof START, _: string, branch: Branch, options?: { withReader?: boolean; }): void; protected _validateInput(input: ExtractUpdateType>): Promise>>; isInterrupted(input: unknown): input is { [INTERRUPT]: Interrupt>[]; }; protected _validateContext(config: Partial>): Promise>>; } //#endregion export { CompiledStateGraph, NodePolicyOptions, StateGraph, StateGraphAddNodeOptions, StateGraphArgs, StateGraphArgsWithInputOutputSchemas, StateGraphArgsWithStateSchema, StateGraphNodeSpec }; //# sourceMappingURL=state.d.cts.map