LangGraph Foundations: Building AI That Thinks in Steps
The Train Station Analogy
Imagine you’re running a magical train station. Trains (your data) arrive, visit different platforms (nodes), and the station master (your graph) decides which track to take next. Sometimes trains loop back, sometimes they split into different directions. That’s LangGraph!
What is LangGraph?
LangGraph helps you build AI systems that think step-by-step. Instead of your AI doing everything at once, it moves through stages—like a train visiting stations on its journey.
Why does this matter?
- You can see exactly what your AI is thinking
- You can fix problems at specific steps
- Your AI can make decisions and change direction
graph TD A["Start"] --> B["Think"] B --> C["Decide"] C --> D["Act"] D --> E["Done!"]
StateGraph Basics
Your Train Schedule Book
A StateGraph is like your train schedule book. It knows:
- Where trains can go (nodes)
- How trains get there (edges)
- What cargo each train carries (state)
Creating Your First StateGraph:
from langgraph.graph import StateGraph
# Create your train station
graph = StateGraph(MyState)
# Add platforms (nodes)
graph.add_node("think", think_fn)
graph.add_node("act", act_fn)
# Connect platforms (edges)
graph.add_edge("think", "act")
Think of StateGraph as the blueprint for your AI’s journey!
Defining Graph State
The Cargo Manifest
Your train carries cargo—that’s your state. It’s all the information your AI needs to remember as it travels.
Simple Example:
from typing import TypedDict
class MyState(TypedDict):
messages: list # Conversation history
current_step: str # Where are we?
result: str # Final answer
Real Life Comparison:
messages= Notes from each station visitedcurrent_step= Current platform numberresult= The package being delivered
Every node can read and update this cargo!
State Reducers and Annotations
The Cargo Handlers
When multiple trains bring cargo to the same spot, how do you combine it? That’s what reducers do!
The Problem:
Train 1 brings: ["apple"]
Train 2 brings: ["banana"]
Without reducer: Only ["banana"] survives!
With reducer: ["apple", "banana"] - Both kept!
Using Annotations:
from typing import Annotated
from operator import add
class MyState(TypedDict):
# This list grows! Old + New
messages: Annotated[list, add]
# This just replaces
current_step: str
| Reducer | What It Does | Example |
|---|---|---|
add |
Combines lists | [1] + [2] = [1,2] |
lambda a,b: b |
Keeps newest | Old → New |
| Custom | Your rules! | Whatever you need |
Graph Nodes
The Station Platforms
Nodes are where the magic happens! Each node is a function that:
- Receives the current state (cargo)
- Does something useful
- Returns updated state
Creating a Node:
def greet_user(state: MyState):
name = state.get("user_name", "Friend")
return {
"messages": [f"Hello, {name}!"]
}
# Add it to your graph
graph.add_node("greet", greet_user)
graph TD A["Input State"] --> B["Node: greet_user"] B --> C["Updated State"] style B fill:#90EE90
Node Rules:
- Takes state as input
- Returns a dictionary with updates
- Only updates what it returns (rest stays same)
Graph Edges and Routing
The Train Tracks
Edges are the tracks connecting your platforms. They tell trains where to go next.
Simple Edge (Always go here):
# After "think", always go to "act"
graph.add_edge("think", "act")
The Journey:
graph LR START((START)) --> A["Think"] A --> B["Act"] B --> FINISH((END))
Setting Start and End:
from langgraph.graph import START, END
# Where does journey begin?
graph.add_edge(START, "think")
# Where does it end?
graph.add_edge("act", END)
Conditional Edges
The Smart Switch Operator
Sometimes trains need to choose their path. Conditional edges let your AI make decisions!
The Decision Maker:
def decide_next(state: MyState):
if state["needs_help"]:
return "ask_human"
else:
return "continue"
# Add the smart switch
graph.add_conditional_edges(
"check", # From this node
decide_next, # This decides
{
"ask_human": "human_node",
"continue": "finish_node"
}
)
graph TD A["Check"] --> B{Needs Help?} B -->|Yes| C["Ask Human"] B -->|No| D["Finish"] style B fill:#FFD700
Real Example - Customer Support Bot:
- Is question simple? → Answer directly
- Is question complex? → Ask supervisor
- Is customer angry? → Transfer to human
Cycles and Branching
The Loop-de-Loop Track
Sometimes your train needs to go around again! Cycles let your AI retry or iterate.
Why Cycles?
Think of editing a document:
- Write draft
- Check for errors
- Found errors? Go back to step 1!
- No errors? Done!
Creating a Cycle:
def check_quality(state):
if state["quality"] < 0.8:
return "revise" # Go back!
return "publish" # Move forward!
graph.add_conditional_edges(
"review",
check_quality,
{
"revise": "write", # Cycle back
"publish": "done" # Exit loop
}
)
graph TD A["Write"] --> B["Review"] B -->|Not Good| A B -->|Good!| C["Done"] style A fill:#87CEEB style B fill:#FFD700 style C fill:#90EE90
Branching - Multiple Paths:
Your AI can also split into different branches based on the situation:
def route_request(state):
req_type = state["request_type"]
if req_type == "billing":
return "billing_team"
elif req_type == "technical":
return "tech_team"
else:
return "general_support"
Putting It All Together
Here’s a complete mini-graph:
from langgraph.graph import StateGraph, START, END
from typing import TypedDict, Annotated
from operator import add
# 1. Define State
class ChatState(TypedDict):
messages: Annotated[list, add]
mood: str
# 2. Create Graph
graph = StateGraph(ChatState)
# 3. Define Nodes
def analyze(state):
return {"mood": "happy"}
def respond(state):
return {"messages": ["Great to hear!"]}
# 4. Add Nodes
graph.add_node("analyze", analyze)
graph.add_node("respond", respond)
# 5. Connect Everything
graph.add_edge(START, "analyze")
graph.add_edge("analyze", "respond")
graph.add_edge("respond", END)
# 6. Compile and Run!
app = graph.compile()
Quick Reference
| Concept | What It Does | Think Of It As |
|---|---|---|
| StateGraph | Holds your workflow | Train station |
| State | Data being processed | Train cargo |
| Reducer | Combines state updates | Cargo handler |
| Node | Processing step | Platform |
| Edge | Connection between nodes | Train track |
| Conditional Edge | Smart routing | Switch operator |
| Cycle | Repeating loop | Round track |
You Did It!
You now understand LangGraph foundations! You can:
- Create a StateGraph (build a train station)
- Define State (plan your cargo)
- Use Reducers (handle cargo smartly)
- Add Nodes (build platforms)
- Connect with Edges (lay tracks)
- Make Smart Decisions (conditional edges)
- Create Loops (cycles for iteration)
Next Step: Build your first AI agent that thinks step-by-step!
graph TD A["You Started Here"] --> B["Learned Basics"] B --> C["Understood State"] C --> D["Mastered Nodes"] D --> E["Connected Edges"] E --> F["🎉 LangGraph Pro!"] style F fill:#FFD700
