Tutorial Image: LangGraph Tutorial: Building Your First Graph - Unit 1.1 Exercise 3

LangGraph Tutorial: Building Your First Graph - Unit 1.1 Exercise 3

Learn how to build your first graph in LangGraph! Discover the basics of StateGraph, node creation, edge configuration, and graph execution to kickstart your journey into graph-based conversation flows.

๐ŸŽฏ 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

  1. StateGraph Initialization
  2. Node Definition and Function
  3. Edge Configuration
  4. Graph Compilation and Execution
  5. 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:

  1. Initializing the graph
  2. Adding nodes
  3. Configuring edges
  4. 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:

  1. Validates the graph structure
  2. Ensures all nodes are properly connected
  3. 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

  1. Graph Structure: StateGraph provides the framework for conversation flow
  2. Node Functions: Nodes process and transform state as it flows through the graph
  3. Edge Configuration: Edges define the execution path through nodes
  4. Special Nodes: START and END nodes control graph entry and exit points
  5. Compilation: Graphs must be compiled before execution

Common Pitfalls to Avoid

  1. Forgetting to compile the graph before use
  2. Not connecting all nodes to both START and END
  3. Returning incorrect state structure from nodes
  4. 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)

Rod Rivera

๐Ÿ‡ฌ๐Ÿ‡ง Chapter