Add a new node to the StateGraph.
add_node(
self,
node: str | StateNode[NodeInputT, ContextT],
action: StateNode[NodeInputT, ContextT] | None = None,
*,
defer: bool = False,
metadata: dict[str, Any] | None = None,
input_schema: type[NodeInputT] | None = None,
retry_policy: RetryPolicy | Sequence[RetryPolicy] | None = None,
cache_policy: CachePolicy | None = None,
destinations: dict[str, str] | tuple[str, ...] | None = None,
**kwargs: Unpack[DeprecatedKwargs] = {}
) -> SelfExample:
from typing_extensions import TypedDict
from langchain_core.runnables import RunnableConfig
from langgraph.graph import START, StateGraph
class State(TypedDict):
x: int
def my_node(state: State, config: RunnableConfig) -> State:
return {"x": state["x"] + 1}
builder = StateGraph(State)
builder.add_node(my_node) # node name will be 'my_node'
builder.add_edge(START, "my_node")
graph = builder.compile()
graph.invoke({"x": 1})
# {'x': 2}
Customize the name::
builder = StateGraph(State)
builder.add_node("my_fair_node", my_node)
builder.add_edge(START, "my_fair_node")
graph = builder.compile()
graph.invoke({"x": 1})
# {'x': 2}| Name | Type | Description |
|---|---|---|
node* | str | StateNode[NodeInputT, ContextT] | The function or runnable this node will run. If a string is provided, it will be used as the node name, and action will be used as the function or runnable. |
action | StateNode[NodeInputT, ContextT] | None | Default: NoneThe action associated with the node. Will be used as the node function or runnable if |
defer | bool | Default: FalseWhether to defer the execution of the node until the run is about to end. |
metadata | dict[str, Any] | None | Default: NoneThe metadata associated with the node. |
input_schema | type[NodeInputT] | None | Default: NoneThe input schema for the node. (Default: the graph's state schema) |
retry_policy | RetryPolicy | Sequence[RetryPolicy] | None | Default: NoneThe retry policy for the node. If a sequence is provided, the first matching policy will be applied. |
cache_policy | CachePolicy | None | Default: NoneThe cache policy for the node. |
destinations | dict[str, str] | tuple[str, ...] | None | Default: NoneDestinations that indicate where a node can route to. Useful for edgeless graphs with nodes that return If a If a Warning This is only used for graph rendering and doesn't have any effect on the graph execution. |