14  State Schemas

Every graph in this book has started with class State(TypedDict), and Chapter 3’s Deep Dive said in passing that LangGraph also accepts dataclasses and Pydantic models. This chapter lays out the four ways to write State, what each buys, and what each does to the reads inside your nodes — because the declaration decides more than what goes in: change it and every state["question"] in the graph changes with it.

State can be a TypedDict, a Pydantic BaseModel, a @dataclass, or the prebuilt MessagesState. The one you choose decides validation, defaults, and access style, and the access style is not yours to pick: it follows the type.

No model runs in this chapter; every output below is deterministic.

14.1 What we’re building

One small graph, a single node that reads a question and writes an answer, built four times. The builder code (StateGraph, add_node, two edges, compile) is the same in every version; only the State type moves, and with it the way the node reads the state. The fourth version, MessagesState, renames the node to chat and carries messages rather than a bare answer, but keeps the same one-node topology.

flowchart LR
    START(["START"]) --> answer["answer"]
    answer --> END(["END"])

14.2 TypedDict: the shape the book already used

A TypedDict is, at runtime, a plain dict. The annotations exist for your editor and your future self, and LangGraph does not check them at runtime, as Chapter 3 showed. Nodes read fields with subscripts, state["question"], because a node receives a dict.

from typing import NotRequired, TypedDict


class State(TypedDict):
    question: str
    answer: NotRequired[str]


def make_answer(question: str) -> str:
    # `.strip()` is an ordinary string operation - it only works on a real str.
    # That matters in the dataclass section, where a bad value gets this far.
    return f"You asked: {question.strip()}"


def answer_typeddict(state: State) -> dict:
    print('  [typeddict]  read state["question"] (subscript)')
    return {"answer": make_answer(state["question"])}

make_answer is shared by every version below: it trims the question and echoes it. Wiring it is the graph you’ve built a dozen times:

from langgraph.graph import StateGraph, START, END

builder = StateGraph(State)
builder.add_node("answer", answer_typeddict)
builder.add_edge(START, "answer")
builder.add_edge("answer", END)
graph = builder.compile()

Invoke it and you get an ordinary dict back:

===== 1. TypedDict (the default, lightest) =====
  [typeddict]  read state["question"] (subscript)
  result: {'question': ' how do I configure Kafka? ', 'answer': 'You asked: how do I configure Kafka?'}

That’s the baseline, and all three of the next versions print that same result: line on the happy path — so from here on only the lines that differ are shown. The build code isn’t repeated either; it does not change. The class and the node’s read do.

14.3 BaseModel: validation at the door

Validation looks like a one-line change: swap class State(TypedDict) for class State(BaseModel) and Pydantic rejects question=123 at invoke(). Then run it and the first node dies with TypeError: 'State' object is not subscriptable, because a node now receives a model instance, read with a dot. Every node that touches the state changes with the declaration.

So the swap buys validation at the door — the input is checked before any node runs, fields with defaults are not required, and the model coerces what it safely can — and it costs you every read: state["question"] becomes state.question.

from pydantic import BaseModel


class ValidatedState(BaseModel):
    question: str
    answer: str = ""


def answer_model(state: ValidatedState) -> dict:
    print("  [basemodel]  read state.question (attribute)")
    return {"answer": make_answer(state.question)}

Wire and compile as before (StateGraph(ValidatedState), same three lines), and the happy path looks the same. The difference shows the moment the input is wrong. Feed question an int where a str belongs:

graph.invoke({"question": 123})   # question should be a str
===== 2. Pydantic BaseModel (runtime validation) =====
  [basemodel]  read state.question (attribute)      # ... same result: line
  --- feeding it a bad value: question=123 ---
  ValidationError raised at invoke(), before any node ran:
    question: Input should be a valid string (got 123)

That is the whole reason to reach for a BaseModel: the bad value never reaches a node. invoke() raises pydantic.ValidationError at the door, naming the field; a missing required field fails the same way. When the graph sits behind an HTTP handler and the input is whatever a client sent, that early rejection is worth the weight.

