LangGraph StateGraph explained
Quick answer
The
StateGraph in langgraph is a Python class for building stateful, graph-based AI agents by defining nodes as functions that transform state dictionaries. You add nodes, define edges, set an entry point, compile the graph, and invoke it with initial state to run the agent logic.PREREQUISITES
Python 3.8+pip install langgraphBasic Python knowledge
Setup
Install the langgraph package via pip and prepare your environment.
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 a typed state dictionary, create node functions that accept and return state, add nodes and edges to StateGraph, set the entry point, compile the graph, and invoke it with initial state.
from langgraph.graph import StateGraph, END
from typing import TypedDict
# Define the state type
class State(TypedDict):
messages: list[str]
# Define a node function
def my_node(state: State) -> State:
new_messages = state["messages"] + ["Hello from LangGraph!"]
return {"messages": new_messages}
# Create the graph
graph = StateGraph(State)
# Add node and edges
graph.add_node("my_node", my_node)
graph.set_entry_point("my_node")
graph.add_edge("my_node", END)
# Compile and invoke
app = graph.compile()
result = app.invoke({"messages": []})
print(result) # {'messages': ['Hello from LangGraph!']} output
{'messages': ['Hello from LangGraph!']} Common variations
You can define multiple nodes with different state transformations, add branching edges between nodes, and use asynchronous node functions if needed. The END constant marks terminal nodes. State can hold any serializable data.
from langgraph.graph import StateGraph, END
from typing import TypedDict
import asyncio
class State(TypedDict):
count: int
async def increment(state: State) -> State:
return {"count": state["count"] + 1}
def check_limit(state: State) -> State:
if state["count"] < 3:
return state
else:
return state
graph = StateGraph(State)
graph.add_node("increment", increment)
graph.add_node("check_limit", check_limit)
graph.set_entry_point("increment")
graph.add_edge("increment", "check_limit")
graph.add_edge("check_limit", "increment")
graph.add_edge("check_limit", END)
app = graph.compile()
import asyncio
result = asyncio.run(app.invoke({"count": 0}))
print(result) # {'count': 3} output
{'count': 3} Troubleshooting
- If you see
TypeErrorabout state types, ensure your state dictionary matches theTypedDictdefinition. - If
app.invoke()hangs, check for cycles without terminalENDedges. - For async nodes, use
asyncio.run()to invoke the compiled graph.
Key Takeaways
- Use
StateGraphto build AI agents as state-transforming node graphs. - Define state with
TypedDictfor type safety and clarity. - Add nodes as functions that accept and return state dictionaries.
- Set entry point and edges to control graph flow, ending with
END. - Compile the graph and invoke it with initial state to run your agent.