Defining and Managing State in LangGraph
State is the central memory backbone of your agent. In this lesson, master TypedDict schemas, understand the critical difference between overwrites and reducers, and learn how add_messages prevents accidental history loss.
1. Core Mechanics of LangGraph State
Select a state pattern to inspectState Reducer Inspector
# 1. DEFINING AN AGENT STATE SCHEMA WITH TYPEDDICT
from typing import TypedDict, Annotated, List, Optional
from langchain_core.messages import BaseMessage
from langgraph.graph.message import add_messages
class AgentState(TypedDict):
# Annotated with a reducer: messages are appended, not overwritten
messages: Annotated[List[BaseMessage], add_messages]
# Standard scalar fields: default behavior is overwrite with new value
current_step: int
user_id: str
is_authorized: bool
context_documents: List[str]2. Interactive State Reducer Inspector
Real-time Reducer SandboxLangGraph State & Reducer InspectorState Mutation Lab
Observe the difference between Default Overwrite Reducers and Annotated Append Reducers
from typing import TypedDict, Annotated
import operator
class State(TypedDict):
# Appends updates to list
messages: Annotated[list, operator.add]
counter: intCommon Engineering Traps
Defining messages: list[BaseMessage] in your TypedDict means any node returning {"messages": [new_msg]} overwrites the prior array. The agent appears amnesiac on turn 2 because turn 1 was erased. Always annotate with add_messages.
Placing live database connections, client sessions, or open file pointers inside State will crash Postgres/Redis checkpointers during serialization. Keep State pure data (strings, ints, lists, dicts, BaseMessages) and initialize clients externally.
Key Architectural Takeaways
- 1.State is Immutable & Functional: Nodes return partial deltas, and LangGraph merges them deterministically using registered reducer functions.
- 2.add_messages Handles Deduplication: The add_messages reducer uses message IDs. If an existing message has ID 'x' and a new message arrives with ID 'x', it replaces that specific message in place rather than duplicating it.
- 3.Checkpointers Require Clean Schemas: Clean primitive schemas enable checkpoint persistence, rewind capability, and multi-tenant thread isolation.
Structured Logging and Observability
You cannot optimize what you do not measure. Learn how to log agent runs, track token expenditure, trace multi-step tool calls, and diagnose production agent failures.