| Name | Type | Description |
|---|---|---|
state_schema* | type[StateT] | The schema class that defines the state. |
context_schema | type[ContextT] | None | Default: NoneThe schema class that defines the runtime context. Use this to expose immutable context data to your nodes, like |
input_schema | type[InputT] | None | Default: None |
output_schema | type[OutputT] | None | Default: None |
A graph whose nodes communicate by reading and writing to a shared state.
The signature of each node is State -> Partial<State>.
Each state key can optionally be annotated with a reducer function that
will be used to aggregate the values of that key received from multiple nodes.
The signature of a reducer function is (Value, Value) -> Value.
StateGraph is a builder class and cannot be used directly for execution.
You must first call .compile() to create an executable graph that supports
methods like invoke(), stream(), astream(), and ainvoke(). See the
CompiledStateGraph documentation for more details.
The config_schema parameter is deprecated in v0.6.0 and support will be removed in v2.0.0.
Please use context_schema instead to specify the schema for run-scoped context.
Example:
from langchain_core.runnables import RunnableConfig
from typing_extensions import Annotated, TypedDict
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import StateGraph
from langgraph.runtime import Runtime
def reducer(a: list, b: int | None) -> list:
if b is not None:
return a + [b]
return a
class State(TypedDict):
x: Annotated[list, reducer]
class Context(TypedDict):
r: float
graph = StateGraph(state_schema=State, context_schema=Context)
def node(state: State, runtime: Runtime[Context]) -> dict:
r = runtime.context.get("r", 1.0)
x = state["x"][-1]
next_value = x * r * (1 - x)
return {"x": next_value}
graph.add_node("A", node)
graph.set_entry_point("A")
graph.set_finish_point("A")
compiled = graph.compile()
step1 = compiled.invoke({"x": 0.5}, context={"r": 3.0})
# {'x': [0.5, 0.75]}The schema class that defines the input to the graph.
The schema class that defines the output from the graph.