Command, Send & control flow — API reference
The Command and Send primitives let a node update state, jump to another node, and fan out to many parallel node instances in a single return value — plus Command.PARENT for cross-subgraph routing.
Verified against langgraph==1.2.22 (module: langgraph.types).
LangGraph’s control flow primitives live in langgraph.types:
| Symbol | Purpose |
|---|---|
Command(update, goto, resume, graph) | Update state and/or jump to another node and/or resume an interrupt — all in one return value from a node. |
Send(node, arg) | Dispatch a node with custom state; used from conditional edges for fan-out and from Command.goto for dynamic routing. |
interrupt(value, *, response_schema=None) | Pause the current task and surface value to the client (resume with Command(resume=...)). |
Overwrite(value) | Write directly to a reducing channel, bypassing the reducer. |
Interrupt(value, id, response_schema) | The dataclass surfaced inside StateSnapshot.interrupts and GraphOutput.interrupts (older attributes ns, when, resumable were removed in v0.6). |
Minimal runnable example
Section titled “Minimal runnable example”from typing import Literalfrom typing_extensions import TypedDictfrom langgraph.graph import StateGraph, START, ENDfrom langgraph.types import Command
class State(TypedDict): messages: list[str] next: str
def planner(state: State) -> Command[Literal["writer", "critic", "__end__"]]: if len(state["messages"]) >= 3: return Command(goto=END) if state["messages"] and state["messages"][-1].startswith("draft"): return Command(update={"next": "critique"}, goto="critic") return Command(update={"next": "write"}, goto="writer")
def writer(state: State) -> Command[Literal["planner"]]: return Command(update={"messages": state["messages"] + ["draft v1"]}, goto="planner")
def critic(state: State) -> Command[Literal["planner"]]: return Command(update={"messages": state["messages"] + ["critique"]}, goto="planner")
builder = StateGraph(State)builder.add_node("planner", planner)builder.add_node("writer", writer)builder.add_node("critic", critic)builder.add_edge(START, "planner")
graph = builder.compile()print(graph.invoke({"messages": [], "next": ""}))# {'messages': ['draft v1', 'critique', 'draft v1'], 'next': 'write'}Notes:
- No
add_edgefromplannertowriter/critic/END— the node returnsCommand(goto=...). Declaringdestinations=("writer", "critic", END)onadd_nodeadds the same edges to the diagram. - Type-hinting the return as
Command[Literal["writer", "critic", "__end__"]]keeps the Mermaid visualization accurate.
Command in full
Section titled “Command in full”@dataclass(frozen=True, kw_only=True, slots=True)class Command(Generic[N], ToolOutputMixin): graph: str | None = None # target graph ("__parent__" for Command.PARENT) update: Any | None = None # state update (dict, dataclass, Pydantic, tuple list, scalar) resume: dict[str, Any] | Any | None = None goto: Send | Sequence[Send | N] | N = () PARENT: ClassVar[Literal["__parent__"]] = "__parent__"Any subset of update, resume, goto, graph can be set. When a node returns Command(update={...}) without goto, it behaves like returning a dict — the graph’s edges decide where to go next.
update
Section titled “update”update accepts the same shapes as a normal node return:
dict— keys are channel names.- A list of
(channel, value)tuples. - A Pydantic model / dataclass matching the state schema.
- A scalar — written to the
__root__channel when the state has a root channel.
Reducers apply as usual; wrap a value in Overwrite(...) to bypass them.
Command(goto="next_node") # singleCommand(goto=["fan_out_a", "fan_out_b"]) # multiple (unrelated to Send fan-out)Command(goto=Send("worker", {"item": x})) # dispatch a node with custom inputCommand(goto=[Send("w", {"i": i}) for i in xs]) # fan-out with SendsSpecial values:
END→ terminate this execution path.- A node name not in the graph does not raise: in 1.2.22 the write is dropped with a logged warning (
wrote to unknown channel branch:to:<name>, ignoring it) and that path simply ends. Declaring the targets withdestinations=or aCommand[Literal[...]]return type makescompile()check them. - Mixing
Sendand plain names in the same list is allowed.
resume
Section titled “resume”Used to resume from an interrupt(). Two shapes:
Command(resume="a single value") # next interrupt gets this valueCommand(resume={"interrupt-id-1": "v1", "interrupt-id-2": "v2"})# address by interrupt idSee the interrupt() section below.
graph / Command.PARENT
Section titled “graph / Command.PARENT”Command(graph=Command.PARENT, goto="retry", update={"reason": "timeout"})From inside a subgraph node, this routes the command to the parent graph — useful for bubbling an error or a handoff signal up to a supervisor.
class Send: node: str arg: Any timeout: TimeoutPolicy | None # added in 1.2.0
def __init__( self, /, node: str, arg: Any, *, timeout: float | timedelta | TimeoutPolicy | None = None, ) -> None: self.node = node self.arg = arg self.timeout = TimeoutPolicy.coerce(timeout) # normalised to TimeoutPolicy | NoneSend packages a node name and a custom state payload. Two places accept it:
- Conditional edges: return one or more
Sends from thepathcallable. Command.goto: returnCommand(goto=Send("worker", {...}))from a node.
The receiving node runs with the provided arg as its state snapshot for this task. The node is a concrete named node; the sent state can be any subset of the node’s input schema.
Equality is structural (node + arg + timeout). hash(Send(...)) hashes the arg too, so a Send whose arg is a dict is not hashable (TypeError); keep Sends in lists, not sets.
Per-task timeout on Send
Section titled “Per-task timeout on Send”The timeout parameter overrides the target node’s default timeout for this specific dispatched task. Pass a float (seconds), timedelta, or TimeoutPolicy directly. Timeouts use cooperative asyncio cancellation, so the target node must be async def (a sync target raises ValueError: Node timeouts are only supported for async nodes), and a branch that overruns raises NodeTimeoutError, which the node’s retry_policy retries by default. (A node error_handler does not catch failures in parallel Send tasks; see Error handlers.)
import operatorfrom datetime import timedeltafrom typing import Annotatedfrom typing_extensions import TypedDictfrom langgraph.graph import StateGraph, START, ENDfrom langgraph.types import Send, TimeoutPolicy
class BatchState(TypedDict): jobs: list[dict] results: Annotated[list[str], operator.add]
class JobState(TypedDict): id: str payload: str priority: str
def dispatch(state: BatchState) -> list[Send]: """Fan-out jobs; high-priority jobs get a 10-second hard cap, normal gets 60.""" sends = [] for job in state["jobs"]: timeout = ( 10.0 # high-priority: 10 s hard cap if job["priority"] == "high" else timedelta(seconds=60) # normal: 60 s hard cap ) sends.append(Send("run_job", job, timeout=timeout)) return sends
async def run_job(state: JobState) -> dict: return {"results": [f"done:{state['id']}"]}
builder = StateGraph(BatchState)builder.add_node("run_job", run_job)builder.add_conditional_edges(START, dispatch)builder.add_edge("run_job", END)graph = builder.compile()# await graph.ainvoke({"jobs": [...], "results": []})For fine-grained control (both run and idle caps), pass a TimeoutPolicy:
sends = [ Send( "expensive_node", {"item": item}, timeout=TimeoutPolicy(run_timeout=60.0, idle_timeout=10.0), ) for item in items]interrupt()
Section titled “interrupt()”from langgraph.types import interrupt, Command
def ask(state: State) -> dict: answer = interrupt({"question": "How old are you?"}) return {"age": int(answer)}Semantics:
- First execution inside a node raises a
GraphInterruptcontaining anInterrupt(value, id). The graph pauses; theInterruptshows up inStateSnapshot.interruptsand in the__interrupt__key emitted onstream_mode="updates". - The client resumes with
graph.invoke(Command(resume="42"), cfg). The node re-runs from the top, this timeinterrupt(...)returns"42". - Multiple
interrupt()calls in one node are matched by order in the current task. Resume values scope to the task, not the graph. - A checkpointer is required to resume. Without one,
invokestops at the interrupt and returns the state with an__interrupt__key, andCommand(resume=...)then raisesRuntimeError: Cannot use Command(resume=...) without checkpointer.
Resume by id when several tasks are paused at once (for example, parallel nodes that each call interrupt()):
from langgraph.types import Commandcfg = {"configurable": {"thread_id": "t"}}pending = graph.get_state(cfg).interrupts # one Interrupt per paused taskgraph.invoke(Command(resume={i.id: "yes" for i in pending}), cfg)With more than one interrupt pending, a non-mapping resume value raises RuntimeError: When there are multiple pending interrupts, you must specify the interrupt id when resuming. Since 1.2.20 each interrupt() call has its own id, and when one node calls interrupt() several times the graph pauses at each call in turn, so you resume them in order. Chapter 7 has a runnable example.
Checkpoint history is not a complete interrupt audit log. Repeated
interrupt()calls in one node reuse the same task slot, soget_state_history()only shows the interrupts each snapshot retained. If you need every interrupt that ever fired, record the__interrupt__events as you stream.
Typed resume values: response_schema
Section titled “Typed resume values: response_schema”interrupt(value, *, response_schema=...) tells the client what shape the resume value should take. It accepts two kinds of schema:
- A JSON Schema
dict: metadata only. It is surfaced to callers, but the resume value is returned as-is with no validation. - A Python type (Pydantic model,
TypedDict, or dataclass): LangGraph validates the resume value with a pydanticTypeAdapter, raisespydantic.ValidationErroron a mismatch, and returns the constructed instance. Type checkers also infer the return type from it.
Either way, the Interrupt stored in the snapshot carries response_schema as a JSON Schema dict, so it serialises with any checkpointer.
from pydantic import BaseModelfrom typing_extensions import TypedDictfrom langgraph.checkpoint.memory import InMemorySaverfrom langgraph.graph import START, END, StateGraphfrom langgraph.types import Command, interrupt
class Decision(BaseModel): action: str reason: str
class State(TypedDict): proposal: str decision: dict | None
def review(state: State) -> dict: decision = interrupt({"proposal": state["proposal"]}, response_schema=Decision) return {"decision": decision.model_dump()} # decision is a Decision instance
graph = ( StateGraph(State) .add_node("review", review) .add_edge(START, "review") .add_edge("review", END) .compile(checkpointer=InMemorySaver()))cfg = {"configurable": {"thread_id": "typed-interrupt"}}
out = graph.invoke({"proposal": "Deploy to prod", "decision": None}, cfg, version="v2")print(out.interrupts[0].response_schema) # {'properties': {...}, 'required': ['action', 'reason'], ...}
graph.invoke(Command(resume={"action": "approve", "reason": "All checks passed."}), cfg)# Resuming with {"action": "approve"} alone would raise pydantic.ValidationError.Interrupt dataclass
Section titled “Interrupt dataclass”@final@dataclass(init=False, slots=True)class Interrupt(Generic[ResponseT]): value: Any id: str response_schema: type[ResponseT] | dict[str, Any] | None = NoneA surfaced interrupt always carries response_schema as JSON Schema (or None). The deprecated interrupt_id property still exists but warns; use id. ns, when, and resumable were removed in v0.6; use StateSnapshot.interrupts for structural info.
Overwrite
Section titled “Overwrite”Writes a value to a reducing channel without applying the reducer:
import operatorfrom typing import Annotatedfrom typing_extensions import TypedDictfrom langgraph.types import Overwrite
class S(TypedDict): items: Annotated[list[str], operator.add]
def reset(state: S) -> dict: return {"items": Overwrite(["start-over"])}Two Overwrites for the same channel in one super-step raise InvalidUpdateError.
Patterns
Section titled “Patterns”1. Map-reduce with Send
Section titled “1. Map-reduce with Send”from langgraph.types import Send
def dispatch(state: dict) -> list[Send]: return [Send("score", {"item": x}) for x in state["items"]]
builder.add_node("score", score_fn)builder.add_conditional_edges("dispatch", dispatch)builder.add_edge("score", "aggregate") # aggregate runs once, after every score task in the stepscore runs once per item with its own state snapshot. Use a reducer on the downstream channel (e.g., Annotated[list, operator.add]) so results concatenate.
2. Supervisor routing without edges
Section titled “2. Supervisor routing without edges”from typing import Literalfrom langgraph.types import Command
def supervisor(state: dict) -> Command[Literal["researcher", "writer", "__end__"]]: if not state.get("notes"): return Command(goto="researcher") if not state.get("draft"): return Command(goto="writer", update={"phase": "drafting"}) return Command(goto=END)
builder.add_node("supervisor", supervisor, destinations=("researcher", "writer", END))destinations= feeds the diagram only; the supervisor’s typed return drives execution.
3. Subgraph bubbling to parent
Section titled “3. Subgraph bubbling to parent”def worker(state: dict) -> Command: if state["escalate"]: return Command( graph=Command.PARENT, goto="human_review", update={"reason": state["reason"]}, ) return Command(update={"done": True})Inside a compiled subgraph worker can hand control back to the parent graph’s human_review node while carrying state.
4. Tool-authored commands
Section titled “4. Tool-authored commands”Any @tool that returns a Command is treated as control flow by ToolNode. The update must include a ToolMessage answering the tool call, or ToolNode raises ValueError: Expected to have a matching ToolMessage in Command.update. Inject the call id with InjectedToolCallId:
from typing import Annotatedfrom langchain_core.messages import ToolMessagefrom langchain_core.tools import InjectedToolCallId, toolfrom langgraph.types import Command
@tooldef transfer_to_refunds( reason: str, tool_call_id: Annotated[str, InjectedToolCallId], # hidden from the LLM) -> Command: """Hand this conversation to the refunds agent.""" return Command( goto="refunds_agent", update={ "transfer_reason": reason, "messages": [ToolMessage("Transferring to refunds.", tool_call_id=tool_call_id)], }, )ToolNode unpacks the Command into a state update plus goto, so the graph jumps to refunds_agent straight from the tools node.
5. Interrupt + resume + update
Section titled “5. Interrupt + resume + update”from langgraph.types import interrupt, Command
def approve(state): decision = interrupt({"approve?": state["proposal"]}) if decision == "yes": return Command(goto="execute", update={"approved_by": "human"}) return Command(goto="cancel")
# Client:graph.stream(initial, cfg) # emits __interrupt__graph.invoke(Command(resume="yes"), cfg) # continues into "execute"6. Send with a per-task timeout
Section titled “6. Send with a per-task timeout”Pass a timeout= to Send to cap how long an individual parallel task may run. A plain float is a hard wall-clock limit (run_timeout); pass a TimeoutPolicy for idle-based cancellation.
import asyncioimport operatorfrom typing import Annotatedfrom typing_extensions import TypedDictfrom langgraph.errors import NodeTimeoutErrorfrom langgraph.graph import StateGraph, START, ENDfrom langgraph.types import Send, RetryPolicy
class Scrape(TypedDict): urls: list[str] results: Annotated[list[str], operator.add]
async def scrape_page(state: dict) -> dict: """Scrape one URL — runs per-Send with its own timeout (async: timeouts need it).""" await asyncio.sleep(0.05) # real HTTP fetch here return {"results": [f"content:{state['url']}"]}
def dispatch(state: Scrape) -> list[Send]: return [ Send( "scrape_page", {"url": url, "results": []}, # Each individual task gets 10 s wall-clock; retry up to 2 extra times timeout=10.0, ) for url in state["urls"] ]
builder = StateGraph(Scrape)builder.add_node( "scrape_page", scrape_page, retry_policy=RetryPolicy(max_attempts=3, retry_on=NodeTimeoutError), # not the built-in TimeoutError)builder.add_conditional_edges(START, dispatch)builder.add_edge("scrape_page", END)
graph = builder.compile()result = asyncio.run(graph.ainvoke({"urls": ["https://a.com", "https://b.com"], "results": []}))print(result["results"]) # ['content:https://a.com', 'content:https://b.com']7. Complete multi-agent handoff with Command.PARENT
Section titled “7. Complete multi-agent handoff with Command.PARENT”A supervisor graph runs two specialised subgraphs. Each subgraph can escalate back to the supervisor using Command(graph=Command.PARENT, goto="supervisor").
import operatorfrom typing import Annotated, Literalfrom typing_extensions import TypedDictfrom langgraph.graph import StateGraph, START, ENDfrom langgraph.types import Commandfrom langgraph.checkpoint.memory import InMemorySaver
# ── Shared state used by both the parent and subgraphs ──────────────────────
class SharedState(TypedDict): task: str output: str escalated: bool
# ── Subgraph A: researcher ──────────────────────────────────────────────────
def researcher_node(state: SharedState) -> Command[Literal["__end__"]]: # Simulate research; escalate if topic is too complex if "complex" in state["task"]: return Command( graph=Command.PARENT, # send to the parent supervisor goto="supervisor", update={"escalated": True, "output": "Research: escalated — topic too complex"}, ) return Command( update={"output": f"Research done: {state['task']}"}, goto=END, )
researcher = ( StateGraph(SharedState) .add_node("researcher_node", researcher_node, destinations=["__end__"]) .add_edge(START, "researcher_node") .compile())
# ── Subgraph B: writer ──────────────────────────────────────────────────────
def writer_node(state: SharedState) -> dict: return {"output": f"Draft written for: {state['task']}"}
writer = ( StateGraph(SharedState) .add_node("writer_node", writer_node) .add_edge(START, "writer_node") .add_edge("writer_node", END) .compile())
# ── Parent supervisor ───────────────────────────────────────────────────────
class SupervisorState(SharedState): phase: str
def supervisor(state: SupervisorState) -> Command[Literal["researcher", "writer", "__end__"]]: if state.get("escalated"): # Researcher escalated — handle manually and finish return Command( update={"output": "Supervisor resolved escalation.", "phase": "done"}, goto=END, ) if state["phase"] == "start": return Command(update={"phase": "research"}, goto="researcher") if state["phase"] == "research": return Command(update={"phase": "write"}, goto="writer") return Command(goto=END)
parent = StateGraph(SupervisorState)parent.add_node("supervisor", supervisor, destinations=["researcher", "writer", "__end__"])parent.add_node("researcher", researcher)parent.add_node("writer", writer)parent.add_edge(START, "supervisor")parent.add_edge("researcher", "supervisor") # report back after each subgraph finishesparent.add_edge("writer", "supervisor")
graph = parent.compile(checkpointer=InMemorySaver())cfg = {"configurable": {"thread_id": "multi-1"}}
# Normal taskresult = graph.invoke({"task": "Write about LangGraph", "output": "", "escalated": False, "phase": "start"}, cfg)print(result["output"]) # "Draft written for: Write about LangGraph"
# Complex task triggers escalation from researcher → parent supervisorcfg2 = {"configurable": {"thread_id": "multi-2"}}result2 = graph.invoke({"task": "complex quantum theory", "output": "", "escalated": False, "phase": "start"}, cfg2)print(result2["output"]) # "Supervisor resolved escalation."8. Nested fan-out: a Send target that fans out again
Section titled “8. Nested fan-out: a Send target that fans out again”Conditional-edge functions always receive the root graph state, not the payload of the Send that started the branch. To fan out a second level from branch-local data, do it inside the node and return Command(goto=[Send(...), ...]):
import operatorfrom typing import Annotatedfrom typing_extensions import TypedDictfrom langgraph.graph import START, END, StateGraphfrom langgraph.types import Command, Send
class RootState(TypedDict): sections: list[str] chunks: Annotated[list[str], operator.add]
class SectionState(TypedDict): section: str
class ChunkState(TypedDict): chunk: str
def section_entry(state: SectionState) -> Command: # Branch-local payload from the level-1 Send; fan out level 2 from here. words = state["section"].split() mid = max(1, len(words) // 2) parts = [" ".join(words[:mid]), " ".join(words[mid:])] return Command(goto=[Send("process_chunk", {"chunk": p}) for p in parts if p])
def process_chunk(state: ChunkState) -> dict: return {"chunks": [state["chunk"].upper()]}
builder = StateGraph(RootState)builder.add_node("section_entry", section_entry, destinations=("process_chunk",))builder.add_node("process_chunk", process_chunk)builder.add_conditional_edges( START, lambda s: [Send("section_entry", {"section": x}) for x in s["sections"]])builder.add_edge("process_chunk", END)graph = builder.compile()
print(graph.invoke({"sections": ["hello world", "foo bar baz"], "chunks": []})["chunks"])# ['HELLO', 'WORLD', 'FOO', 'BAR BAZ'] (order may vary)9. Fan-out then fan-in with Send and a barrier edge
Section titled “9. Fan-out then fan-in with Send and a barrier edge”Send from a conditional edge fans out to N parallel tasks. A barrier edge (add_edge(["source1", "source2"], "target")) waits for all of them before running the aggregation node.
import operatorfrom typing import Annotatedfrom typing_extensions import TypedDictfrom langgraph.graph import StateGraph, START, ENDfrom langgraph.types import Send
class Pipeline(TypedDict): documents: list[str] scores: Annotated[list[dict], operator.add] # accumulates results from all workers
def score_document(state: dict) -> dict: """Score one document — runs once per Send.""" doc = state["document"] score = len(doc) / 100.0 # replace with a real scoring call return {"scores": [{"doc": doc[:30], "score": score}]}
def aggregate(state: Pipeline) -> dict: avg = sum(s["score"] for s in state["scores"]) / len(state["scores"]) best = max(state["scores"], key=lambda s: s["score"]) print(f"Scored {len(state['scores'])} documents. avg={avg:.2f}, best={best['doc']!r}") return {}
builder = StateGraph(Pipeline)builder.add_node("score_document", score_document)builder.add_node("aggregate", aggregate)
# Fan out: one Send per document, all run in parallelbuilder.add_conditional_edges( START, lambda s: [Send("score_document", {"document": d, "scores": []}) for d in s["documents"]],)# Fan in: barrier waits for all score_document tasksbuilder.add_edge("score_document", "aggregate")builder.add_edge("aggregate", END)
graph = builder.compile()graph.invoke({ "documents": ["Short doc", "A much longer document with more content", "Medium length document here"], "scores": [],})Gotchas
Section titled “Gotchas”Command(goto="name")adds to explicit edges; it does not replace them. A node withadd_edge("node", "next")that returnsCommand(goto="other")runs bothotherandnextin the next step. Pick one style per node.Command.gotodoes not acceptstrfor subgraph namespaces. Always use a plain node name at the current graph level; cross-graph jumps usegraph=Command.PARENT.- The type parameter on
Command[Literal[...]]is for the visualizer. It doesn’t narrow to runtime errors. Send(node, arg)ignores the main state.argis the snapshot for the target node’s run. If you need context, stuff it intoarg.Sendwith a dictargis unhashable. Equality comparesargstructurally, andhash()hashes(node, arg, timeout), so putting such aSendin a set raisesTypeError.- A node that returns
Command(graph=Command.PARENT)outside a subgraph raisesParentCommand. Only valid when the node runs inside a compiled subgraph used by a parent. update=in aCommandstill goes through reducers. UseOverwrite(...)in theupdatevalues if you need to replace a reducing channel.- Resuming an interrupt re-runs the node from the top. Make side effects idempotent or put them in
@tasks.
Breaking changes
Section titled “Breaking changes”| Version | Change |
|---|---|
| 1.2.0 | Send(..., timeout=...). |
| 0.6 | Interrupt.ns, Interrupt.when, Interrupt.resumable removed; Interrupt.id added and Interrupt.interrupt_id deprecated in its favour. |
| 0.4 | Interrupt.interrupt_id property added. |
| 0.2.24 | Interrupt added. |