State schemas — TypedDict, Pydantic and dataclasses
Overview
In the previous lesson, Understanding graph state, you learned that state is the shared information flowing through a LangGraph workflow. Nodes read that information, perform operations, and return updates that become available to subsequent nodes.
However, an important engineering question remains: how do we define the structure of that information?
Imagine building a customer support agent that needs to maintain:
- The customer’s original message.
- Conversation history.
- The detected intent of the request.
- Retrieved knowledge base documents.
- A generated response.
- Whether human assistance is required.
- Intermediate processing information.
Without a defined structure, developers might introduce inconsistent field names, incompatible data types, and assumptions about which information exists at different execution stages.
A state schema establishes a common data contract for the workflow. It describes the fields that can participate in graph state, their expected types, and, when required, how their updates should be combined.
LangGraph supports three primary Python schema styles:
TypedDict- Pydantic
BaseModel - Python
dataclass
The graph execution model remains fundamentally the same regardless of the schema style.
Environment setup
Use Python 3.11 or newer and install the required packages:
python -m pip install -U "langgraph>=1,<2" "langchain>=1,<2" "pydantic>=2,<3" typing-extensionsCheck the installed versions:
python -c "from importlib.metadata import version; print(version('langgraph')); print(version('langchain'))"All examples use the LangGraph 1.x Graph API. They deliberately use deterministic Python functions instead of LLM calls so that you can study state behavior without API credentials, network requests, or model variability.
The examples are designed as standalone scripts and have been checked against the current API documentation, although they have not been execution-tested in this authoring environment.
How LangGraph interprets a schema
When you construct a StateGraph, LangGraph examines the supplied schema and identifies its state channels.
For example, a schema containing question, category, and answer establishes three named channels.
During execution, LangGraph prepares a state view for the active node. The node returns an update, and the framework applies that update to the appropriate channels. Sequential nodes can then consume the updated values.
The following diagram illustrates this process.
A schema is therefore more than documentation, but it is not automatically a comprehensive validation system. Its exact capabilities depend on the Python type used to define it.
The schema describes what data participates in the graph. Reducers, introduced in the next lesson, determine how updates to individual channels are combined.
TypedDict
What is TypedDict?
TypedDict is a Python typing construct that describes dictionaries with predefined keys and expected value types.
Unlike an ordinary annotation such as dict[str, str], a TypedDict allows different keys to have different types.
Consider this definition:
from typing_extensions import TypedDict
class CustomerState(TypedDict):
customer_id: str
message: str
priority: int
resolved: boolHere, each key has a specific meaning and expected type.
Editors and static analysis tools such as Pyright and mypy can use these declarations to identify incorrect assignments, misspelled keys, and incompatible function arguments.
At runtime, however, a TypedDict value is still an ordinary dictionary. Creating one does not automatically validate its contents.
For example, Python itself does not reject a string assigned to the integer priority field. A static type checker may report the mistake, but runtime validation must be implemented separately.
Building a TypedDict state graph
The following example implements a simple support workflow that classifies a customer message and generates a response.
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
message: str
category: NotRequired[str]
response: NotRequired[str]
def classify(state: State) -> dict:
message = state["message"].lower()
category = (
"billing" if "payment" in message
else "general"
)
return {"category": category}
def respond(state: State) -> dict:
if state["category"] == "billing":
response = "We can help with your payment issue."
else:
response = "How can we assist you?"
return {"response": response}
builder = StateGraph(State)
builder.add_node("classify", classify)
builder.add_node("respond", respond)
builder.add_edge(START, "classify")
builder.add_edge("classify", "respond")
builder.add_edge("respond", END)
graph = builder.compile()
result = graph.invoke({
"message": "I have a payment problem"
})
print(result)Expected output:
{'message': 'I have a payment problem', 'category': 'billing', 'response': 'We can help with your payment issue.'}Notice that the invocation supplies only message. The remaining fields are produced during execution.
The classification node returns only category, while the response node returns only response. Neither node needs to return the entire dictionary.
Required and optional fields
A common mistake is assuming that every declared state field must already contain a value when execution begins.
State evolves throughout the workflow. A field populated by the third node may not exist when the first node runs.
Python provides NotRequired to describe keys that may be absent:
from typing_extensions import TypedDict, NotRequired
class State(TypedDict):
question: str
answer: NotRequired[str]
confidence: NotRequired[float]This is different from allowing a value to be None.
| Declaration | Meaning |
|---|---|
answer: str |
The key is expected to exist with a string value. |
answer: str | None |
The key is expected to exist but may contain None. |
answer: NotRequired[str] |
The key may be absent; when present, it should contain a string. |
answer: NotRequired[str | None] |
The key may be absent or contain a string or None. |
These distinctions primarily communicate expectations to type checkers and developers. They do not turn TypedDict into a runtime validator.
If a node reads an absent key using state["answer"], ordinary Python dictionary behavior applies and a KeyError may occur.
Use state.get("answer") when absence is legitimate. When the field is essential, ensure that the graph’s execution order guarantees its creation rather than silently masking a workflow error.
Returning partial updates
Suppose the current graph state is:
{
"message": "Payment failed",
"category": "billing",
"response": "Pending"
}A node returns:
{"response": "Please check your payment method."}The updated state retains message and category, while response receives its new value.
For ordinary fields without custom reducers, sequential updates replace the existing value. Omitting a field leaves its existing value unchanged.
This distinction becomes particularly important in conversational applications, where different nodes maintain different parts of the shared state.
Tip: Treat the state received by a node as a read-only snapshot. Return explicit updates instead of mutating dictionaries, lists, or nested objects in place.
TypedDict is generally the best starting point because it offers clarity with minimal overhead.
Pydantic
Why use Pydantic state schemas?
Real-world applications receive information from users, APIs, databases, and language models. That information may not satisfy the types or business constraints that your application expects.
Pydantic provides tools for validating and transforming such data into structured Python objects.
A Pydantic schema inherits from BaseModel and can define:
- Required fields and default values.
- Numeric ranges and string length constraints.
- Allowed values.
- Nested data models.
- Custom field and model validators.
- Strict or coercive type handling.
Unlike TypedDict, Pydantic actively validates data when a model is constructed or explicitly validated.
Building a validated state graph
Consider a document-processing workflow in which the number of requested results must be between one and ten.
The following example uses Pydantic to constrain the initial state.
from pydantic import BaseModel, Field, ValidationError
from langgraph.graph import StateGraph, START, END
class SearchState(BaseModel):
query: str = Field(min_length=3)
max_results: int = Field(default=3, ge=1, le=10)
results: list[str] = Field(default_factory=list)
def search(state: SearchState) -> dict:
results = [
f"Document {i + 1}: {state.query}"
for i in range(state.max_results)
]
return {"results": results}
builder = StateGraph(SearchState)
builder.add_node("search", search)
builder.add_edge(START, "search")
builder.add_edge("search", END)
graph = builder.compile()
result = graph.invoke({
"query": "LangGraph state",
"max_results": 2
})
print(result)
try:
graph.invoke({
"query": "LangGraph",
"max_results": 20
})
except ValidationError:
print("Invalid search request")Expected output:
{'query': 'LangGraph state', 'max_results': 2, 'results': ['Document 1: LangGraph state', 'Document 2: LangGraph state']}
Invalid search requestNotice two differences compared with TypedDict.
First, the node receives a Pydantic model and accesses fields using attribute notation:
state.query
state.max_resultsSecond, invalid input fails validation when the initial node’s model-shaped state is constructed.
Despite receiving an object, the node still returns a dictionary containing partial updates.
Understanding validation boundaries
Pydantic state is useful, but it should not be confused with a guarantee that every graph operation produces valid data.
LangGraph’s documented state validation guarantees are limited. Do not assume that every node update, channel merge, intermediate value, or final output is automatically validated simply because the overall state inherits from BaseModel.
In particular, a node returning a dictionary is not itself constructing a validated Pydantic model.
If a node produces critical business data, validate that data explicitly before returning it.
For example, an LLM-generated classification should be checked against a model defining the allowed categories and confidence range.
Similarly, if a public API requires validated output, validate the final result before returning it to the client.
Pydantic also performs type coercion by default for supported conversions. For example, some numeric strings can become integers. When coercion is undesirable, configure strict validation using ConfigDict(strict=True) or strict field settings.
Note: With the default
graph.invoke()output format, Pydantic and dataclass state graphs return dictionaries. The newerversion="v2"invocation format returns aGraphOutputwhose.valuecan be an instance of the declared output model or dataclass. All invocation examples in this lesson use the default dictionary-returning format.
Validating external input with a TypedDict graph
You do not have to use Pydantic as the entire graph state to benefit from runtime validation.
A particularly useful production pattern is to validate external requests using Pydantic, then pass the validated data into a lightweight TypedDict graph.
The following example demonstrates this combination.
from typing_extensions import TypedDict, NotRequired
from pydantic import BaseModel, ConfigDict, Field
from langgraph.graph import StateGraph, START, END
class Request(BaseModel):
model_config = ConfigDict(
strict=True,
extra="forbid"
)
question: str = Field(min_length=3, max_length=500)
class State(TypedDict):
question: str
answer: NotRequired[str]
def respond(state: State) -> dict:
return {
"answer": f"Received: {state['question']}"
}
graph = (
StateGraph(State)
.add_node("respond", respond)
.add_edge(START, "respond")
.add_edge("respond", END)
.compile()
)
raw_request = {"question": "What is graph state?"}
validated = Request.model_validate(raw_request)
result = graph.invoke(validated.model_dump())
print(result["answer"])Expected output:
Received: What is graph state?This design separates API validation from workflow execution.
It is especially useful when building REST services: Pydantic handles untrusted request payloads, while TypedDict provides an efficient internal state contract.
Dataclasses
What is a dataclass?
Python’s dataclasses module provides a convenient way to define classes primarily intended to hold data.
The @dataclass decorator automatically generates common methods, including an initializer and a readable object representation.
Dataclasses are part of Python’s standard library and do not require an additional dependency.
They occupy a useful middle ground between TypedDict and Pydantic:
- Like Pydantic, they provide attribute-based access.
- Like TypedDict, they do not automatically enforce type annotations.
- They support convenient default values and default factories.
Dataclasses are appropriate when you want structured state objects and sensible initialization without requiring extensive runtime validation.
Building a dataclass state graph
The following example creates a document review workflow with default review settings.
from dataclasses import dataclass, field
from langgraph.graph import StateGraph, START, END
@dataclass
class ReviewState:
document: str
review_mode: str = "standard"
findings: list[str] = field(default_factory=list)
reviewed: bool = False
def review(state: ReviewState) -> dict:
findings = []
if len(state.document.split()) < 10:
findings.append("Document is very short.")
if state.review_mode == "strict":
findings.append("Strict review completed.")
return {
"review_mode": state.review_mode,
"findings": findings,
"reviewed": True
}
graph = (
StateGraph(ReviewState)
.add_node("review", review)
.add_edge(START, "review")
.add_edge("review", END)
.compile()
)
result = graph.invoke({
"document": "This is a short document."
})
print(result)Expected output:
{'document': 'This is a short document.', 'review_mode': 'standard', 'findings': ['Document is very short.'], 'reviewed': True}The node accesses state using state.document and state.review_mode.
The dataclass supplies the default review mode when constructing the node’s state object.
The node explicitly returns review_mode so that the value is written into the graph’s channels and included in the resulting state.
This matters because a default available on a constructed state object should not automatically be treated as a guarantee that the corresponding channel has already been populated.
Mutable defaults
Lists and dictionaries require special care when defining dataclasses.
Avoid defining a list using a direct mutable default:
Instead, use field(default_factory=list), which creates a separate list for each dataclass instance.
The same principle applies to dictionaries using field(default_factory=dict).
Although dataclasses make initialization convenient, their defaults do not provide reducer behavior. Returning a new list to an ordinary state channel replaces the previous list rather than automatically appending to it.
Input and output schemas
Separating public interfaces from internal state
So far, our graphs have primarily used one schema for incoming data, internal processing, and returned results.
This works for small examples but becomes less appropriate as applications grow.
Imagine a retrieval-augmented generation workflow that accepts a question, retrieves documents, ranks them, constructs a prompt, and generates an answer.
The caller may need to provide only the question and receive only the answer. Retrieved documents, ranking information, and intermediate prompts are implementation details.
LangGraph allows these responsibilities to be separated using three schemas:
| Schema | Responsibility |
|---|---|
| Input schema | Describes the fields accepted from the caller. |
| Internal state schema | Describes the working information used during graph execution. |
| Output schema | Describes the fields exposed in the normal invocation result. |
This resembles designing a REST endpoint with separate request and response models instead of exposing the entire internal database representation.
The following diagram shows the separation between public interfaces and internal processing.
Implementing separate schemas
The following example simulates a knowledge base assistant using an internal collection of documents.
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
class InputState(TypedDict):
question: str
class OutputState(TypedDict):
answer: str
class OverallState(InputState):
documents: NotRequired[list[str]]
answer: NotRequired[str]
def retrieve(state: InputState) -> dict:
knowledge_base = {
"refund": "Refunds are processed within 7 business days.",
"shipping": "Standard shipping takes 3 business days."
}
question = state["question"].lower()
documents = [
text
for keyword, text in knowledge_base.items()
if keyword in question
]
return {"documents": documents}
def generate(state: OverallState) -> OutputState:
documents = state["documents"]
answer = (
documents[0]
if documents
else "No relevant information was found."
)
return {"answer": answer}
builder = StateGraph(
OverallState,
input_schema=InputState,
output_schema=OutputState
)
builder.add_node("retrieve", retrieve)
builder.add_node("generate", generate)
builder.add_edge(START, "retrieve")
builder.add_edge("retrieve", "generate")
builder.add_edge("generate", END)
graph = builder.compile()
result = graph.invoke({
"question": "How long does a refund take?"
})
print(result)
assert set(result.keys()) == {"answer"}Expected output:
{'answer': 'Refunds are processed within 7 business days.'}The graph maintains question, documents, and answer internally. However, only answer appears in the final invocation result.
Notice that the retrieve node accepts InputState but writes to documents, which belongs to the broader internal schema.
A node’s input schema controls which state channels it reads. It does not restrict its writes exclusively to those same channels.
Why this separation matters
Explicit interfaces reduce coupling between the graph and its consumers.
You can change the retrieval strategy, introduce ranking information, or add intermediate evaluation results without changing the caller’s response contract.
However, schema selection is not equivalent to strict request validation. TypedDict schemas do not guarantee that malformed input is rejected or that every required output field is populated.
Use Pydantic or explicit validation when enforcing those guarantees is necessary.
Private state channels
What are private channels?
Sometimes information is needed only by a small number of nodes.
For example, a classification node might calculate an internal routing code that the next node consumes. Other nodes have no reason to access this value, and the caller should not receive it.
LangGraph supports declaring additional channels through node-specific schemas.
Unlike an ordinary internal field declared in the overall schema, a private channel can be introduced using a separate schema that is referenced by participating nodes.
This helps establish focused data contracts between individual workflow stages.
Passing private information between nodes
The following example creates an internal routing code without including that field in the graph’s overall schema.
from typing import Literal
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
class InputState(TypedDict):
message: str
class OutputState(TypedDict):
response: str
class OverallState(InputState):
response: NotRequired[str]
class PrivateState(TypedDict):
routing_code: Literal["BILLING", "GENERAL"]
def classify(state: InputState) -> PrivateState:
code = (
"BILLING"
if "invoice" in state["message"].lower()
else "GENERAL"
)
return {"routing_code": code}
def respond(state: PrivateState) -> OutputState:
if state["routing_code"] == "BILLING":
return {"response": "Contact our billing team."}
return {"response": "Contact our general support team."}
builder = StateGraph(
OverallState,
input_schema=InputState,
output_schema=OutputState
)
builder.add_node("classify", classify)
builder.add_node("respond", respond)
builder.add_edge(START, "classify")
builder.add_edge("classify", "respond")
builder.add_edge("respond", END)
graph = builder.compile()
result = graph.invoke({
"message": "Please explain my invoice."
})
print(result)
assert "routing_code" not in resultExpected output:
{'response': 'Contact our billing team.'}During graph construction, LangGraph discovers the additional channel through the receiving node’s annotated input schema.
The classification node writes routing_code, and the response node reads it through PrivateState.
The private field is not included in the public input or output schema.
Private does not mean secret
Private state channels establish logical separation, not a security boundary.
Although the normal invocation result excludes routing_code, that information may still be visible through graph streaming, tracing, debugging, checkpoint inspection, or administrative interfaces.
Using the previous compiled graph, inspect its streamed state:
for chunk in graph.stream(
{"message": "Please explain my invoice."},
stream_mode="values",
version="v2"
):
snapshot = chunk["data"]
if "routing_code" in snapshot:
print("Internal channel:", snapshot["routing_code"])Expected output includes:
Internal channel: BILLINGThe private value is accessible because values streaming exposes internal state by default.
To restrict values streaming to specific public channels, use an explicit allowlist:
for chunk in graph.stream(
{"message": "Please explain my invoice."},
stream_mode="values",
output_keys=["response"],
version="v2"
):
print(chunk["data"])The relevant emitted result contains only the response channel.
This filtering does not automatically change what is recorded in checkpoints, traces, or other streaming modes.
Never use private state channels as a place to hide API keys, passwords, database credentials, or other secrets. Keep those in appropriate secret-management systems and supply necessary execution dependencies through runtime context.
Which should I use?
Comparing the three schema styles
There is no universally superior schema style. The correct choice depends on validation requirements, performance considerations, and the architecture of your application.
| Feature | TypedDict | Pydantic | Dataclass |
|---|---|---|---|
| Python representation | Dictionary | Model instance | Class instance |
| Node field access | state["field"] |
state.field |
state.field |
| Static type information | Yes | Yes | Yes |
| Automatic model validation | No | Yes | No |
| Built-in field defaults | No | Yes | Yes |
| Nested validation | No | Yes | No |
| Custom validators | Manual | Built-in support | Manual |
| Relative overhead | Low | Higher | Low |
| Suitable for most graphs | Yes | When validation is needed | When defaults are useful |
Supported custom state style for create_agent |
Yes | No | No |
All three styles support the LangGraph Graph API and explicit partial state updates.
The higher-level LangChain create_agent API uses TypedDict-based custom agent state schemas, which is another reason to become comfortable with TypedDict early.
Practical selection guidelines
Choose TypedDict for most workflows, especially conversational agents, tool-calling systems, retrieval pipelines, and applications where runtime validation occurs at external boundaries.
Choose Pydantic when the workflow benefits from constrained fields, structured nested objects, or explicit validation rules. Consider the cost of repeated model construction when designing graphs with many execution steps.
Choose dataclasses when attribute access and default values improve readability, but automatic validation is unnecessary.
For larger applications, combining these approaches is often more effective than committing to one everywhere. A service can use Pydantic for incoming requests, TypedDict for internal graph state, and dataclasses for runtime configuration.
Common schema design mistakes
Several mistakes become increasingly expensive as graphs grow:
- Creating an oversized state schema: Avoid storing unrelated configuration, service clients, or temporary objects in shared workflow state.
- Assuming annotations enforce types: TypedDict and dataclass annotations do not provide automatic runtime validation.
- Reading fields before initialization: Ensure that producer nodes execute before consumer nodes access their fields.
- Returning the entire state unnecessarily: Return the fields a node intentionally changes.
- Exposing internal data: Use explicit output schemas instead of returning every intermediate channel.
- Assuming private means secure: Review checkpoint, tracing, and streaming behavior before handling sensitive information.
- Ignoring schema evolution: Changing field names or types can affect previously persisted graph state.
When building production workflows, prefer clearly named channels, small data contracts, explicit validation boundaries, and deterministic tests that verify both expected results and output field exposure.
For API details and version-specific behavior, consult the official LangGraph Graph API reference, state schema documentation, and streaming documentation.
Preparing for the conversational application project
The hands-on project for this chapter is a stateful conversational application.
Its eventual state will need to represent conversation history, the current request, assistant responses, and potentially additional information such as conversation summaries or detected user preferences.
TypedDict provides a natural foundation for this design. Later, you will use LangGraph’s specialized MessagesState schema to simplify conversation history management.
However, defining a conversation history field as list is not sufficient. When a new message arrives, the workflow must determine whether to replace the existing list or merge the new message into it.
That behavior belongs to the state channel’s update rules rather than to its ordinary Python type.
In the next lesson, Reducers and Annotated types, you will learn how to attach custom update behavior to individual state fields, preserve accumulated information, and handle updates from multiple nodes. Those mechanisms transform a basic typed workflow into the foundation of a genuinely stateful agent.
Build a Customer Support State Schema
Build a customer support workflow using TypedDict with separate input, output, and internal state schemas. Create three nodes that normalize a customer message, classify its intent using a private state channel, and generate an appropriate response. Ensure that the final graph output contains only the response and does not expose internal classification data. Test the workflow with billing and technical support requests.
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
# TODO: Define InputState with a customer_message field.
# TODO: Define OutputState with a response field.
# TODO: Define OverallState with input, output,
# and normalized_message fields.
# TODO: Define PrivateState with an intent field.
def normalize_message(state):
# TODO: Strip whitespace and convert to lowercase.
raise NotImplementedError
def classify_intent(state):
# TODO: Return billing, technical, or general intent.
raise NotImplementedError
def generate_response(state):
# TODO: Generate a response based on the private intent.
raise NotImplementedError
# TODO: Construct StateGraph with input and output schemas.
# TODO: Register the three nodes with appropriate type hints.
# TODO: Connect START, the nodes, and END.
# TODO: Compile and invoke the graph.
# Test inputs:
# {"customer_message": " I have a BILLING question "}
# {"customer_message": "My application has an error"}
# Verify that the result contains only the response field.from typing import Literal
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
class InputState(TypedDict):
customer_message: str
class OutputState(TypedDict):
response: str
class OverallState(InputState):
normalized_message: NotRequired[str]
response: NotRequired[str]
class PrivateState(TypedDict):
intent: Literal["billing", "technical", "general"]
def normalize_message(state: InputState) -> dict:
return {
"normalized_message":
state["customer_message"].strip().lower()
}
def classify_intent(state: OverallState) -> PrivateState:
message = state["normalized_message"]
if any(word in message for word in ("billing", "invoice", "payment")):
return {"intent": "billing"}
if any(word in message for word in ("error", "bug", "crash")):
return {"intent": "technical"}
return {"intent": "general"}
def generate_response(state: PrivateState) -> OutputState:
responses = {
"billing": "Our billing team can help with your request.",
"technical": "Our technical team can investigate your issue.",
"general": "How can our support team assist you?",
}
return {"response": responses[state["intent"]]}
builder = StateGraph(
OverallState,
input_schema=InputState,
output_schema=OutputState,
)
builder.add_node("normalize", normalize_message)
builder.add_node("classify", classify_intent)
builder.add_node("respond", generate_response)
builder.add_edge(START, "normalize")
builder.add_edge("normalize", "classify")
builder.add_edge("classify", "respond")
builder.add_edge("respond", END)
graph = builder.compile()
billing_result = graph.invoke({
"customer_message": " I have a BILLING question "
})
technical_result = graph.invoke({
"customer_message": "My application has an error"
})
general_result = graph.invoke({
"customer_message": "What services do you offer?"
})
print(billing_result)
print(technical_result)
print(general_result)
assert billing_result == {
"response": "Our billing team can help with your request."
}
assert technical_result == {
"response": "Our technical team can investigate your issue."
}
assert general_result == {
"response": "How can our support team assist you?"
}
for result in (billing_result, technical_result, general_result):
assert set(result.keys()) == {"response"}
print("All tests passed.")Summary
- A state schema defines the named data channels that a LangGraph workflow uses to communicate between nodes.
- TypedDict is a lightweight schema style that provides static type information without automatic runtime validation.
- Pydantic models provide runtime validation and data constraints but introduce additional processing overhead.
- Dataclasses provide attribute-based access, default values, and convenient initialization without automatic type validation.
- Nodes should return partial state updates rather than directly modifying the state they receive.
- Separate input and output schemas establish a public interface independent of the graph's internal implementation.
- Private state channels restrict normal data exposure but do not automatically protect information from checkpoints, streams, or traces.