langchain.js
    Preparing search index...

    Class StateGraph<SD, S, U, N, I, O, C, NodeReturnType, InterruptType, WriterType>

    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<State>.

    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 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.

    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<string>,
    messages: Annotation<BaseMessage[]>({
    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",
    // }

    Type Parameters

    • SD extends StateDefinitionInit | unknown

      The state definition used to construct the graph. Can be an AnnotationRoot, StateSchema, or Zod object schema. This is the primary generic from which S and U are derived.

    • S = ExtractStateType<SD>

      The full state type representing the complete shape of your graph's state after all reducers have been applied. Automatically inferred from SD.

    • U = ExtractUpdateType<SD, S>

      The update type representing what nodes can return to modify state. Typically a partial of the state type. Automatically inferred from SD.

    • N extends string = typeof START

      Union of all node names in the graph (e.g., "agent" | "tool"). Accumulated as you call .addNode(). Used for type-safe routing.

    • I extends StateDefinitionInit = ExtractStateDefinition<SD>

      The input schema definition. Set via the input option in the constructor to restrict what data the graph accepts when invoked.

    • O extends StateDefinitionInit = ExtractStateDefinition<SD>

      The output schema definition. Set via the output option in the constructor to restrict what data the graph returns after execution.

    • C extends StateDefinitionInit = StateDefinition

      The config/context schema definition. Set via the context option to define additional configuration passed at runtime.

    • NodeReturnType = unknown

      Constrains what types nodes in this graph can return.

    • InterruptType = unknown

      The type for interrupt resume values. Set via the interrupt option for typed human-in-the-loop patterns.

    • WriterType = unknown

      The type for custom stream writers. Set via the writer option to enable typed custom streaming from within nodes.

    Hierarchy (View Summary)

    • Graph<N, S, U, StateGraphNodeSpec<S, U>, ToStateDefinition<C>>
      • StateGraph
    Index

    Constructors

    • Create a new StateGraph for building stateful, multi-step workflows.

      Accepts state definitions via Annotation.Root, StateSchema, or Zod schemas.

      Type Parameters

      • SD extends unknown
      • S = ExtractStateType<SD>
      • U = ExtractUpdateType<SD, S>
      • N extends string = "__start__"
      • I extends StateDefinitionInit = ExtractStateDefinition<SD>
      • O extends StateDefinitionInit = ExtractStateDefinition<SD>
      • C extends StateDefinitionInit = StateDefinition
      • NodeReturnType = unknown
      • InterruptType = unknown
      • WriterType = unknown

      Parameters

      Returns StateGraph<SD, S, U, N, I, O, C, NodeReturnType, InterruptType, WriterType>

      const StateAnnotation = Annotation.Root({
      messages: Annotation<string[]>({ reducer: (a, b) => [...a, ...b] }),
      });
      const graph = new StateGraph(StateAnnotation);
      const graph = new StateGraph(StateAnnotation, {
      input: InputSchema,
      output: OutputSchema,
      });
      const graph = new StateGraph({
      state: FullStateSchema,
      input: InputSchema,
      output: OutputSchema,
      });
      const graph = new StateGraph({
      input: InputAnnotation,
      output: OutputAnnotation,
      });
    • Type Parameters

      • SD extends unknown
      • S = ExtractStateType<SD>
      • U = ExtractUpdateType<SD, S>
      • N extends string = "__start__"
      • I extends StateDefinitionInit = ExtractStateDefinition<SD>
      • O extends StateDefinitionInit = ExtractStateDefinition<SD>
      • C extends StateDefinitionInit = StateDefinition
      • NodeReturnType = unknown
      • InterruptType = unknown
      • WriterType = unknown

      Parameters

      Returns StateGraph<SD, S, U, N, I, O, C, NodeReturnType, InterruptType, WriterType>

    • Type Parameters

      • SD extends unknown
      • S = ExtractStateType<SD>
      • U = ExtractUpdateType<SD, S>
      • N extends string = "__start__"
      • I extends StateDefinitionInit = ExtractStateDefinition<SD>
      • O extends StateDefinitionInit = ExtractStateDefinition<SD>
      • C extends StateDefinitionInit = StateDefinition
      • NodeReturnType = unknown
      • InterruptType = unknown
      • WriterType = unknown

      Parameters

      • fields: SD extends StateDefinition
            ? | AnnotationRoot<SD<SD>>
            | StateGraphArgsWithStateSchema<
                SD<SD>,
                ToStateDefinition<I>,
                ToStateDefinition<O>,
            >
            : never
      • OptionalcontextSchema: C | AnnotationRoot<ToStateDefinition<C>>

      Returns StateGraph<SD, S, U, N, I, O, C, NodeReturnType, InterruptType, WriterType>

    • Type Parameters

      • SD extends unknown
      • S = ExtractStateType<SD>
      • U = ExtractUpdateType<SD, S>
      • N extends string = "__start__"
      • I extends StateDefinitionInit = ExtractStateDefinition<SD>
      • O extends StateDefinitionInit = ExtractStateDefinition<SD>
      • C extends StateDefinitionInit = StateDefinition
      • NodeReturnType = unknown
      • InterruptType = unknown
      • WriterType = unknown

      Parameters

      • init: Omit<
            StateGraphInit<
                SD extends StateDefinitionInit ? SD<SD> : StateDefinitionInit,
                SD extends StateDefinitionInit ? SD<SD> : StateDefinitionInit,
                O,
                C extends ContextSchemaInit ? C<C> : undefined,
                N,
                InterruptType,
                WriterType,
            >,
            "input" | "state" | "stateSchema",
        > & {
            input: SD extends StateDefinitionInit ? SD<SD> : never;
            state?: undefined;
            stateSchema?: undefined;
        }
      • OptionalcontextSchema: C | AnnotationRoot<ToStateDefinition<C>>

      Returns StateGraph<SD, S, U, N, I, O, C, NodeReturnType, InterruptType, WriterType>

    • Type Parameters

      • SD extends unknown
      • S = ExtractStateType<SD>
      • U = ExtractUpdateType<SD, S>
      • N extends string = "__start__"
      • I extends StateDefinitionInit = ExtractStateDefinition<SD>
      • O extends StateDefinitionInit = ExtractStateDefinition<SD>
      • C extends StateDefinitionInit = StateDefinition
      • NodeReturnType = unknown
      • InterruptType = unknown
      • WriterType = unknown

      Parameters

      Returns StateGraph<SD, S, U, N, I, O, C, NodeReturnType, InterruptType, WriterType>

    • Type Parameters

      • SD extends unknown
      • S = ExtractStateType<SD>
      • U = ExtractUpdateType<SD, S>
      • N extends string = "__start__"
      • I extends StateDefinitionInit = ExtractStateDefinition<SD>
      • O extends StateDefinitionInit = ExtractStateDefinition<SD>
      • C extends StateDefinitionInit = StateDefinition
      • NodeReturnType = unknown
      • InterruptType = unknown
      • WriterType = unknown

      Parameters

      Returns StateGraph<SD, S, U, N, I, O, C, NodeReturnType, InterruptType, WriterType>

      Use Annotation.Root, StateSchema, or Zod schemas instead.

    Properties

    branches: Record<string, Record<string, Branch<RunInput, N, any>>>
    channels: Record<string, BaseChannel> = {}
    compiled: boolean = false
    edges: Set<["__start__" | N, "__end__" | N]>
    entryPoint?: string
    Node: StrictNodeAction<S, U, C, N, InterruptType, WriterType>
    nodes: Record<N, NodeSpecType>
    waitingEdges: Set<[N[], N]> = ...

    Accessors

    • get allEdges(): Set<[string, string]>

      Returns Set<[string, string]>

    Methods

    • Parameters

      • stateDefinition: StateDefinitionInit

      Returns void

    • Parameters

      Returns this

    • Parameters

      • source: N
      • path: RunnableLike<
            S,
            BranchPathReturnValue,
            LangGraphRunnableConfig<StateType<ToStateDefinition<C>>>,
        >
      • OptionalpathMap: Record<string, "__end__" | N> | ("__end__" | N)[]

      Returns this

    • Parameters

      • startKey: "__start__" | N | N[]
      • endKey: "__end__" | N

      Returns this

    • Type Parameters

      Parameters

      Returns StateGraph<
          SD,
          S,
          U,
          N
          | K,
          I,
          O,
          C,
          MergeReturnType<
              NodeReturnType,
              {
                  [key in string
                  | number
                  | symbol]: NodeMap[key] extends NodeAction<
                      S,
                      U,
                      C,
                      InterruptType,
                      WriterType,
                  >
                      ? U
                      : never
              },
          >,
      >

    • Type Parameters

      • K extends string
      • NodeInput = S
      • NodeOutput = U

      Parameters

      Returns StateGraph<
          SD,
          S,
          U,
          N
          | K,
          I,
          O,
          C,
          MergeReturnType<NodeReturnType, { [key in string]: NodeOutput }>,
      >

    • Type Parameters

      • K extends string
      • InputSchema extends StateDefinitionInit
      • NodeOutput = U

      Parameters

      Returns StateGraph<
          SD,
          S,
          U,
          N
          | K,
          I,
          O,
          C,
          MergeReturnType<NodeReturnType, { [key in string]: NodeOutput }>,
      >

    • Type Parameters

      • K extends string
      • InputSchema extends StateDefinitionInit
      • NodeOutput = U

      Parameters

      Returns StateGraph<
          SD,
          S,
          U,
          N
          | K,
          I,
          O,
          C,
          MergeReturnType<NodeReturnType, { [key in string]: NodeOutput }>,
      >

    • Type Parameters

      • K extends string
      • NodeInput = S
      • NodeOutput = U

      Parameters

      Returns StateGraph<
          SD,
          S,
          U,
          N
          | K,
          I,
          O,
          C,
          MergeReturnType<NodeReturnType, { [key in string]: NodeOutput }>,
      >

    • Type Parameters

      • K extends string
      • NodeInput = S

      Parameters

      Returns StateGraph<SD, S, U, N | K, I, O, C, NodeReturnType>

    • Type Parameters

      • K extends string
      • NodeInput = S
      • NodeOutput = U

      Parameters

      Returns StateGraph<
          SD,
          S,
          U,
          N
          | K,
          I,
          O,
          C,
          MergeReturnType<NodeReturnType, { [key in string]: NodeOutput }>,
      >

    • Type Parameters

      Parameters

      Returns StateGraph<
          SD,
          S,
          U,
          N
          | K,
          I,
          O,
          C,
          MergeReturnType<
              NodeReturnType,
              {
                  [key in string
                  | number
                  | symbol]: NodeMap[key] extends NodeAction<
                      S,
                      U,
                      C,
                      InterruptType,
                      WriterType,
                  >
                      ? U
                      : never
              },
          >,
      >

    • Parameters

      • __namedParameters: {
            cache?: any;
            checkpointer?: any;
            description?: string;
            interruptAfter?: any;
            interruptBefore?: any;
            name?: string;
            store?: any;
        } = {}

      Returns CompiledStateGraph<
          { [K in string
          | number
          | symbol]: S[K] },
          { [K in string | number | symbol]: U[K] },
          N,
          I,
          O,
          C,
          NodeReturnType,
          InterruptType,
          WriterType,
      >

    • Parameters

      • key: N

      Returns this

      use addEdge(START, key) instead

    • Parameters

      • key: N

      Returns this

      use addEdge(key, END) instead

    • Parameters

      • Optionalinterrupt: string[]

      Returns void

    • Parameters

      • message: string

      Returns void