LangGraph Tutorial
our main focus is on code in sections: Imports → State → Nodes → Routing Function → Graph Creation → Execution Flow.
LangGraph Conditional Routing Example
Purpose of the Code
This LangGraph workflow demonstrates:
- Creating a graph using
StateGraph. - Defining a shared state.
- Creating multiple nodes.
- Using a conditional edge to dynamically choose the next node.
- Executing the graph and returning the final state.
from langgraph.graph import START, END, StateGraph
from typing_extensions import TypedDict
from typing import Literal
import random
from IPython.display import display,Image
class State(TypedDict):
game: str
def play_game(state: State):
print("I am inside play_game node")
return {"game": state["game"] + "I am playing "}
def badminton(state: State):
print("I am inside badminton node")
return {"game": state["game"] + "badminton"}
def cricket(state: State):
print("I am inside cricket node")
return {"game": state["game"] + "cricket"}
def random_game(state: State) -> Literal["cricket", "badminton"]:
print("I am inside random_game node")
if random.random() < 0.5:
return "cricket"
else:
return "badminton"
graph = StateGraph(State)
graph.add_node("play_game", play_game)
graph.add_node("badminton", badminton)
graph.add_node("cricket", cricket)
graph.add_edge(START, "play_game")
graph.add_conditional_edges("play_game", random_game)
graph.add_edge("badminton", END)
graph.add_edge("cricket", END)
app = graph.compile()
display(Image(graph_builder.get_graph().draw_mermaid_png()))
result = app.invoke({"game": ""})
print(result)For your documentation, the best approach is to explain the code in sections: Imports → State → Nodes → Routing Function → Graph Creation → Execution Flow.
LangGraph Conditional Routing Example
Purpose of the Code
This LangGraph workflow demonstrates:
- Creating a graph using
StateGraph. - Defining a shared state.
- Creating multiple nodes.
- Using a conditional edge to dynamically choose the next node.
- Executing the graph and returning the final state.
The workflow randomly chooses between Cricket and Badminton.
1. Import Statements
from langgraph.graph import START, END, StateGraph
from typing_extensions import TypedDict
from typing import Literal
import random
from IPython.display import display, Image
Explanation
StateGraph
from langgraph.graph import StateGraph
Used to create a LangGraph workflow.
Think of it as the container that holds:
- Nodes
- Edges
- State
START
from langgraph.graph import START
Represents the entry point of the graph.
Every graph execution begins from the START node.
END
from langgraph.graph import END
Represents the termination point of the graph.
When execution reaches END, the graph stops.
TypedDict
from typing_extensions import TypedDict
Defines the structure of the graph state.
It tells LangGraph:
What data can flow between nodes?
Literal
from typing import Literal
Used for type safety.
It specifies that a function can only return particular values.
Example:
Literal[“cricket”, “badminton”]
means only these two strings are allowed.
random
import random
Used to generate a random number.
This helps in choosing either Cricket or Badminton.
display and Image
from IPython.display import display, Image
Used to display the graph diagram inside Jupyter Notebook.
2. Defining State
class State(TypedDict):
game: str
Explanation
This defines the information that flows through the graph.
Current state contains:
{
“game”: “”
}
Example
Initial State:
{
“game”: “”
}
After first node:
{
“game”:”I am playing “
}
After cricket node:
{
“game”:”I am playing cricket”
}
3. Node: play_game
def play_game(state: State):
print(“I am inside play_game node”)
return {“game”: state[“game”] + “I am playing “}
Purpose
This node initializes the game message.
Input State
{
“game”:””
}
Output State
{
“game”:”I am playing “
}
``
Console Output
I am inside play_game node
4. Node: badminton
def badminton(state: State):
print(“I am inside badminton node”)
return {“game”: state[“game”] + “badminton”}
Purpose
Adds “badminton” to the game message.
Input
{
“game”:”I am playing “
}
Output
{
“game”:”I am playing badminton”
}
5. Node: cricket
def cricket(state: State):
print(“I am inside cricket node”)
return {“game”: state[“game”] + “cricket”}
Purpose
Adds “cricket” to the state.
Input
{
“game”:”I am playing “
}
``
Output
{
“game”:”I am playing cricket”
}
6. Conditional Routing Function
def random_game(state: State) -> Literal[“cricket”, “badminton”]:
`
Purpose
Determines which node should execute next.
Logic
if random.random() < 0.5:
return “cricket”
else:
return “badminton”
Example
Suppose:
random.random()
returns
0.25
Then:
return “cricket”
Suppose:
random.random()
returns
0.75
Then:
return “badminton”
Why Literal is Used?
-> Literal[“cricket”, “badminton”]
This tells LangGraph:
The function can only route to:
“cricket”
or
“badminton”
Get Reema Kumaritech’s stories in your inbox
Join Medium for free to get updates from this writer.
No other node names are allowed.
7. Creating the Graph
graph = StateGraph(State)
Purpose
Creates a graph that uses the State schema.
Visually:
Graph
├── Nodes
├── Edges
└── State
8. Adding Nodes
graph.add_node(“play_game”, play_game)
graph.add_node(“badminton”, badminton)
graph.add_node(“cricket”, cricket)
Syntax
add_node(“node_name”, function)
Mapping
Node NameFunctionplay_gameplay_game()badmintonbadminton()cricketcricket()
9. Adding Edges
START → play_game
graph.add_edge(START, “play_game”)
Execution starts here:
START
|
v
play_game
Conditional Edge
graph.add_conditional_edges(
“play_game”,
random_game
)
After play_game executes:
play_game
|
v
random_game()
random_game() decides:
play_game
|
+ — — -> cricket
|
+ — — -> badminton
Connecting to END
graph.add_edge(“badminton”, END)
graph.add_edge(“cricket”, END)
``
Visually:
badminton — → END
cricket — — → END
10. Compile Graph
app = graph.compile()
Purpose
Converts the graph definition into an executable application.
Before:
Graph Definition
After:
Runnable LangGraph App
11. Display Graph
display(
Image(
graph_builder.get_graph().draw_mermaid_png()
)
)
Purpose
Generates and displays the workflow diagram.
Expected Diagram:
START
|
v
play_game
|
+ — — -> cricket
| |
| v
| END
|
+ — — -> badminton
|
v
END
Note
Your code contains a bug:
graph_builder
is not defined.
You compiled as:
app = graph.compile()
Therefore use:
display(
Image(
app.get_graph().draw_mermaid_png()
)
)
12. Execute Graph
result = app.invoke({“game”: “”})
Initial State
{
“game”:””
}
Execution Flow
Suppose random choice is Cricket.
Step 1:
START
↓
Step 2:
play_game
State becomes:
{
“game”:”I am playing “
}
↓
Step 3:
random_game
returns:
“cricket”
↓
Step 4:
cricket
State becomes:
{
“game”:”I am playing cricket”
}
``
↓
Step 5:
END
13. Final Output
print(result)
Possible output:
{‘game’: ‘I am playing cricket’}
or
{‘game’: ‘I am playing badminton’}
Complete Workflow Diagram
START
|
v
+ — — — — — — -+
| play_game |
+ — — — — — — -+
|
v
+ — — — — — — -+
| random_game |
+ — — — — — — -+
/ </span>
/ </span>
v v
+ — — — — — — + + — — — — — — +
| cricket | | badminton |
+ — — — — — — + + — — — — — — +
| |
v v
END
Key LangGraph Concepts Used
- State: Shared data passed between nodes.
- Node: A Python function that performs a task.
- Edge: Defines the next node to execute.
- Conditional Edge: Dynamically chooses the next node.
- START: Entry point of the graph.
- END: Exit point of the graph.
- compile(): Converts the graph into an executable app.
- invoke(): Runs the graph with input state.






