๐ฏ What You'll Learn Today
LangGraph Tutorial: Building Your First Graph - Unit 1.1 Exercise 3
This tutorial is also available in Google Colab here or for download here
Joint Initiative: This tutorial is part of a collaboration between AI Product Engineer and the Nebius Academy.
This tutorial introduces the core components of LangGraph: StateGraph, nodes, and edges. We'll build a simple graph that demonstrates the fundamental concepts of graph-based conversation flow.
Key Concepts Covered
- StateGraph Initialization
- Node Definition and Function
- Edge Configuration
- Graph Compilation and Execution
- Special Nodes (START and END)
Let's break it down step by step:
from typing import TypedDict
#!pip install langchain-core
from langchain_core.messages import BaseMessage, HumanMessage
#!pip install langgraph
from langgraph.graph import END, START, StateGraph
Step 1: State Definition
First, we define our state structure to hold conversation messages. This provides the foundation for data flow through our graph.
class State(TypedDict):
"""State container for graph-based conversation flow.
In LangGraph, state flows through the graph, being transformed
by each node it encounters. This simple state tracks just messages,
but can be extended for more complex applications.
Attributes:
messages: List of conversation messages that will flow through the graph
"""
messages: list[BaseMessage]
Step 2: Node Definition
Nodes are where the actual work happens in LangGraph. Each node is a function that takes the current state and returns an updated state.
def simple_node(state: State) -> State:
"""A basic node that adds a greeting message to the state.
This demonstrates the fundamental pattern of node functions in LangGraph:
1. Receive current state
2. Process the state
3. Return modified state
Args:
state: Current conversation state
Returns:
dict: Updated state with new message added
Note:
In real applications, nodes typically perform more complex operations:
- Making LLM calls
- Processing user input
- Updating conversation context
- Making decisions about conversation flow
"""
return {"messages": [HumanMessage(content="Hello!")]}
Step 3: Graph Construction
Now we create and configure our StateGraph, which involves:
- Initializing the graph
- Adding nodes
- Configuring edges
- Compiling for execution
Initialize the graph with our State type
graph = StateGraph(State)
Add our node to the graph
The string "greeter" becomes the node's identifier in the graph
graph.add_node("greeter", simple_node)
Step 4: Edge Configuration
Edges define the flow of execution in LangGraph. There are two special nodes in every graph
- START: Entry point of the graph
- END: Exit point of the graph
Configure the entry point
graph.add_edge(START, "greeter") # First node to execute
Configure the exit point
graph.add_edge("greeter", END) # Last node to execute
Step 5: Compilation and Execution
The graph must be compiled before use. Compilation:
- Validates the graph structure
- Ensures all nodes are properly connected
- Creates an executable chain
Compile the graph into an executable chain
chain = graph.compile()
Step 6: Running the Graph
Execute the graph by invoking it with an initial state
Initialize state and run the graph
result = chain.invoke({"messages": []})
Access the result
print(result["messages"][0].content) # Output: "Hello!"
Key Takeaways
- Graph Structure: StateGraph provides the framework for conversation flow
- Node Functions: Nodes process and transform state as it flows through the graph
- Edge Configuration: Edges define the execution path through nodes
- Special Nodes: START and END nodes control graph entry and exit points
- Compilation: Graphs must be compiled before execution
Common Pitfalls to Avoid
- Forgetting to compile the graph before use
- Not connecting all nodes to both START and END
- Returning incorrect state structure from nodes
- Missing edge definitions
Next Steps
- Add multiple nodes with different functions
- Implement conditional routing between nodes
- Add error handling to nodes
- Explore more complex state transformations
Advanced Example:
Multi-node graph example:
graph = StateGraph(State)
graph.add_node("greeting", greeting_node)
graph.add_node("processor", process_node)
graph.add_node("farewell", farewell_node)
graph.add_edge(START, "greeting")
graph.add_edge("greeting", "processor")
graph.add_edge("processor", "farewell")
graph.add_edge("farewell", END)
๐ฌ๐ง Chapter