Intermediate11 min
State: The Agent's Brain
Designing state: TypedDict, Pydantic, reducers, and the add_messages pattern.
Quick Reference
- →TypedDict is the default state type — lightweight, no validation overhead
- →Pydantic v2 BaseModel adds runtime coercion and validation on every state update
- →Reducers (Annotated[list, operator.add]) control how node outputs merge into state
- →add_messages is the built-in reducer for chat messages — handles deduplication by ID
- →MessagesState is a pre-built state class with a messages key using add_messages
- →RemoveMessage lets nodes surgically delete messages from the state history
3 Ways to Define State
State flows through nodes — each returns a partial update, merged via reducers
| Type | Validation | Coercion | Performance | Use When |
|---|---|---|---|---|
| TypedDict | None (trust nodes) | None | Fastest | Simple state, trusted nodes |
| Pydantic BaseModel | On every update | Yes (v2) | Slower | Need validation, external input |
| dataclass | None | None | Fast | Prefer dataclass syntax |
TypedDict — the default
Pydantic — when you need validation