Mod 2.8Defining and Managing State in LangGraph
Level 2›Module 2.8
Level 2: Core Implementation & WorkflowsModule 2.8

Defining and Managing State in LangGraph

Managing State in

Level 2 • Core Implementation & Workflows
Est. ~18 mins
5 Key Topics
🎁 Free Learner Perk

Unlock Verified Certificate & Daily Streak Tracker

Ready to master Defining and Managing State in LangGraph? Enable cloud sync to record your daily streak 🔥 and earn your Informational Completion Badge for your study milestones.

Day 1 Streak ActiveFree Completion BadgeSync Laptop & Phone
Module 2.8 • Core Implementation~20 min interactive

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 inspect

State Reducer Inspector

state_schema.py • schema
# 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 Sandbox

LangGraph State & Reducer InspectorState Mutation Lab

Observe the difference between Default Overwrite Reducers and Annotated Append Reducers

1. Reducer Configuration
Simulate Graph Progression:
# LangGraph State Schema:
from typing import TypedDict, Annotated
import operator

class State(TypedDict):
    # Appends updates to list
    messages: Annotated[list, operator.add]
    counter: int
2. Current State Snapshot (Memory)After Initial State (START)
STATE DICTIONARYAccumulative Memory
counter: 0
messages: [
"User: 'Find flights to Tokyo'"
]
📌 Cardinal Rule of LangGraph State: If a field is a list and you don't attach a reducer like Annotated[list, add_messages], the very first node that returns a message will wipe out the entire user conversation history! Always annotate lists that aggregate data over turns.

Common Engineering Traps

TRAP #1: Plain list vs Annotated[list, add_messages]

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.

TRAP #2: Storing Non-Serializable Objects in State

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.
Up Next • Module 2.9

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.

Continue to Module 2.9