State
State
Another important aspect of LangGraph is the concept of State. The basic graph example in the previous section didn’t use any state except for the output passed from one node to be used as the input for the next. The problem with this, though, is that it’s difficult to access the state of a node that came much earlier in the graph. In a two-node graph, it’s no problem, but what if you had ten nodes? How would the eighth node know what the second node did?
To solve this problem, you’ll define a State for most graphs. The nodes will then modify this state as they obtain it.
You define a State class like so:
from typing import TypedDict
class MyState(TypedDict):
key_1: list[str]
key_2: int
You can call your State class anything you like. Usually, it’ll subclass TypedDict. That means the state is a dictionary of the types you define in your class. You can add as many keys to the dictionary as needed. The data type for each entry follows the key name.
Note: LangGraph also supports a Pydantic
BaseModelinstead ofTypedDictif you prefer to define your state that way.
By default, when nodes modify the state, the values are replaced. If you’d prefer to append values to a list, you can use the add reducer function. Here’s the modified example from above:
from typing import TypedDict, Annotated
from operator import add
class MyState(TypedDict):
key_1: Annotated[list[str], add]
key_2: int
Annotated is a type that lets you add additional information to another type. In this case, LangGraph uses it to indicate that modifications should be appended to the list rather than replacing it.
Once you’ve defined your State, you can use StateGraph to create the graph.
from langgraph.graph import StateGraph
graph = StateGraph(MyState)
This informs the graph that the input and output of each node will have the schema you defined in your State class.