NoteDeep Dive: the state a node sees, and the value invoke returns

Two different objects wear the word “state” here. Inside a node, a BaseModel (or @dataclass) state arrives as a real instance — hence state.question. But invoke() hands back a plain dict of channel values whatever the schema type, which is why the result: lines are all dicts. The schema governs how nodes read the state in flight; it does not turn the graph’s return into an object. And a BaseModel state instance is built — and validated — for each node it reaches, not only at the first invoke(): a bad value written mid-graph is caught when the next node’s input is constructed, exactly the asymmetry Chapter 3 opened on.

14.4 dataclass: defaults without the checks

A @dataclass sits in the middle. Like BaseModel it gives you defaults and attribute access; like TypedDict it does no validation. That combination is easy to misjudge, so here it is failing.

from dataclasses import dataclass


@dataclass
class DataclassState:
    question: str
    answer: str = ""


def answer_dataclass(state: DataclassState) -> dict:
    print("  [dataclass]  read state.question (attribute)")
    return {"answer": make_answer(state.question)}

Now feed it the same bad value that BaseModel rejected at the door:

===== 3. dataclass (defaults, attribute access, no validation) =====
  [dataclass]  read state.question (attribute)      # ... same result: line
  --- feeding it the SAME bad value: question=123 ---
  [dataclass]  read state.question (attribute)
  input passed schema construction; the node then raised:
    AttributeError: 'int' object has no attribute 'strip'

invoke() accepted question=123 and the node read the field fine — 123 is a perfectly good attribute value. It only detonated when make_answer called a string method on it. That is the tax of no validation: the stack trace points at a symptom (.strip()) rather than the cause, and the further the bad value travels before something touches it, the further the two sit apart.

14.5 MessagesState: the prebuilt chat state

The fourth option isn’t a way of writing a schema so much as a schema LangGraph ships ready-made. MessagesState is a TypedDict with a single field baked in:

class MessagesState(TypedDict):
    messages: Annotated[list[AnyMessage], add_messages]

(AnyMessage is langchain-core’s union of the message types.) That Annotated[..., add_messages] is a reducer like those in Chapter 10: instead of overwriting messages, add_messages appends and reconciles ids. You subclass it to add your own fields, and because it’s a TypedDict, access is by subscript again.

from langchain_core.messages import AIMessage, HumanMessage
from langgraph.graph import MessagesState


class ChatState(MessagesState):
    user_id: str


def chat_node(state: ChatState) -> dict:
    incoming = state["messages"][-1].content
    print(f'  [messages]   user={state["user_id"]} said {incoming!r}; appending a reply')
    # Return ONE message; the add_messages reducer appends it to the list.
    return {"messages": [AIMessage(content=f"You asked: {incoming.strip()}")]}

Invoke it with one human message (a hard-coded turn shows the reducer without a model) and the reply is appended, not substituted:

===== 4. MessagesState (prebuilt, for chat / tool-calling) =====
  [messages]   user=u_123 said 'how do I configure Kafka?'; appending a reply
  result: 2 message(s), user_id='u_123'
    HumanMessage: 'how do I configure Kafka?'
    AIMessage: 'You asked: how do I configure Kafka?'

The node returned a one-element list, yet the result holds two messages: the reducer merged the new one onto the history. This is the shape LangGraph’s prebuilt tool-calling machinery expects, which is why Chapter 13 ran on it. Reach for it whenever the graph is a conversation.

14.6 The four schemas side by side

Four questions decide it: does it validate, does it give defaults, how do nodes read it, and how heavy is it.

Schema Validation when constructing node input Defaults Access in a node Weight Reach for it when
TypedDict no no state["x"] lightest the default — most graphs
BaseModel yes (strong) yes state.x heavy input is untrusted; fail early
@dataclass no yes state.x middle you want defaults + attributes, not checks
MessagesState no messages starts empty state["messages"] light chat / tool-calling agents

