States are the data that flows through your graph. They’re defined as TypedDict for type safety.
Basic State Definition
from typing_extensions import TypedDictclass MyState(TypedDict): input: str output: str count: int
State Reducers
Reducers control how state updates are merged. By default, new values replace old ones:
from typing import Annotated, Listimport operatorclass RichState(TypedDict): # Reducer: operator.add - new items append to list messages: Annotated[List[str], operator.add] # Reducer: sum - numeric values add together total_cost: Annotated[float, lambda a, b: a + b] # No reducer - new value replaces old (default) current_step: str
Common Reducer Patterns:
Reducer
Behavior
Use Case
operator.add
Append/concatenate
Lists, strings
lambda a, b: a + b
Sum values
Counters, totals
max
Keep maximum
Scores, priorities
min
Keep minimum
Costs, distances
Example: Message History
from typing import Annotated, Listimport operatorclass ChatState(TypedDict): messages: Annotated[List[str], operator.add] turn_count: Annotated[int, lambda a, b: a + b] topic: strdef node1(state: ChatState) -> dict: return { "messages": ["Hello"], # Appends to list "turn_count": 1, # Adds to counter "topic": "greeting" # Replaces old value }def node2(state: ChatState) -> dict: return { "messages": ["How are you?"], # Appends "turn_count": 1 # Adds 1 }# After both nodes:# messages = ["Hello", "How are you?"]# turn_count = 2# topic = "greeting"
Nodes
Nodes are functions that process state. They receive the current state and return updates.
Basic Node
def my_node(state: MyState) -> dict: """Process state and return updates.""" result = process(state["input"]) return { "output": result, "count": state["count"] + 1 }
Recursion Limits: Always set a recursion_limit when using loops to prevent infinite execution. Default is 100 steps.
Best Practices
1. Keep Nodes Focused
Each node should have a single responsibility:
# ✅ Good - focused nodesdef fetch_data(state): ...def process_data(state): ...def validate_results(state): ...# ❌ Bad - doing too muchdef big_node(state): # Fetch data # Process data # Validate # Store results pass
Think about what needs to be in state vs what can be computed:
# ✅ Good - only essential dataclass State(TypedDict): items: List[str] # Compute count when needed: len(state["items"])# ❌ Bad - storing derived dataclass State(TypedDict): items: List[str] item_count: int # Can be computed from items