LangChain Reference home pageLangChain ReferenceLangChain Reference
  • GitHub
  • Main Docs
Deep Agents
LangChain
LangGraph
Integrations
LangSmith
LangGraph
  • Web
  • Channels
  • Pregel
  • Prebuilt
  • Remote
LangGraph SDK
  • Client
  • Auth
  • React
  • Logging
  • React Ui
  • Server
LangGraph Checkpoint
LangGraph Checkpoint MongoDB
LangGraph Checkpoint Postgres
  • Store
LangGraph Checkpoint Redis
  • Shallow
  • Store
LangGraph Checkpoint SQLite
LangGraph Checkpoint Validation
  • Cli
LangGraph API
LangGraph CLI
LangGraph CUA
  • Utils
LangGraph Supervisor
LangGraph Swarm
⌘I

LangChain Assistant

Ask a question to get started

Enter to send•Shift+Enter new line

Menu

LangGraph
WebChannelsPregelPrebuiltRemote
LangGraph SDK
ClientAuthReactLoggingReact UiServer
LangGraph Checkpoint
LangGraph Checkpoint MongoDB
LangGraph Checkpoint Postgres
Store
LangGraph Checkpoint Redis
ShallowStore
LangGraph Checkpoint SQLite
LangGraph Checkpoint Validation
Cli
LangGraph API
LangGraph CLI
LangGraph CUA
Utils
LangGraph Supervisor
LangGraph Swarm
Language
Theme
JavaScript@langchain/langgraphwebStateGraph
Class●Since v0.3

StateGraph

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.

Copy
class StateGraph

Bases

Graph<N, S, U, StateGraphNodeSpec<S, U>, ToStateDefinition<C>>

Used in Docs

  • Build a custom RAG agent with LangGraph
  • Build a custom SQL agent
  • Build a multi-source knowledge base with routing
  • Choosing between Graph and Functional APIs
  • Custom workflow
(13 more not shown)

Example

Copy
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",
// }

Constructors

constructor
constructor

Properties

property
branches: Record<string, Record<string, Branch<RunInput, N, any>>>
property
channels: Record<string, BaseChannel>

The channels in the graph, mapping channel names to their BaseChannel or ManagedValueSpec instances

property
compiled: boolean
property
edges: Set<["__start__" | N, "__end__" | N]>
property
entryPoint: string
property
Node: StrictNodeAction<S, U, C, N, InterruptType, WriterType>
property
nodes: Record<N, NodeSpecType>

The nodes in the graph, mapping node names to their PregelNode instances

property
waitingEdges: Set<[N[], N]>
property
allEdges: Set<[string, string]>

Methods

method
_addSchema
method
addConditionalEdges→ this
method
addEdge→ this
method
addNode→ Graph<N | K, RunInput, RunOutput>
method
addSequence→ StateGraph<SD, S, U, N | K, I, O, C, MergeReturnType<NodeReturnType, { [key in string]: NodeOutput }>>
method
compile→ CompiledGraph<N>
method
validate→ this

Validates the graph structure to ensure it is well-formed. Checks for:

  • No orphaned nodes
  • Valid input/output channel configurations
  • Valid interrupt configurations
method
warnIfCompiled
deprecatedmethod
setEntryPoint→ this
deprecatedmethod
setFinishPoint→ this

Inherited fromGraph

Properties

Pbranches: Record<string, Record<string, Branch<RunInput, N, any>>>Pcompiled: booleanPedges: Set<[N | "__start__", N | "__end__"]>PentryPoint: stringPnodes: Nodes
—

The nodes in the graph, mapping node names to their PregelNode instances

PallEdges: Set<[string, string]>

Methods

MaddConditionalEdges→ thisMaddEdge→ thisMaddNode→ Graph<N | K, RunInput, RunOutput>Mcompile→ CompiledGraph<N>MsetEntryPoint→ thisMsetFinishPoint→ thisMvalidate→ this
—

Validates the graph structure to ensure it is well-formed.

MwarnIfCompiled
View source on GitHub