The validation column is narrower than it looks. A BaseModel state polices reads, not writes: what Pydantic validates is the object LangGraph builds for a node to read. A node returning {"answer": 12345} into a string field lands in the result unchanged, and only raises if that value becomes some later node’s input. Every node still returns a plain, unvalidated partial dict.

The book’s default stays TypedDict, the lightest thing that works; you move off it only when untrusted input or a chat history asks you to.

WarningGotcha: change the schema type and every node’s reads must change

The access column is dictated by the type: BaseModel and @dataclass states are objects, read with a dot; TypedDict and MessagesState are dicts, read with brackets:

docs = state["docs"]   # TypedDict / MessagesState — subscript
docs = state.docs      # BaseModel / @dataclass   — attribute

So the one-line change from this chapter’s opening is never one line. Every node flips from state["x"] to state.x, and state.get("x", default) — the defensive read this book relies on — has no attribute equivalent, becoming getattr(state, "x", default) or a plain default on the model. Miss one and it fails only when that node runs, which on a branching graph may be a path your first test never takes. Decide the schema type early.

14.7 Three things that don’t change

Whichever of the four you pick, three rules hold across all of them.

Reducers ride Annotated. The Annotated[list, add_messages] in MessagesState is the same mechanism as Annotated[list, operator.add] from Chapter 10, and it works the same in a TypedDict, a BaseModel, or a @dataclass.

Nodes return only what changed. Every node in this chapter returned a small dict, {"answer": ...} or {"messages": [...]}, never the whole state. The schema decides how you read; it does not change how you write back.

You can split the public shape from the internal one. The state a graph runs on is often wider than what a caller should send or see. StateGraph takes two optional schemas for this:

1class InputState(TypedDict):
    question: str

2class OutputState(TypedDict):
    answer: str

3class InternalState(TypedDict):
    question: str
    scratch: str       # never leaves the graph
    answer: str

builder = StateGraph(
    InternalState, input_schema=InputState, output_schema=OutputState
)
1
input_schema selects which channels invoke() accepts.
2
output_schema selects which channels the final invoke() result carries.
3
The graph runs on the full state in between.
===== 5. Input / output schema separation =====
  invoke saw only {question}; internal 'scratch' is hidden from output
  result: {'answer': 'You asked: how do I configure Kafka?'}

The caller supplied only question and the result carried only answer; scratch did its work inside the graph. This is a projection, not a wall — extra input keys are ignored rather than rejected, and scratch is still visible to a caller streaming the run’s intermediate steps (Chapter 18). You buy a smaller, more stable public contract on invoke(), not a secret.

14.8 What doesn’t go in State: runtime context

Those three rules are about what lives inside State. A fourth is about what stays out. The model handle, a user_id, a database connection: a node reaches for them, yet they aren’t data the graph produces. Park them in State and you’ve mixed dependencies into your data; leave them as module-level globals and you’re editing globals to serve two users on different models.

The distinction is data versus dependency. It is also the line between what may be written down and what must not: everything in State reaches the checkpointer, every trace, and every endpoint that returns a run — in the clear, as Section 26.8 will show you with strings — so an API key, a tenant id that scopes a search (Section 27.4), anything you would not want copied everywhere the state goes, belongs on the dependency side. LangGraph 1.x gives dependencies their own typed channel, separate from state, called runtime context. You declare its shape with context_schema, and every node can read a Runtime object whose .context holds those per-run values:

from dataclasses import dataclass
from typing import NotRequired, TypedDict
from langchain_core.language_models import BaseChatModel
from langgraph.runtime import Runtime


@dataclass
class Context:
    user_id: str
    llm: BaseChatModel    # the model handle itself — a dependency, not data
    model_label: str      # a display name; see the note below


class State(TypedDict):
    question: str
    answer: NotRequired[str]   # the model/user/db are NOT here


