Four Ways to Write the State
The state is a class that lists the keys. LangGraph accepts four kinds of class. Your 01_states.py shows all four.
Way 1: TypedDict. Simple, and the most common.
class State(TypedDict): topic:str summary:str score:str
Way 2: Pydantic. It checks the data: here, the score must not be negative.
from pydantic import BaseModel , field_validator class State(BaseModel): topic:str score:int summary:str="" @field_validator("score") @classmethod def score_postive(cls ,v): if v <0: raise ValueError("score must be postive") return v
Way 3: dataclass. It lets you give default values.
from dataclasses import dataclass , field @dataclass class State(): topic:str ="" score :int=0 messages :list = field(default_factory=list)
Way 4: MessagesState. For chatbots: it already has a
messages list.from langgraph.graph import MessagesState class State(MessagesState): user_name:str language:str
| Way | Use it when |
|---|---|
TypedDict | you want it simple. Most graphs use this. |
Pydantic BaseModel | the data must be checked, for example a score that must be positive. |
@dataclass | you want default values. |
MessagesState | you are building a chatbot and want the message list ready made. |
Overwrite or Merge? Reducers
By default, a new value replaces the old one. Sometimes that loses data.
Without a reducer: overwrite
One check writes {'toxicity': 12}.Another check writes {'copyright_risk': 8}.One after the other: the second overwrites the first, and the first score is lost.At the same time: LangGraph stops with an error, because a key can receive only one value per step.With a reducer: merge
One check writes {'toxicity': 12}.Another check writes {'copyright_risk': 8}.The state keeps both: {'toxicity': 12, 'copyright_risk': 8}Example scores. The merge is exactly what your
merge_score_dicts does. We tested both cases on the installed LangGraph.def merge_score_dicts(existing : dict , newUpdate:dict) -> dict: if existing is None: return newUpdate return {**existing, **newUpdate} class AnlayzerState(TypedDict): raw_text : str safety_scores :Annotated[dict[str,int],merge_score_dicts]
Reducer
A function that says how to combine the old value and the new value of one key.
Annotated
Annotated[type, reducer] attaches the reducer to that key. Keys without it simply overwrite.Built in
MessagesState already uses a reducer for messages, so new messages are added to the list, not overwritten.The code is from your
01_parallel_reducers.py. You will use it in the Parallel lesson, where three nodes write at the same time.Quick Revision
The whole lesson on one page.
State
The shared notebook
A dictionary with fixed keys. Every node reads it and writes to it.
Nodes
Return only what changes
A node gets the whole state and returns a small dictionary. LangGraph merges it in.
Reducers
Overwrite or merge
By default a key is overwritten. A reducer, attached with
Annotated, merges the old and new values.LangGraph docsGraph API: state and reducers
Code
01_states.py01_states.py · 49 linesShow code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | from typing import TypedDict # 1 typed DICT class State(TypedDict): topic:str summary:str score:str #2 pydantic approch # it is good at data validaition from pydantic import BaseModel , field_validator class State(BaseModel): topic:str score:int summary:str="" @field_validator("score") @classmethod def score_postive(cls ,v): if v <0: raise ValueError("score must be postive") return v # 3 python dataclasses from dataclasses import dataclass , field @dataclass class State(): topic:str ="" score :int=0 messages :list = field(default_factory=list) # 4 from langgraph.graph import MessagesState class State(MessagesState): user_name:str language:str |