StateGraph
StateGraph
. A StateGraph
object defines the structure of our chatbot as a “state machine”. We’ll add nodes
to represent the llm and functions our chatbot can call and edges
to specify how the bot should transition between these functions.
node
can receive the current State
as input and output an update to the state.messages
will be appended to the existing list rather than overwriting it, thanks to the prebuilt add_messages
function used with the Annotated
syntax.State
. The State
includes the graph’s schema and reducer functions that handle state updates. In our example, State
is a TypedDict
with one key: messages
. The add_messages
reducer function is used to append new messages to the list instead of overwriting it. Keys without a reducer annotation will overwrite previous values. To learn more about state, reducers, and related concepts, see LangGraph reference docs.chatbot
” node. Nodes represent units of work and are typically regular Python functions.
Let’s first select a chat model:
chatbot
node function takes the current State
as input and returns a dictionary containing an updated messages
list under the key “messages”. This is the basic pattern for all LangGraph node functions.
The add_messages
function in our State
will append the LLM’s response messages to whatever messages are already in the state.
entry
pointentry
point to tell the graph where to start its work each time it is run:
exit
pointexit
point to indicate where the graph should finish execution. This is helpful for more complex flows, but even in a simple graph like this, adding an end node improves clarity.
compile()
on the graph builder. This creates a CompiledStateGraph
we can invoke on our state.
get_graph
method and one of the “draw” methods, like draw_ascii
or draw_png
. The draw
methods each require additional dependencies.
quit
, exit
, or q
.