LangGraph Detailed interpretation of Simple Graph
📚 Overview
This document explains LangGraph’s Simple Graph tutorial in detail. This is your first introduction to LangGraph, helping you master the core concepts and infrastructure of LangGraph by building a simple graph with 3 nodes and 1 conditional edge.
Learning Objectives:
- Understand the core components of LangGraph (State, Node, Edge)
- Master the graph construction and execution process
- Learn how to use conditional edges
- Familiar with Python type hints and TypedDict
🎯 Core Concept
What is LangGraph?
LangGraph is a framework for building stateful multi-step applications. It models the application as a Graph where:
- Node: function that performs specific operations
- Edge: Define the path of the execution process
- State: Data passed between nodes
Basic structure of the graph
START → Node 1 → [条件判断] → Node 2 或 Node 3 → ENDFeatures:
- Process Control: Control the execution order of nodes through edges
- State Management: Each node can read and update status
- Dynamic Routing: Conditional edges dynamically select the next node based on status
🎭 Practical case: Emotion generator
We will build a simple sentiment generator that demonstrates the complete workflow of LangGraph:
Requirements:
- Receive user input (such as "Hi, this is Lance.")
- Add "I am" to the text
- Randomly choose to add "happy!" or "sad!"
System architecture diagram
用户输入: "Hi, this is Lance."
↓
[START]
↓
[Node 1] 添加 "I am"
↓
[条件边: decide_mood]
↓
┌────────────┐
↓ ↓
[Node 2] [Node 3]
添加 "happy!" 添加 "sad!"
↓ ↓
└─────┬──────┘
↓
[END]
↓
输出: "Hi, this is Lance. I am happy!"
或 "Hi, this is Lance. I am sad!"🔧 Detailed explanation of code implementation
1. Environment preparation
%%capture --no-stderr
%pip install --quiet -U langgraphDescription:
%%capture --no-stderr: Jupyter magic command, hide installation output--quiet: silent installation mode-U: upgrade to the latest version
2. Define state (State)
State is the core data structure of LangGraph and runs throughout the entire graph execution process.
from typing_extensions import TypedDict
class State(TypedDict):
graph_state: strPython knowledge points: TypedDict
TypedDict is a type hint tool introduced in Python 3.8+, which is used to define the structure of the dictionary:
# 传统字典 - 无类型提示
state = {"graph_state": "Hello"}
# TypedDict - 有类型提示
class State(TypedDict):
graph_state: str # 明确指定字段类型
state: State = {"graph_state": "Hello"}Advantages:
- IDE support: auto-completion and type checking
- Document Function: Clearly display the data structure
- Error Prevention: Static type checking finds potential errors
Role in LangGraph:
Statedefines the data structure shared by all nodes in the graph- Each node can access and modify fields in
State - Provides type-safe state management
3. Define nodes (Nodes)
Nodes are Python functions that perform specific operations.
def node_1(state):
print("---Node 1---")
return {"graph_state": state['graph_state'] + " I am"}
def node_2(state):
print("---Node 2---")
return {"graph_state": state['graph_state'] + " happy!"}
def node_3(state):
print("---Node 3---")
return {"graph_state": state['graph_state'] + " sad!"}Core features of node
1. Input parameters
def node_1(state):
# ^^^^^
# 必须接收 state 参数- The first parameter is the current state (
Statetype) - The status field can be accessed via
state['graph_state']
2. Return value
return {"graph_state": state['graph_state'] + " I am"}
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# 返回一个字典,更新状态中的字段- The returned dictionary will have updated status
- Default behavior: overwrite the original value (not merge)
3. Status update mechanism
# 执行前:state = {"graph_state": "Hi, this is Lance."}
node_1(state)
# 执行后:state = {"graph_state": "Hi, this is Lance. I am"}Important: The returned value will completely replace the original value of the corresponding field, unless a Reducer is used (explained in subsequent courses).
4. Define edges (Edges)
Edges define the connection relationships between nodes and are divided into two types:
Normal Edge
builder.add_edge(START, "node_1")- Fixed routing: always flows from the starting point to the ending point
- Unconditional Execution: This path will be taken every time
Conditional Edge
import random
from typing import Literal
def decide_mood(state) -> Literal["node_2", "node_3"]:
# 从状态中获取数据(这里未使用,仅作示例)
user_input = state['graph_state']
# 50/50 随机选择
if random.random() < 0.5:
return "node_2" # 50% 概率返回 Node 2
return "node_3" # 50% 概率返回 Node 3Python knowledge points: Literal type
Literal is an advanced type hint for Python 3.8+, used to limit the possible values of the return value:
from typing import Literal
def decide_mood(state) -> Literal["node_2", "node_3"]:
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^
# 返回值只能是 "node_2" 或 "node_3"
return "node_2" # ✅ 合法
# return "node_4" # ❌ 类型检查会报错Advantages:
- Type safety: IDE will check whether the return value is legal
- Autocomplete: The editor will prompt available options
- Document Function: Clearly display all possible paths
How conditional edges work
# 条件函数的职责
def decide_mood(state) -> Literal["node_2", "node_3"]:
# 1. 读取状态
user_input = state['graph_state']
# 2. 执行逻辑判断
if some_condition:
return "node_2" # 路由到节点 2
else:
return "node_3" # 路由到节点 3Execution process:
- Node 1 is executed
- LangGraph calls
decide_mood(state) - Select the next node based on the return value ("node_2" or "node_3")
- Execute the selected node
5. Graph Construction
Now assemble all the components into the complete diagram.
from IPython.display import Image, display
from langgraph.graph import StateGraph, START, END
# 1. 初始化图构建器
builder = StateGraph(State)
# 2. 添加节点
builder.add_node("node_1", node_1)
builder.add_node("node_2", node_2)
builder.add_node("node_3", node_3)
# 3. 添加边
builder.add_edge(START, "node_1") # 开始 → 节点1
builder.add_conditional_edges("node_1", decide_mood) # 节点1 → 条件判断
builder.add_edge("node_2", END) # 节点2 → 结束
builder.add_edge("node_3", END) # 节点3 → 结束
# 4. 编译图
graph = builder.compile()
# 5. 可视化
display(Image(graph.get_graph().draw_mermaid_png()))Detailed explanation of LangGraph core API
1.StateGraph
builder = StateGraph(State)
# ^^^^^
# 传入状态类型- Graph builder for adding nodes and edges
- Generic class, accepting
Statetype parameters - Ensure all nodes use the same state structure
2. add_node
builder.add_node("node_1", node_1)
# ^^^^^^^^ ^^^^^^
# 节点名称 节点函数- Register nodes into the graph
- Node name used for edge connection (string form)
- Node functions are the actual executed logic
3. add_edge
builder.add_edge(START, "node_1")
# ^^^^^ ^^^^^^^^
# 起点 终点- Add fixed routing edges
STARTandENDare special nodes (explained later)
4. add_conditional_edges
builder.add_conditional_edges("node_1", decide_mood)
# ^^^^^^^^ ^^^^^^^^^^^
# 起点节点 条件函数- Add edges for conditional routing
- The conditional function returns the name of the next node
- Automatically route to the corresponding node based on the return value
5. compile
graph = builder.compile()- Convert builders into executable graphs
- Perform basic validation (e.g. check if edge connections are valid)
- Return
CompiledGraphobject, you can callinvokeand other methods
Special nodes: START and END
START node
- Entry point of graph
- Receive user input
- Pass the input to the first node
builder.add_edge(START, "node_1")
# 用户输入 → node_1END node
- the exit point of the graph
- mark the end of execution
- Return to final state
builder.add_edge("node_2", END)
# node_2 → 结束并返回结果Visual graph structure
display(Image(graph.get_graph().draw_mermaid_png()))Generate a Mermaid diagram showing the structure of the diagram:
- Node: rectangular box
- Edge: Arrow connection
- Conditional edge: diamond judgment box
6. Graph Invocation
The graph implements LangChain's Runnable protocol and provides a unified execution interface.
graph.invoke({"graph_state": "Hi, this is Lance."})Example output:
---Node 1---
---Node 3---
{'graph_state': 'Hi, this is Lance. I am sad!'}Detailed explanation of invoke method
1. Input parameters
graph.invoke({"graph_state": "Hi, this is Lance."})
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# 初始状态(字典形式)- Input must be a dictionary
- Field must match
Statedefinition - Set the initial state of the graph
2. Execution process
# 1. 初始状态
state = {"graph_state": "Hi, this is Lance."}
# 2. START → node_1
state = node_1(state)
# {"graph_state": "Hi, this is Lance. I am"}
# 3. 条件边判断
next_node = decide_mood(state) # 返回 "node_3"
# 4. node_3 执行
state = node_3(state)
# {"graph_state": "Hi, this is Lance. I am sad!"}
# 5. END 节点
return state3. Return value
result = graph.invoke({"graph_state": "Hi, this is Lance."})
print(result)
# {'graph_state': 'Hi, this is Lance. I am sad!'}- Returns the final state (dictionary form)
- Contains the latest values for all status fields
Synchronous execution features
invoke() # 同步方法- Blocking Execution: Wait for each node to complete before continuing
- Sequential execution: Execute in sequence according to the definition of edges
- Final Return: Return to the final state after all nodes are executed
Comparing asynchronous methods (subsequent course):
invoke(): Sync, waiting for completionainvoke(): asynchronous, non-blockingstream(): streaming, stepwise return
🎓 Summary of core knowledge points
LangGraph-specific concepts
1. State
Definition:
from typing_extensions import TypedDict
class State(TypedDict):
graph_state: strFunction:
- Define data structures shared by all nodes in the graph
- Provide type-safe state management -Support status reading and updating
Key Points:
- Must use
TypedDictor similar type - All nodes use the same state structure
- Status field can be of any type (str, list, dict, custom class, etc.)
2. Node
Definition:
def node_name(state):
# 读取状态
value = state['field_name']
# 执行逻辑
new_value = process(value)
# 更新状态
return {"field_name": new_value}Features:
- Must receive
stateparameter - Return dictionary update status
- Can read and modify any status field
3. Edge
Normal side:
builder.add_edge("node_a", "node_b")
# node_a 总是流向 node_bConditional edge:
def condition(state) -> Literal["node_b", "node_c"]:
if some_logic:
return "node_b"
return "node_c"
builder.add_conditional_edges("node_a", condition)
# node_a 根据 condition 返回值选择下一个节点4. Special nodes
| Node | Function | Usage |
|---|---|---|
| START | Image entrance | builder.add_edge(START, "first_node") |
| END | Picture export | builder.add_edge("last_node", END) |
5. Diagram construction process
# 1. 创建构建器
builder = StateGraph(State)
# 2. 添加节点
builder.add_node("name", function)
# 3. 添加边
builder.add_edge(source, target)
builder.add_conditional_edges(source, condition_function)
# 4. 编译
graph = builder.compile()
# 5. 执行
result = graph.invoke(initial_state)Python-specific knowledge points
1. TypedDict
from typing_extensions import TypedDict
class State(TypedDict):
field1: str
field2: int
field3: list[str]Features:
- Define the key and value types of the dictionary
- Static type checking (IDE support)
- No validation forced at runtime (unlike Pydantic)
2. Literal type
from typing import Literal
def function() -> Literal["option1", "option2"]:
return "option1" # 只能返回这两个值之一Function:
- Limit the possible values of the return value
- Provide more precise type hints
- Return type used for conditional edges
3. Type Hints
# 函数参数和返回值类型
def node_1(state: State) -> dict[str, str]:
return {"graph_state": "..."}
# 变量类型
graph_state: str = "Hello"Advantages:
- Code readability is better
- IDE auto-completion and error checking
- Document function
💡 Best Practices
1. When to use simple diagrams?
✅ Applicable scenarios:
- Learn the basic concepts of LangGraph
- Simple process control (3-5 nodes)
- Simple tasks requiring conditional routing
- Prototype development and proof of concept
❌ Not applicable scenarios:
- Complex multi-step processes (consider subgraphs)
- Requires parallel execution (consider Map-Reduce)
- Requires looping and retrying (think loop graph)
- Complex state management (consider multi-state design)
2. State design principles
Principle 1: Keep state simple
# ✅ 好的设计 - 只包含必需字段
class State(TypedDict):
user_input: str
result: str
# ❌ 不好的设计 - 过多字段
class State(TypedDict):
user_input: str
intermediate_1: str
intermediate_2: str
intermediate_3: str
temp_value: str
result: strPrinciple 2: Use meaningful field names
# ✅ 清晰的命名
class State(TypedDict):
user_query: str
search_results: list[str]
final_answer: str
# ❌ 模糊的命名
class State(TypedDict):
data: str
result: list
output: strPrinciple 3: Appropriate field types
class State(TypedDict):
# 简单类型
message: str
count: int
is_done: bool
# 复杂类型
items: list[str]
metadata: dict[str, Any]
# 自定义类型(后续课程)
# response: ChatMessage3. Node design skills
Tip 1: Single Responsibility
# ✅ 每个节点做一件事
def fetch_data(state):
data = api.fetch()
return {"data": data}
def process_data(state):
result = process(state["data"])
return {"result": result}
# ❌ 节点做太多事情
def do_everything(state):
data = api.fetch()
result = process(data)
final = format(result)
return {"final": final}Tip 2: Add a log
def node_1(state):
print(f"---Node 1 执行---")
print(f"输入状态: {state}")
result = process(state)
print(f"输出状态: {result}")
return resultTip 3: Error handling
def safe_node(state):
try:
result = risky_operation(state)
return {"result": result, "error": None}
except Exception as e:
return {"result": None, "error": str(e)}4. Design of conditional edges
Tip 1: Stateful Routing
def route_by_state(state) -> Literal["node_a", "node_b"]:
# 基于状态字段做决策
if state["score"] > 0.8:
return "node_a"
return "node_b"Tip 2: Multi-condition judgment
def complex_routing(state) -> Literal["node_a", "node_b", "node_c"]:
value = state["value"]
if value < 10:
return "node_a"
elif value < 50:
return "node_b"
else:
return "node_c"Tip 3: Add a default route
def safe_routing(state) -> Literal["node_a", "node_b", "error_node"]:
try:
if state["condition"]:
return "node_a"
return "node_b"
except:
return "error_node" # 异常情况的默认路由🚀 Advanced extensions
1. Multi-field status
class State(TypedDict):
user_input: str
processing_step: int
results: list[str]
metadata: dict
def node(state):
# 可以更新多个字段
return {
"processing_step": state["processing_step"] + 1,
"results": state["results"] + ["new_item"]
}2. Nested state structure
from typing import Any
class State(TypedDict):
config: dict[str, Any]
data: dict[str, list[str]]
def node(state):
# 访问嵌套结构
threshold = state["config"]["threshold"]
items = state["data"]["items"]
return {"data": {"items": processed_items}}3. Optional fields (Python 3.11+)
from typing import NotRequired
class State(TypedDict):
required_field: str
optional_field: NotRequired[str] # 可选字段🎯 Practical application cases
Case 1: Simple chatbot
class ChatState(TypedDict):
user_message: str
bot_response: str
sentiment: str
def analyze_sentiment(state):
# 分析用户消息的情感
sentiment = sentiment_analyzer(state["user_message"])
return {"sentiment": sentiment}
def generate_response(state):
# 根据情感生成回复
if state["sentiment"] == "positive":
response = "很高兴听到这个消息!"
else:
response = "我理解你的感受。"
return {"bot_response": response}
def route_by_sentiment(state) -> Literal["positive_response", "negative_response"]:
return "positive_response" if state["sentiment"] == "positive" else "negative_response"Case 2: Content review process
class ModerationState(TypedDict):
content: str
is_safe: bool
action: str
def check_content(state):
# 检查内容是否安全
is_safe = content_filter(state["content"])
return {"is_safe": is_safe}
def approve_content(state):
return {"action": "approved"}
def reject_content(state):
return {"action": "rejected"}
def route_content(state) -> Literal["approve", "reject"]:
return "approve" if state["is_safe"] else "reject"Case 3: Data processing pipeline
class DataState(TypedDict):
raw_data: str
cleaned_data: str
processed_data: dict
quality_score: float
def clean_data(state):
cleaned = remove_noise(state["raw_data"])
return {"cleaned_data": cleaned}
def process_data(state):
processed = transform(state["cleaned_data"])
return {"processed_data": processed}
def check_quality(state):
score = calculate_quality(state["processed_data"])
return {"quality_score": score}
def route_quality(state) -> Literal["save_result", "retry_processing"]:
return "save_result" if state["quality_score"] > 0.7 else "retry_processing"🔍 Frequently Asked Questions
Q1: Why does the node return a dictionary instead of returning a value directly?
Because LangGraph needs to know which state field to update:
# ✅ 正确 - 明确指定更新的字段
def node(state):
return {"graph_state": "new_value"}
# ❌ 错误 - LangGraph 不知道如何更新状态
def node(state):
return "new_value"Q2: Can a node not return any value?
Yes, but the status will not be updated:
def node(state):
print("This node only prints")
# 不返回任何值,状态保持不变Suitable for nodes that only perform side effects (such as logging, notifications).
Q3: Does the return value of a conditional edge have to be of Literal type?
Not required, but highly recommended:
# 推荐 ✅ - 类型安全
def decide(state) -> Literal["node_a", "node_b"]:
return "node_a"
# 可行但不推荐 - 无类型检查
def decide(state):
return "node_a" # 可能拼写错误导致运行时错误Q4: Can variables be shared between nodes?
Not recommended. Data should be passed via state:
# ❌ 不好的做法 - 全局变量
shared_data = []
def node_1(state):
shared_data.append("data")
return {}
# ✅ 好的做法 - 通过状态
class State(TypedDict):
shared_data: list[str]
def node_1(state):
return {"shared_data": state["shared_data"] + ["data"]}Q5: Can the START and END nodes be omitted?
Can't. They are required special nodes:
# ❌ 错误 - 缺少 START
builder.add_edge("node_1", "node_2")
# ✅ 正确
builder.add_edge(START, "node_1")
builder.add_edge("node_2", END)📊 Execution mode of graph
invoke - synchronous execution
result = graph.invoke({"graph_state": "input"})
# 阻塞直到图执行完成
print(result)Features:
- Synchronous blocking
- Return to final state
- Suitable for simple scenes
stream - Streaming execution (preview)
for step in graph.stream({"graph_state": "input"}):
print(step) # 逐步返回每个节点的输出Features:
- Return results step by step
- Can observe the execution process
- Suitable for long-running graphs
📖 Further reading
- LangGraph official documentation - core concepts
- LangGraph official document - State
- LangGraph official documentation - Nodes
- LangGraph official documentation - Edges
- Python TypedDict Documentation
- Python Literal Documentation
🎉 Summary
Through this simple diagram tutorial, we learned:
LangGraph Core Concepts
- State: Define the data structure of the graph
- Node: Function that performs specific operations
- Edge: Controls the connection of the execution process
- START/END: The entrance and exit of the graph
Python technical points
- TypedDict: type-safe dictionary definition
- Literal: Limit the possible values of the return value
- Type Tips: Improve code quality and maintainability
Key Skills
- Build a simple state machine
- Use conditional edges to implement dynamic routing
- Understand the execution process of the graph
Next step: Learn more complex graph structures, such as chain graphs, parallel graphs, loop graphs, etc., to build more powerful AI applications!