How to beginner · 3 min read

How to define state in LangGraph

Quick answer
In LangGraph, define state by creating a TypedDict that specifies the structure of your state data. This state type is then used as a generic parameter for StateGraph, enabling type-safe state management across nodes.

PREREQUISITES

  • Python 3.8+
  • pip install langgraph
  • Basic knowledge of Python typing and TypedDict

Setup

Install the langgraph package via pip to use StateGraph and related classes. Ensure you have Python 3.8 or newer for TypedDict support.

bash
pip install langgraph
output
Collecting langgraph
  Downloading langgraph-0.1.0-py3-none-any.whl (10 kB)
Installing collected packages: langgraph
Successfully installed langgraph-0.1.0

Step by step

Define your state as a TypedDict to specify the keys and types your graph nodes will use. Then create a StateGraph with this state type. Add nodes that accept and return this state, and invoke the graph with an initial state.

python
from langgraph.graph import StateGraph, END
from typing import TypedDict

# Define the state structure
class State(TypedDict):
    messages: list[str]

# Define a node function that updates the state
def my_node(state: State) -> State:
    new_messages = state["messages"] + ["Hello from LangGraph"]
    return {"messages": new_messages}

# Create the graph with the State type
graph = StateGraph(State)
graph.add_node("my_node", my_node)
graph.set_entry_point("my_node")
graph.add_edge("my_node", END)

# Compile and invoke the graph
app = graph.compile()
result = app.invoke({"messages": ["Start"]})
print(result["messages"])
output
['Start', 'Hello from LangGraph']

Common variations

  • You can define more complex state with multiple keys and nested types using TypedDict.
  • State can be immutable or mutable depending on your node logic, but returning a new state dict is recommended.
  • Use END to mark graph termination points.

Troubleshooting

If you get type errors, ensure your TypedDict keys and types exactly match the state your nodes return. Also, confirm you set the entry point before compiling the graph.

Key Takeaways

  • Use Python's TypedDict to define structured state for LangGraph.
  • Pass the state type as a generic to StateGraph for type safety.
  • Nodes receive and return the full state dict, enabling state updates.
  • Always set an entry point and add edges to END to complete the graph.
  • Return new state dicts from nodes to avoid mutation bugs.
Verified 2026-04
Verify ↗