LangGraph State Schema Detailed interpretation
📚 Overview
This document explains in detail the State Schema in LangGraph. State is the core concept of LangGraph, which defines the structure and type of data in the graph. Understanding state patterns is a key step to mastering LangGraph.
In this tutorial, we'll dive into:
- What is State Schema
- Three ways to define state (TypedDict, Dataclass, Pydantic)
- Advantages, disadvantages and applicable scenarios of each method
- Detailed explanation of actual code
🎯 Core Concept
What is State Schema?
In LangGraph, State Schema defines:
- Data structure: What data is stored in the graph?
- Data type: What is the type of each field?
- Communication Protocol: How to transfer and update data between nodes
You can think of State as a shared data container that all nodes can read and update.
Core Features
1. Channel concept
Each key in State is a channel:
State = {
"name": "Alice", # name 通道
"mood": "happy" # mood 通道
}- Each node can read the value of any channel
- Each node can update one or more channels
- Channels are independent of each other
2. Node update mechanism
def node_1(state):
# 读取 name 通道
current_name = state["name"]
# 更新 name 通道(返回字典)
return {"name": current_name + " is happy"}Key points:
- Input: The node receives the complete State
- Output: The node returns the fields to be updated (partial update)
- Merge: LangGraph automatically merges the return value into State
🔧Three definition methods
LangGraph supports three ways of defining State Schema, each with unique advantages.
Method 1: TypedDict ⭐
This is the most common and simplest way.
Basic usage
from typing_extensions import TypedDict
class TypedDictState(TypedDict):
foo: str
bar: strFeatures:
- ✅ Simple syntax
- ✅ Good IDE support (auto-completion, type prompts)
- ✅ Optimal performance (no runtime verification)
- ❌ No runtime type checking
Advanced usage: Literal type
from typing import Literal
class TypedDictState(TypedDict):
name: str
mood: Literal["happy", "sad"] # 限定只能是这两个值之一Literal detailed explanation:
Literal is Python's type hint tool for limiting the range of values:
# ✅ 正确
state = {"name": "Alice", "mood": "happy"}
# ❌ IDE 会警告(但运行时不报错)
state = {"name": "Alice", "mood": "angry"} # angry 不在允许的值中Used in LangGraph
from langgraph.graph import StateGraph, START, END
# 1. 定义状态
class TypedDictState(TypedDict):
name: str
mood: Literal["happy", "sad"]
# 2. 定义节点
def node_1(state):
return {"name": state["name"] + " is ... "}
# 3. 创建图
builder = StateGraph(TypedDictState) # 传入状态类
builder.add_node("node_1", node_1)
builder.add_edge(START, "node_1")
builder.add_edge("node_1", END)
# 4. 编译和运行
graph = builder.compile()
result = graph.invoke({"name": "Lance"}) # 用字典初始化Key Points:
- Use
StateGraph(TypedDictState)to specify state mode - Call
graph.invoke({"name": "Lance"})with dictionary - Nodes access fields via
state["key"]
Method 2: Dataclass
Data class decorators provided by Python 3.7+.
Basic usage
from dataclasses import dataclass
@dataclass
class DataclassState:
name: str
mood: Literal["happy", "sad"]Differences from TypedDict
| Properties | TypedDict | Dataclass |
|---|---|---|
| Access method | state["name"] | state.name |
| initialization | dictionary | class instance |
| Performance | Faster | Slightly slower |
| Features | Basics | More (default values, methods, etc.) |
Used in LangGraph
# 定义节点 - 注意访问方式改变
def node_1(state):
# ✅ 使用点号访问(不是 state["name"])
return {"name": state.name + " is ... "}
# 创建图
builder = StateGraph(DataclassState)
builder.add_node("node_1", node_1)
builder.add_edge(START, "node_1")
builder.add_edge("node_1", END)
graph = builder.compile()
# 用 dataclass 实例初始化
result = graph.invoke(DataclassState(name="Lance", mood="sad"))IMPORTANT DETAILS:
Although state is a dataclass, the node still returns a dictionary:
def node_1(state):
# 输入:dataclass
name = state.name # 点号访问
# 输出:字典!
return {"name": name + " updated"} # ✅ 正确
# return DataclassState(...) # ❌ 不需要**Why is this possible? **
LangGraph internally stores each field of state as a separate channel. The dictionary returned by the node only needs to have matching keys to update the corresponding channel.
Method 3: Pydantic BaseModel ⭐⭐
The most powerful way to provide runtime verification.
What is Pydantic?
Pydantic is a data validation library for Python. The core class is BaseModel:
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
# ✅ 自动类型转换
user = User(name="Alice", age="25") # "25" 自动转为 25
print(user.age) # 25 (int)
# ❌ 验证失败会抛出异常
user = User(name="Alice", age="invalid") # ValidationErrorTypedDict vs Pydantic comparison
# TypedDict - 不做运行时检查
class DataclassState:
name: str
mood: Literal["happy", "sad"]
# ❌ 这段代码可以运行(虽然 IDE 会警告)
state = DataclassState(name="Lance", mood="angry") # 没有报错# Pydantic - 运行时验证
from pydantic import BaseModel, field_validator
class PydanticState(BaseModel):
name: str
mood: str
@field_validator('mood')
@classmethod
def validate_mood(cls, value):
if value not in ["happy", "sad"]:
raise ValueError("Mood must be 'happy' or 'sad'")
return value
# ✅ 正确的值
state = PydanticState(name="Lance", mood="happy") # OK
# ❌ 错误的值会抛出异常
state = PydanticState(name="Lance", mood="angry") # ValidationError!Detailed explanation of custom validator
from pydantic import BaseModel, field_validator, ValidationError
class PydanticState(BaseModel):
name: str
mood: str
@field_validator('mood') # 装饰器:指定要验证的字段
@classmethod # 必须是类方法
def validate_mood(cls, value):
# value 是传入的值
if value not in ["happy", "sad"]:
raise ValueError("Each mood must be either 'happy' or 'sad'")
return value # 返回验证后的值
# 测试验证
try:
state = PydanticState(name="John", mood="mad")
except ValidationError as e:
print("Validation Error:", e)
# 输出:Validation Error: 1 validation error for PydanticState
# mood
# Input should be 'happy' or 'sad'Validator workflow:
传入值 → field_validator → 检查逻辑 → 返回值或抛出异常
↓ ↓
"mad" ValueError
↓
ValidationErrorUsed in LangGraph
# 创建图(与之前完全相同)
builder = StateGraph(PydanticState)
builder.add_node("node_1", node_1)
builder.add_edge(START, "node_1")
builder.add_edge("node_1", END)
graph = builder.compile()
# 用 Pydantic 实例初始化
result = graph.invoke(PydanticState(name="Lance", mood="sad"))🎭 Practical case: Emotional decision-making system
Let's build a complete system to demonstrate the use of the three ways of defining states.
System architecture
用户输入姓名
↓
[node_1] 生成描述
↓
(随机决策)
↓
/ \
/ \
↓ ↓
[node_2] [node_3]
(happy) (sad)
↓ ↓
\ /
\ /
↓ ↓
返回结果Complete code implementation
import random
from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
# 1. 定义状态
class TypedDictState(TypedDict):
name: str
mood: Literal["happy", "sad"]
# 2. 定义节点
def node_1(state):
print("---Node 1---")
return {"name": state["name"] + " is ... "}
def node_2(state):
print("---Node 2---")
return {"mood": "happy"}
def node_3(state):
print("---Node 3---")
return {"mood": "sad"}
# 3. 条件函数
def decide_mood(state) -> Literal["node_2", "node_3"]:
"""50/50 随机选择"""
if random.random() < 0.5:
return "node_2" # 50% 概率选择 happy
return "node_3" # 50% 概率选择 sad
# 4. 构建图
builder = StateGraph(TypedDictState)
# 添加节点
builder.add_node("node_1", node_1)
builder.add_node("node_2", node_2)
builder.add_node("node_3", node_3)
# 添加边
builder.add_edge(START, "node_1")
builder.add_conditional_edges("node_1", decide_mood) # 条件边
builder.add_edge("node_2", END)
builder.add_edge("node_3", END)
# 5. 编译和运行
graph = builder.compile()
result = graph.invoke({"name": "Lance"})
print(result)
# 输出:
# ---Node 1---
# ---Node 2--- (或 ---Node 3---)
# {'name': 'Lance is ... ', 'mood': 'happy'} (或 'sad')Detailed code explanation
1. How conditional edges work
builder.add_conditional_edges("node_1", decide_mood)
# ^^^^^^^^^ ^^^^^^^^^^^
# 源节点 条件函数Execution process:
1. 执行 node_1
2. 调用 decide_mood(state)
3. decide_mood 返回 "node_2" 或 "node_3"
4. 路由到对应的节点
5. 执行 node_2 或 node_3
6. 到达 END2. The role of Literal in conditional functions
def decide_mood(state) -> Literal["node_2", "node_3"]:
# ^^^^^^^^^^^^^^^^^^^^^^^^^^
# 返回类型提示:只能是这两个字符串之一
return "node_2" # ✅ 正确
return "node_5" # ❌ IDE 会警告Not only is this a type hint, it also helps LangGraph understand possible routing targets.
3. Execution sequence of status update
初始状态: {"name": "Lance", "mood": None}
↓
node_1: 返回 {"name": "Lance is ... "}
合并后: {"name": "Lance is ... ", "mood": None}
↓
node_2: 返回 {"mood": "happy"}
合并后: {"name": "Lance is ... ", "mood": "happy"} ← 最终结果🎓 Summary of core knowledge points
LangGraph-specific concepts
1. The role of State Schema
| Function | Description | Example |
|---|---|---|
| Define data structure | Specify which fields | name: str, mood: str |
| Type prompt | IDE auto-completion | Enter state. auto-prompt field |
| Validation (optional) | Pydantic runtime checks | Prevent invalid data |
| Node Communication | Unified data interface | All nodes use the same structure |
2. Channel model
State = {
"name": ..., # name 通道
"mood": ... # mood 通道
}
# 节点可以更新部分通道
def node(state):
return {"name": "new_value"} # 只更新 name 通道Key Features:
- Each field is an independent channel
- Nodes can update only some channels
- Unreturned channels remain unchanged
3. Comparison of three status methods
| Features | TypedDict | Dataclass | Pydantic |
|---|---|---|---|
| Syntax Complexity | ⭐ Simple | ⭐⭐ Medium | ⭐⭐ Medium |
| Access Method | state["key"] | state.key | state.key |
| Runtime Verification | ❌ None | ❌ None | ✅ Yes |
| Performance | Fastest | Fast | Slightly slower (verified) |
| Applicable scenarios | Simple type | Requires default value/method | Requires strict verification |
| Initialization method | Dictionary | Class instance | Class instance |
Selection suggestions:
# 简单项目 → TypedDict
class State(TypedDict):
message: str
# 需要默认值 → Dataclass
@dataclass
class State:
message: str = "default"
# 需要验证 → Pydantic
class State(BaseModel):
message: str
@field_validator('message')
@classmethod
def validate_message(cls, v):
if len(v) < 1:
raise ValueError("Message cannot be empty")
return vPython-specific knowledge points
1. TypedDict detailed explanation
from typing_extensions import TypedDict
# 基础用法
class State(TypedDict):
name: str
age: int
# 可选字段
from typing import Optional
class State(TypedDict):
name: str
age: Optional[int] # 可以是 int 或 None
# total=False 使所有字段可选
class State(TypedDict, total=False):
name: str # 可选
age: int # 可选2. Detailed explanation of Literal type
from typing import Literal
# 限制字符串值
def set_mood(mood: Literal["happy", "sad"]):
...
set_mood("happy") # ✅
set_mood("angry") # ❌ IDE 警告
# 限制多种类型
def process(value: Literal[1, 2, "auto"]):
...
process(1) # ✅
process("auto") # ✅
process(3) # ❌ IDE 警告3. Detailed explanation of Pydantic Validator
from pydantic import BaseModel, field_validator, validator
class State(BaseModel):
name: str
age: int
# 方式 1: field_validator (推荐)
@field_validator('age')
@classmethod
def validate_age(cls, v):
if v < 0:
raise ValueError('Age must be positive')
return v
# 方式 2: 多字段验证
@field_validator('name', 'age')
@classmethod
def validate_both(cls, v, info):
# info.field_name 可以知道是哪个字段
if info.field_name == 'name' and len(v) < 1:
raise ValueError('Name cannot be empty')
return v4. Advanced usage of Dataclass
from dataclasses import dataclass, field
@dataclass
class State:
name: str
mood: str = "neutral" # 默认值
# 列表字段需要用 field(default_factory)
tags: list = field(default_factory=list)
# 计算属性
@property
def display_name(self):
return f"{self.name} ({self.mood})"
state = State(name="Alice")
print(state.mood) # "neutral"
print(state.display_name) # "Alice (neutral)"💡 Best Practices
1. When to use which state definition?
✅ TypedDict - most cases
# 推荐用于:
# - 简单的数据结构
# - 性能敏感的应用
# - 不需要运行时验证的场景
class State(TypedDict):
messages: list
user_id: str✅ Dataclass - Requires default value or method
# 推荐用于:
# - 需要默认值
# - 需要计算属性
# - 面向对象设计
@dataclass
class State:
messages: list = field(default_factory=list)
retries: int = 3
def should_retry(self):
return self.retries > 0✅ Pydantic - requires strict verification
# 推荐用于:
# - 外部输入(API、用户输入)
# - 关键数据(配置、凭证)
# - 需要复杂验证逻辑
class State(BaseModel):
api_key: str
max_retries: int
@field_validator('api_key')
@classmethod
def validate_key(cls, v):
if not v.startswith('sk-'):
raise ValueError('Invalid API key format')
return v
@field_validator('max_retries')
@classmethod
def validate_retries(cls, v):
if v < 1 or v > 10:
raise ValueError('Retries must be between 1 and 10')
return v2. State design principles
Principle 1: Minimize the state
# ❌ 不好 - 包含冗余数据
class State(TypedDict):
user_input: str
user_input_lower: str # 可以从 user_input 计算
user_input_length: int # 可以从 user_input 计算
# ✅ 好 - 只存储必需数据
class State(TypedDict):
user_input: str
def node(state):
# 需要时再计算
lower = state["user_input"].lower()
length = len(state["user_input"])Principle 2: Use explicit types
# ❌ 不好 - 类型模糊
class State(TypedDict):
data: dict # 什么 dict?
# ✅ 好 - 类型明确
from typing import List, Dict
class Message(TypedDict):
role: str
content: str
class State(TypedDict):
messages: List[Message]
user_info: Dict[str, str]Principle 3: Group related fields
# ❌ 不好 - 平铺所有字段
class State(TypedDict):
user_name: str
user_age: int
user_email: str
config_api_key: str
config_timeout: int
# ✅ 好 - 使用嵌套结构
class UserInfo(TypedDict):
name: str
age: int
email: str
class Config(TypedDict):
api_key: str
timeout: int
class State(TypedDict):
user: UserInfo
config: Config3. Common pitfalls
Trap 1: Modifying mutable objects
# ❌ 错误 - 直接修改 state
def node(state):
state["messages"].append("new message") # 危险!
return state
# ✅ 正确 - 返回新对象
def node(state):
new_messages = state["messages"] + ["new message"]
return {"messages": new_messages}Trap 2: Forgetting to initialize
# ❌ 错误 - 字段未初始化
class State(TypedDict):
messages: list
graph.invoke({}) # 报错!messages 未定义
# ✅ 正确 - 提供初始值
graph.invoke({"messages": []})
# 或使用 Dataclass 提供默认值
@dataclass
class State:
messages: list = field(default_factory=list)
graph.invoke(State()) # OKTrap 3: Pydantic Verification Performance
# ❌ 性能问题 - 复杂验证
class State(BaseModel):
data: list
@field_validator('data')
@classmethod
def validate_data(cls, v):
# 每次更新都运行!
for item in v:
complex_validation(item) # 慢!
return v
# ✅ 优化 - 只在必要时验证
class State(TypedDict):
data: list
def validate_once(state):
# 只在特定节点验证一次
for item in state["data"]:
complex_validation(item)
return state🚀 Advanced skills
1. Mixing multiple states
# 全局状态用 TypedDict(性能)
class OverallState(TypedDict):
messages: list
user_id: str
# 特定节点用 Pydantic(验证)
class ValidatedInput(BaseModel):
query: str
@field_validator('query')
@classmethod
def validate_query(cls, v):
if len(v) < 3:
raise ValueError("Query too short")
return v
def validation_node(state: OverallState):
# 验证输入
validated = ValidatedInput(query=state["messages"][-1])
return {"messages": state["messages"]}2. Dynamic status field
# 使用 Dict 存储动态数据
class State(TypedDict):
metadata: Dict[str, Any] # 动态字段
def node(state):
# 可以动态添加任意键
metadata = state.get("metadata", {})
metadata["timestamp"] = time.time()
metadata["custom_field"] = "value"
return {"metadata": metadata}3. Status version management
# 添加版本字段跟踪状态变化
class State(TypedDict):
data: str
version: int
def node_1(state):
return {
"data": state["data"] + " updated",
"version": state["version"] + 1
}
# 可以根据 version 做条件判断
def should_continue(state):
return "continue" if state["version"] < 5 else "stop"📊 Comparison and summary of three methods
Function comparison table
| Function | TypedDict | Dataclass | Pydantic |
|---|---|---|---|
| Type Tips | ✅ | ✅ | ✅ |
| IDE Support | ✅ | ✅ | ✅ |
| Runtime Verification | ❌ | ❌ | ✅ |
| Default | ❌ | ✅ | ✅ |
| Custom Method | ❌ | ✅ | ✅ |
| Access method | ["key"] | .key | .key |
| initialization | dictionary | instance | instance |
| Performance | Fastest | Fast | Moderate |
| Learning Curve | Low | Medium | Medium |
Summary of usage scenarios
# 🎯 选择决策树
# 1. 需要运行时验证?
# 是 → Pydantic
# 否 → 继续
# 2. 需要默认值或方法?
# 是 → Dataclass
# 否 → 继续
# 3. 追求最佳性能?
# 是 → TypedDictActual project suggestions
Small projects (< 10 nodes):
# 全用 TypedDict
class State(TypedDict):
messages: list
config: dictMedium-sized projects (10-50 nodes):
# 主状态用 TypedDict,配置用 Pydantic
class State(TypedDict):
messages: list
config: AppConfig # Pydantic model
class AppConfig(BaseModel):
api_key: str
timeout: intLarge projects (>50 nodes):
# 分层设计
class BaseState(TypedDict):
# 核心字段
messages: list
class ValidatedState(BaseModel):
# 需验证的字段
user_input: str
@dataclass
class CachedState:
# 需默认值的字段
cache: dict = field(default_factory=dict)🔍 Frequently Asked Questions
Q1: What should I do if the type hint of TypedDict does not work?
Reason: TypedDict only provides static type checking and does not perform runtime verification.
Solution:
- Use IDE (VSCode, PyCharm) for static checking
- Use mypy for type checking:bash
pip install mypy mypy your_script.py - For runtime verification, use Pydantic instead
Q2: Why does the Dataclass node return a dictionary?
Reason: LangGraph stores states by fields (channels), and the dictionary returned by the node is automatically mapped to the corresponding channel.
Example:
@dataclass
class State:
name: str
age: int
def node(state):
# state 是 dataclass,访问用点号
updated_name = state.name + " Smith"
# 返回字典,LangGraph 会自动更新对应 channel
return {"name": updated_name} # ✅ 正确Q3: Will Pydantic verification failure cause the graph to crash?
**Yes. ** Pydantic verification failure will throw ValidationError, causing graph execution to be interrupted.
Solution:
def node(state):
try:
validated = MyModel(**state)
return {"data": validated.data}
except ValidationError as e:
# 处理错误
return {"error": str(e), "data": None}Q4: Can the state structure be changed at runtime?
**Not recommended. ** State Schema should be determined when defining the diagram.
If dynamic fields are required:
# 使用 Dict 存储动态数据
class State(TypedDict):
static_field: str
dynamic_data: Dict[str, Any] # 动态字段放这里📖 Further reading
- LangGraph State official document
- TypedDict official document
- Dataclasses official document
- Pydantic official documentation
🎯 Practical exercises
Exercise 1: Implement chatbot state
Requirements:
- Store conversation history (message list)
- Store user information (name, age)
- Storage configuration (API key, model name)
Challenge: Use TypedDict, Dataclass, and Pydantic to implement respectively, and compare the advantages and disadvantages.
Exercise 2: Status Verification
Requirements:
- Create a Pydantic state
- Adding a validator ensures:
- Age between 0-150
- The email format is correct
- Password length >= 8
Exercise 3: Nested States
Requirements:
- Create nested state structures (User → Address → City/Street)
- Implement node update nested fields
Summary: State Schema is the basis of LangGraph. Understanding the advantages and disadvantages of the three definition methods can help you design more robust and efficient AI applications. Choosing the appropriate state definition method is the first step in building a maintainable LangGraph application!