# A node's optional SECOND parameter is the Runtime; LangGraph injects it.
def answer_node(state: State, runtime: Runtime[Context]) -> dict:
    llm = runtime.context.llm
    user_id = runtime.context.user_id
    # Display the label from context, not `llm.model_name`: that attribute is
    # provider-specific, and reading it here would narrow `llm` from any
    # BaseChatModel to an OpenAI handle. The node touches `llm` only through the
    # shared interface (e.g. .invoke()).
    label = runtime.context.model_label
    print(f"[answer] user={user_id} using model={label}")
    return {"answer": f"question from {user_id}, to be answered by {label}"}

Declaring the shape and supplying the values are two separate lines:

1builder = StateGraph(State, context_schema=Context)
# ... add_node / add_edge / compile() as before ...

graph.invoke(
    {"question": "ping"},
2    context=Context(user_id="u_123", llm=big_model,
                    model_label="openai/gpt-oss-20b"),
)
1
The context shape is declared when you build the graph.
2
The values are passed at invoke time under context=, its own argument next to the state.

Run it for two users on two models and the same compiled graph serves both, with nothing added to State:

[answer] user=u_123 using model=openai/gpt-oss-20b
  -> question from u_123, to be answered by openai/gpt-oss-20b
[answer] user=u_777 using model=qwen2.5-vl-7b-instruct
  -> question from u_777, to be answered by qwen2.5-vl-7b-instruct

Because the model handle rides context, this is also what makes the doc-bot testable: a test invokes the same graph with llm=FakeListChatModel(responses=[…]) through the very same channel, and nothing in the node changes. That only holds because the node uses llm through the shared BaseChatModel interface — reaching for a provider-specific attribute like llm.model_name would quietly narrow the dependency and break the swap, which is why the display name rides context too.

One clarification, since the names sit close together: runtime context (context=, typed by context_schema) is distinct from the config= dict carrying the framework’s own knobs (recursion_limit, thread_id) and from the older, untyped config["configurable"]. Use context for the model, the user, the db; leave config for the framework’s settings.

Row by row:

State Runtime context
Holds data flowing through the graph the dependencies a run needs
Which is question, docs, answer model handle, user_id, db connection
Passed at invoke the first argument (the input dict) context=, its own argument
Declared with StateGraph(State) context_schema=Context
A node reads it via state["x"] (or state.x) runtime.context.x
Written during the run? yes — nodes return updates that merge not by the framework — treat it as read-only dependencies
Saved by a checkpointer? yes — it is the checkpoint no — rebuilt on every invoke

The last two rows are the reason to keep them apart: data persists, so it belongs in State and lands in the checkpoint; dependencies are handed in fresh on every invoke and never touch it.

“Read-only” here is a convention, not a guarantee. LangGraph does not deep-freeze the context object, and nothing routes a change made to it back into State. A node can reassign runtime.context.x, it just should not. A frozen dataclass stops field reassignment, but mutable objects inside it still need their own ownership and concurrency rules — especially across parallel branches.

14.9 The same shape elsewhere

Data versus dependency is the line every server framework draws at its front door. The request body is data: it arrives per call, it belongs to the caller, you validate it. The database handle is a dependency: wired in from outside, never seen by the caller. Dependency injection is the name for keeping the second out of the first. context_schema is that container sized down to one typed object per run; State is the request body. input_schema and output_schema are the other half — a narrower request and response type over a wider internal one, which is a DTO projection by another name.

The analogy has one sharp edge, and the chapter already put a warning on it: this projection is not a wall. A strict deserializer rejects an unknown field; input_schema merely ignores it.

14.10 Before moving on

All five demonstrations live in one file (python code/ch12_state_schemas.py). Three judgments to carry out of it:

  • Pick the schema type before the second node exists. TypedDict until something asks for more; BaseModel when the input is a client’s; MessagesState when the graph is a conversation. A @dataclass buys only defaults and dotted access.
  • A schema change is a change to every node — reads flip between state["x"] and state.x, state.get has no attribute form, and a missed node fails only when it runs.
  • Validation is on the way in, and only there. Nodes return unvalidated partial dicts whatever the schema, and input_schema/output_schema project the public shape without policing it. Dependencies ride context_schema and a node’s Runtime, not State and not config.

