State#
In langgraph, the state in langgraph determines the information that the node receives from the previous step and passes on to the following step. This page looks at the details of working with different schemas.
from langchain_core.messages import HumanMessage
from langgraph.graph import MessagesState, StateGraph
Messages State#
The langgraph.graph.MessagesState is a modified python dictionary with a built in messages key and an add_messages reducer applied to it. This means that messages from different branches of the graph are reduced to a single list.
The following cell shows the mro of the langgraph.graph.MessagesState.
MessagesState.__mro__
(langgraph.graph.message.MessagesState, dict, object)
Consider the following example: here is a graph containing a sigle node that returns dict with a defined message under the “messages” key.
def put_message(state: MessagesState) -> dict:
return {"messages": [HumanMessage("New message")]}
graph = (
StateGraph(MessagesState)
.add_node("put_message", put_message)
.add_edge("__start__", "put_message")
.add_edge("put_message", "__end__")
.compile()
)
The following cell invokes the graph, and passes the “user” question to it.
state = MessagesState(messages=[
HumanMessage("What is the capital of France?")
])
for m in graph.invoke(state)["messages"]:
m.pretty_print()
================================ Human Message =================================
What is the capital of France?
================================ Human Message =================================
New message
The graph’s output shows the “user’s” original message of the user and message added to it by the put_message node.