Implementation:Langchain ai Langgraph StateGraph Init
| Metadata | Value |
|---|---|
| Type | Implementation (API Doc) |
| Library | langgraph |
| Source File | libs/langgraph/langgraph/graph/state.py
|
| Lines | L112-250 (class definition and __init__)
|
| Workflow | Building_a_Stateful_Graph |
Overview
StateGraph.__init__ creates a new graph builder instance from a state schema. It registers internal channels for each schema field, initializes data structures for nodes and edges, and optionally accepts separate input, output, and context schemas to control the graph's external interface.
Description
StateGraph is a generic class parameterized by StateT, ContextT, InputT, and OutputT. The constructor:
- Accepts a
state_schema(required) which must be a type -- typically aTypedDictor PydanticBaseModel. - Accepts optional
context_schema,input_schema, andoutput_schema. Ifinput_schemaoroutput_schemaare not provided, they default to thestate_schema. - Calls
_add_schema()for each schema to extract channels and managed values from type annotations. - Initializes empty collections:
nodes(dict),edges(set),branches(defaultdict),channels(dict),managed(dict),schemas(dict), andwaiting_edges(set). - Sets
compiled = Falseto indicate the graph has not yet been compiled.
The class also supports a deprecated config_schema keyword that maps to context_schema for backward compatibility.
Usage
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph
import operator
class State(TypedDict):
x: Annotated[list, operator.add]
# Minimal instantiation
builder = StateGraph(State)
# With all optional schemas
class Input(TypedDict):
x: list
class Output(TypedDict):
x: list
class Context(TypedDict):
r: float
builder = StateGraph(
state_schema=State,
context_schema=Context,
input_schema=Input,
output_schema=Output,
)
Code Reference
Source Location
| Item | Path | Lines |
|---|---|---|
StateGraph class |
libs/langgraph/langgraph/graph/state.py |
L112-1153 |
__init__ |
libs/langgraph/langgraph/graph/state.py |
L197-249 |
Signature
class StateGraph(Generic[StateT, ContextT, InputT, OutputT]):
def __init__(
self,
state_schema: type[StateT],
context_schema: type[ContextT] | None = None,
*,
input_schema: type[InputT] | None = None,
output_schema: type[OutputT] | None = None,
) -> None:
Import
from langgraph.graph import StateGraph
I/O Contract
| Parameter | Type | Default | Description |
|---|---|---|---|
state_schema |
type[StateT] |
required | The primary state schema class. Must be a type with annotations (e.g., TypedDict, BaseModel).
|
context_schema |
None | None |
Optional schema defining immutable runtime context available to all nodes. |
input_schema |
None | None |
Optional schema defining what callers provide as input. Defaults to state_schema.
|
output_schema |
None | None |
Optional schema defining what the graph returns as output. Defaults to state_schema.
|
Returns: A new StateGraph instance (the builder), ready to receive node and edge registrations.
Raises:
ValueError-- If managed channels are found ininput_schemaoroutput_schema(managed channels are only permitted in the state schema).
Usage Examples
Simple State Schema
from typing_extensions import TypedDict
from langgraph.graph import StateGraph
class State(TypedDict):
count: int
name: str
builder = StateGraph(State)
# builder.nodes == {}
# builder.edges == set()
# builder.compiled == False
Using MessagesState
from langgraph.graph import StateGraph, MessagesState
builder = StateGraph(MessagesState)
# State has a single field: messages: Annotated[list[AnyMessage], add_messages]
Separate Input and Output
from typing_extensions import TypedDict
from langgraph.graph import StateGraph
class FullState(TypedDict):
query: str
documents: list
answer: str
class InputOnly(TypedDict):
query: str
class OutputOnly(TypedDict):
answer: str
builder = StateGraph(
FullState,
input_schema=InputOnly,
output_schema=OutputOnly,
)
# Callers provide {"query": "..."} and receive {"answer": "..."}
With Context Schema
from typing_extensions import TypedDict
from langgraph.graph import StateGraph
class State(TypedDict):
x: int
class Context(TypedDict):
multiplier: float
builder = StateGraph(State, context_schema=Context)
# Nodes can access runtime.context["multiplier"] during execution