We’ve now looked hard at the container that flows through a graph. The next chapter steps back further and questions the graph itself: the Functional API gives you LangGraph’s powers — persistence, human-in-the-loop, streaming — over ordinary Python functions, with @task and @entrypoint and no StateGraph to build at all.

New pieces in this chapter

Piece Usage
Type
AIMessage Langchain-core’s message type for a model’s turn. AIMessage(content=…); return it in a one-element list and the add_messages reducer appends it
HumanMessage Langchain-core’s message type for a user’s turn. HumanMessage(content="how do I …?"); arrives on the input messages list
BaseChatModel Langchain-core’s base type that all chat models share. llm: BaseChatModel in the Context dataclass; lets a test hand in a fake model with no node changed
Runtime The typed runtime-context object injected as a node’s optional second parameter. def answer_node(state, runtime: Runtime[Context]); read dependencies via runtime.context.x
API
add_messages Reducer for chat history. messages: Annotated[list[AnyMessage], add_messages]; appends new messages and replaces existing ones with the same message id
@dataclass Decorator: stdlib state schema with defaults and attribute access, no validation. @dataclass on class DataclassState:; a bad input passes the door and only blows up later, deep in a node
StateGraph(input_schema=…, output_schema=…) Keyword args: select which channels invoke() accepts and which its result carries. StateGraph(InternalState, input_schema=…, output_schema=…); a projection, not a wall — extra input keys are ignored
StateGraph(context_schema=…) Keyword arg: declare the typed shape of a run’s dependencies. StateGraph(State, context_schema=Context); context is rebuilt on every invoke — never checkpointed
invoke(context=…) Keyword arg: pass the dependencies at invoke time, beside the state. graph.invoke({"question": …}, context=Context(…)); distinct from the framework’s config= dict

Code in this chapter

File What it runs
code/ch12_state_schemas.py The same question/answer graph written four ways – TypedDict, BaseModel, @dataclass, MessagesState – and what each validates.
code/ch12_runtime_context.py Ambient dependencies (the model handle, the user id) passed as runtime context instead of riding in State.

Challenge

🥉 Bronze — make the door reject bad input

Take a real slice of the doc-bot’s state — question: str, route: str, iterations: int — and write it twice: once as a @dataclass, once as a BaseModel. On the BaseModel, give iterations a floor with Field(ge=0) so a negative count is illegal.

Invoke each with a deliberately broken input (iterations=-5, or question=123). Predict first, then run. The BaseModel should raise ValidationError at invoke(), before any node runs, naming the field; the @dataclass accepts the same input and only surfaces the problem (if at all) when a node touches the bad field. Write down where each failure lands.

office hours Worked solution with tests: code/answers/ch12_validating_state.py.

🥈 Silver — three windows, one state

Take the InputState / OutputState / InternalState split from this chapter and wire it into a two-node graph: think reads question and writes scratch, answer reads scratch and writes answer. Before running anything, write down four predictions:

  1. What does graph.invoke({"question": "kafka"}) return — all three fields, or fewer?
  2. Feed an extra key: invoke({"question": "kafka", "smuggled": 42}). Error, or no error? Can any node see smuggled?
  3. Have a node return a key that appears in no schema. Error, or no error? Where does the value end up?
  4. Leave the question out entirely: invoke({}). Does the door catch it?

Prediction 3 is the one to get wrong on paper first; I did. I wrote down “error”, ran it, got None back from invoke, and spent a while looking for the exception that never came. A key no schema lists is not an error: it lands in no channel and is gone, silently, and if a required output field is missing as a result, invoke returns None without a word. The framework will not say so; a check at the node boundary is the only thing that will.

office hours Worked solution with tests: code/answers/ch12_schema_windows.py.