Updating state and routing with Command

Topic 4 of 5 in Advanced control flow28 min readIntermediateFree course

Overview

In the previous lesson, you learned how Send distributes work dynamically across multiple worker invocations. An orchestrator could examine a collection of documents, create one task per document, and distribute those tasks across parallel branches.

That mechanism solves the problem of dynamic task distribution.

However, another important requirement arises when a node performs an operation, obtains a result, and must immediately decide what happens next.

Consider an enterprise document-processing system. After evaluating a document, the system might need to:

  • Record the document’s quality score.
  • Update its processing status.
  • Route high-quality documents to publication.
  • Route uncertain documents to human review.
  • Reject documents that fail validation.

You could implement the evaluation as a normal node and attach a separate conditional routing function. That approach works well, but it separates a closely related state update and routing decision.

LangGraph provides Command for expressing both responsibilities together.

A node returning Command can communicate not only what changed in the application state, but also which node should execute next.

This capability is particularly valuable for stateful agents, business workflows, tool-driven handoffs, hierarchical multi-agent systems, and human-in-the-loop applications.

Command is not a replacement for every edge or routing function. It is a specialized control-flow primitive for situations where state transitions and execution decisions naturally belong together.

Install the dependencies for this lesson:

Terminal
pip install -U "langgraph>=1.0,<2.0" "langchain>=1.0,<2.0"

The examples are standalone scripts using deterministic functions and simulated document-processing operations. No model API keys or external services are required.

The examples follow the current LangGraph 1.x documentation. Expected outputs are provided for verification; the packages were not installed in the lesson-authoring environment, so the scripts have not been executed there.

Basic usage

Understanding the Command object

Import Command from langgraph.types:

Python
from langgraph.types import Command

A typical command looks like this:

Python
Command(
    update={"status": "approved"},
    goto="publish",
)

This object expresses two instructions:

  1. Update the graph’s status field to approved.
  2. Schedule the registered node named publish.

Unlike directly calling a Python function, this delegates execution to LangGraph’s runtime.

The destination remains a graph node, which means it participates in normal scheduling, state management, checkpointing, tracing, retry handling, and recursion-limit enforcement.

Command parameters

Parameter Purpose
update Specifies partial state updates
goto Specifies the next node or nodes
graph Selects the graph that receives the command
resume Supplies a value to a suspended interrupt

For ordinary node execution, update and goto are the most frequently used parameters.

For nested workflows, graph becomes important. For human-in-the-loop execution, resume is the primary parameter.

These arguments are optional, so a command may contain only an update, only a routing instruction, or both.

Example: Routing documents by quality

Suppose a document has already received a quality score from an earlier analysis stage.

Documents scoring at least 80 should be accepted. All other documents should require revision.

The following diagram illustrates a node that combines the evaluation result and routing decision.

Basic usage diagram: START to Evaluate document; Evaluate document to Score sufficient?; Score sufficient? to Accept document (Yes); Score sufficient? to Request revision (No); Accept document to END; Request revision to END.

The following complete program implements this workflow using Command.

Python
import operator
from typing import Annotated, Literal
from typing_extensions import TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.types import Command

class State(TypedDict):
    document: str
    quality_score: int
    status: str
    audit: Annotated[list[str], operator.add]
    result: str

def evaluate(
    state: State,
) -> Command[Literal["accept", "revise"]]:
    score = state["quality_score"]

    if not 0 <= score <= 100:
        raise ValueError("Invalid quality score")

    if score >= 80:
        return Command(
            update={
                "status": "approved",
                "audit": ["Quality evaluation passed"],
            },
            goto="accept",
        )

    return Command(
        update={
            "status": "revision_required",
            "audit": ["Quality evaluation failed"],
        },
        goto="revise",
    )

def accept(state: State) -> dict:
    return {
        "result": f"Accepted: {state['document']}",
        "audit": ["Acceptance completed"],
    }

def revise(state: State) -> dict:
    return {
        "result": f"Revise: {state['document']}",
        "audit": ["Revision requested"],
    }

builder = StateGraph(State)

builder.add_node("evaluate", evaluate)
builder.add_node("accept", accept)
builder.add_node("revise", revise)

builder.add_edge(START, "evaluate")
builder.add_edge("accept", END)
builder.add_edge("revise", END)

graph = builder.compile()

for score in [92, 65]:
    result = graph.invoke({
        "document": "Compliance report",
        "quality_score": score,
        "status": "pending",
        "audit": [],
    })

    print(result["status"])
    print(result["result"])
    print(result["audit"])
    print()

Expected output:

Text
approved
Accepted: Compliance report
['Quality evaluation passed', 'Acceptance completed']

revision_required
Revise: Compliance report
['Quality evaluation failed', 'Revision requested']

Notice that no static or conditional outgoing edges are defined for evaluate.

The node’s returned command determines its next destination.

Understanding the return type

The evaluation function declares:

Python
def evaluate(
    state: State,
) -> Command[Literal["accept", "revise"]]:

The Literal type identifies the possible destinations.

LangGraph uses these destination declarations to understand and visualize dynamic transitions. They also improve code readability and enable static type-checking tools to detect certain mistakes.

However, a type annotation is not a runtime authorization mechanism. An application must still validate dynamic destinations when they originate from untrusted inputs or model-generated decisions.

Destination names must correspond to registered graph nodes or supported special destinations such as END.

You can inspect the compiled graph’s Mermaid representation:

Python
print(graph.get_graph().draw_mermaid())

Dynamic transitions declared through Command can then appear in the graph visualization.

How Command works internally

When evaluate executes, LangGraph supplies the state available to that node.

The returned command is interpreted by the runtime as state-update instructions and scheduling information.

The update portion is processed using the graph’s state channels and reducers. The goto portion contributes dynamic execution triggers.

At the appropriate super-step boundary, the updates become available to downstream nodes.

In the example, the accept node sees status="approved" because the evaluation update has already been applied before the downstream node executes.

The audit field uses operator.add, so each new audit entry is appended rather than replacing earlier entries.

Command does not bypass reducer behavior, and it does not make external database operations transactional.

Note: Returning a command schedules downstream graph execution; it does not immediately call the destination function or provide an unrestricted jump into arbitrary Python code.

See the official Graph API overview for the relationship between state channels, nodes, and dynamic execution.

Routing to multiple destinations

A command is not restricted to one destination.

For example:

Python
return Command(
    update={"status": "analysis_started"},
    goto=["check_quality", "check_compliance"],
)

This schedules both registered analysis nodes.

When both become eligible in the same super-step, they can execute concurrently, subject to runtime concurrency constraints.

If both update the same state field, the field still requires compatible merge semantics.

Command.goto can also contain Send objects. Unlike a plain destination name, a Send supplies a custom input for a specific worker invocation.

This connects the current lesson to the dynamic fan-out patterns introduced previously.

To terminate the current execution path, use:

Python
return Command(
    update={"status": "completed"},
    goto=END,
)

Routing to END does not cancel unrelated branches that are already scheduled.

Command vs conditional edges

Both conditional edges and Command support dynamic routing. The primary difference is where the routing responsibility resides.

Using conditional edges

With conditional edges, a node produces state updates, and a separate routing function determines the destination.

For example:

Python
def evaluate(state: State) -> dict:
    approved = state["quality_score"] >= 80

    return {
        "status": (
            "approved" if approved
            else "revision_required"
        )
    }

def route(
    state: State,
) -> Literal["accept", "revise"]:
    if state["status"] == "approved":
        return "accept"

    return "revise"

The builder connects the routing function to the evaluation node:

Python
builder.add_conditional_edges(
    "evaluate",
    route,
)

The routing function can inspect the evaluation result without repeating the evaluation itself.

This separation is useful when routing rules are reusable, independently maintained, or logically distinct from the node’s primary responsibility.

Using Command

With Command, the evaluation function returns both pieces of information directly.

Python
def evaluate(
    state: State,
) -> Command[Literal["accept", "revise"]]:
    approved = state["quality_score"] >= 80

    return Command(
        update={
            "status": (
                "approved" if approved
                else "revision_required"
            )
        },
        goto="accept" if approved else "revise",
    )

No separate conditional edge is necessary for that transition.

Comparing the approaches

Feature Conditional edges Command
Routing responsibility Separate routing function Node or tool
State updates Returned by the source node Included in the command
Routing-only decisions Preferred approach Supported but often unnecessary
Coupled update and routing Separate responsibilities Expressed together
Dynamic fan-out Supports Send Supports Send through goto
Tool-driven transitions Usually coordinated externally Can originate inside tools
Parent graph navigation Not directly supported Supports Command.PARENT
Interrupt resumption Not supported directly Supports resume

Choose conditional edges when a decision simply examines available state. Choose Command when an operation naturally determines both a state transition and its next action.

Neither approach inherently requires an additional LLM call. Performance differences are generally less important than maintainability.

Avoiding duplicate transitions

A particularly important mistake is combining Command.goto with an unintended static outgoing edge.

Consider this node:

Python
def evaluate(state: State):
    return Command(
        update={"status": "approved"},
        goto="accept",
    )

Suppose the builder also contains:

Python
builder.add_edge("evaluate", "revise")

Both accept and revise can execute.

The command adds a dynamic transition; it does not remove the static transition.

This can produce conflicting statuses, duplicate notifications, or concurrent state-update errors.

Similarly, attaching a conditional routing function to a node that already returns routing commands can introduce additional paths.

Keep one intentional routing mechanism per source node unless multiple transitions are explicitly part of your design.

Incoming edges are unaffected. A node that returns Command can still be reached through ordinary static or conditional edges.

The official Send and Command guide demonstrates how these dynamic transitions are represented.

Command from tools

Tools extend an agent’s capabilities by allowing it to retrieve information, execute application logic, or interact with external systems.

Ordinarily, a tool returns text or structured data. That output becomes a tool result that an LLM can interpret.

However, returning a normal dictionary from a tool does not automatically update arbitrary graph state fields.

For example:

Python
return {"document_status": "verified"}

This is ordinary tool output.

To update the graph’s structured document_status field directly, return a command:

Python
return Command(
    update={"document_status": "verified"}
)

This distinction matters when subsequent nodes need reliable application state instead of reconstructing facts from conversational messages.

Accessing tool runtime information

LangChain’s ToolRuntime provides injected execution information, including:

  • Current graph state through runtime.state.
  • Runtime context through runtime.context.
  • The active tool-call identifier through runtime.tool_call_id.
  • The configured store through runtime.store.

These values are supplied by the execution framework rather than generated as tool arguments by the model.

When a tool returns a command targeting the current graph, include a corresponding ToolMessage in its message-state update.

The message must contain the matching tool-call identifier. This preserves the relationship between an assistant’s tool request and the resulting response.

Example: A tool-controlled document workflow

The following program simulates a document registry.

A verification tool looks up a document, updates its verification status, and routes execution to either an acceptance node or a manual-review node.

Instead of invoking a paid model, the program constructs an AIMessage containing a tool call. This reproduces the relevant execution structure without model-dependent behavior.

Python
from typing import Literal

from langchain.messages import (
    AIMessage,
    HumanMessage,
    ToolMessage,
)
from langchain.tools import tool, ToolRuntime

from langgraph.graph import (
    StateGraph,
    MessagesState,
    START,
    END,
)
from langgraph.prebuilt import ToolNode
from langgraph.types import Command

DOCUMENT_REGISTRY = {
    "DOC-001": "verified",
    "DOC-002": "unverified",
}

class State(MessagesState):
    document_id: str
    document_status: str
    outcome: str

@tool
def verify_document(
    document_id: str,
    runtime: ToolRuntime,
) -> Command[Literal["accept", "review"]]:
    """Check a document against the document registry."""

    status = DOCUMENT_REGISTRY.get(
        document_id,
        "not_found",
    )

    destination = (
        "accept" if status == "verified"
        else "review"
    )

    return Command(
        update={
            "document_status": status,
            "messages": [
                ToolMessage(
                    content=f"Registry status: {status}",
                    tool_call_id=runtime.tool_call_id,
                )
            ],
        },
        goto=destination,
    )

def request_verification(state: State) -> dict:
    return {
        "messages": [
            AIMessage(
                content="",
                tool_calls=[{
                    "name": "verify_document",
                    "args": {
                        "document_id": state["document_id"]
                    },
                    "id": "verification-call",
                    "type": "tool_call",
                }],
            )
        ]
    }

def accept(state: State) -> dict:
    return {
        "outcome": "Accepted",
        "messages": [
            AIMessage(content="Document verified.")
        ],
    }

def review(state: State) -> dict:
    return {
        "outcome": "Manual review required",
        "messages": [
            AIMessage(
                content="Document requires manual review."
            )
        ],
    }

builder = StateGraph(State)

builder.add_node("request", request_verification)
builder.add_node(
    "tools",
    ToolNode([verify_document]),
    destinations=("accept", "review"),
)

builder.add_node("accept", accept)
builder.add_node("review", review)

builder.add_edge(START, "request")
builder.add_edge("request", "tools")

builder.add_edge("accept", END)
builder.add_edge("review", END)

graph = builder.compile()

for document_id in ["DOC-001", "DOC-002"]:
    result = graph.invoke({
        "document_id": document_id,
        "messages": [
            HumanMessage(
                content=f"Verify {document_id}"
            )
        ],
    })

    print(document_id)
    print(result["document_status"])
    print(result["outcome"])
    print()

Expected output:

Text
DOC-001
verified
Accepted

DOC-002
unverified
Manual review required

Walking through tool execution

The request node creates an assistant message containing a tool request.

ToolNode executes the registered tool, injects its runtime information, and propagates the returned command.

The command updates document_status, contributes a matching ToolMessage, and schedules the appropriate destination.

MessagesState already supplies the message reducer, so the new tool response is merged into existing message history.

The destinations argument documents the possible transitions from the tool-execution node for graph visualization. It does not create executable static edges.

If you implement your own tool-execution node, you must explicitly propagate returned commands instead of treating them as ordinary tool content.

Tool commands in production agents

The high-level LangChain create_agent API also supports tools that return commands to update custom agent state.

Use a custom StateGraph when your tools must navigate among application-specific processing nodes.

With parallel tool calls, multiple commands may be returned during the same execution stage. Their state updates still follow reducer rules, and their destinations can introduce multiple execution paths.

For mutually exclusive transitions, a safer design is to let tools record structured findings and allow one coordinator node to make the final routing decision.

Consult the official LangChain tools documentation for tool runtime injection and tool-result requirements.

Jumping to the parent graph

Large agentic applications are often divided into subgraphs.

A parent graph may coordinate specialized workflows for document extraction, security analysis, compliance evaluation, and publication.

A subgraph normally executes its internal workflow and returns results to its parent. However, a specialized worker may discover information that requires an immediate handoff to another parent-level operation.

For example, a security scanner might detect sensitive information that requires escalation rather than normal publication.

Command.PARENT provides a mechanism for transferring control to the immediate enclosing graph.

Parent graph navigation

The general syntax is:

Python
return Command(
    graph=Command.PARENT,
    update={"audit": ["Escalation required"]},
    goto="manual_review",
)

Here, manual_review must exist in the parent graph rather than the current subgraph.

The state update is directed to that parent graph.

The following diagram shows a parent workflow containing a specialized scanning subgraph.

Jumping to the parent graph diagram: START to Security subgraph; Security subgraph to Scan document; Scan document to Sensitive content?; Sensitive content? to Manual review (Yes); Sensitive content? to Publish document (No); Manual review to END; Publish document to END.

Example: Escalating from a subgraph

The following program builds a security-scanning subgraph that dynamically transfers control to one of two parent-level nodes.

Python
import operator
from typing import Annotated
from typing_extensions import TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.types import Command

class ParentState(TypedDict):
    document: str
    audit: Annotated[list[str], operator.add]
    status: str

class ScannerState(TypedDict):
    document: str
    audit: Annotated[list[str], operator.add]

def scan_document(state: ScannerState) -> Command:
    sensitive = (
        "confidential" in state["document"].lower()
    )

    if sensitive:
        return Command(
            graph=Command.PARENT,
            update={
                "audit": ["Sensitive content detected"]
            },
            goto="manual_review",
        )

    return Command(
        graph=Command.PARENT,
        update={
            "audit": ["Security scan passed"]
        },
        goto="publish",
    )

scanner_builder = StateGraph(ScannerState)

scanner_builder.add_node("scan", scan_document)
scanner_builder.add_edge(START, "scan")

scanner = scanner_builder.compile()

def manual_review(state: ParentState) -> dict:
    return {
        "status": "requires_review",
        "audit": ["Escalated to security team"],
    }

def publish(state: ParentState) -> dict:
    return {
        "status": "published",
        "audit": ["Publication completed"],
    }

parent_builder = StateGraph(ParentState)

parent_builder.add_node(
    "security_scanner",
    scanner,
    destinations=("manual_review", "publish"),
)

parent_builder.add_node(
    "manual_review",
    manual_review,
)

parent_builder.add_node("publish", publish)

parent_builder.add_edge(
    START,
    "security_scanner",
)

parent_builder.add_edge("manual_review", END)
parent_builder.add_edge("publish", END)

graph = parent_builder.compile()

documents = [
    "Public company announcement",
    "Confidential customer information",
]

for document in documents:
    result = graph.invoke({
        "document": document,
        "audit": [],
        "status": "pending",
    })

    print(result["status"])
    print(result["audit"])

Expected output:

Text
published
['Security scan passed', 'Publication completed']
requires_review
['Sensitive content detected', 'Escalated to security team']

Understanding shared state and reducers

The parent and subgraph both declare document and audit.

The parent additionally owns the final status field.

Because the command updates a field shared between parent and subgraph, the parent defines a reducer for audit. This explicitly establishes how the transferred contribution should merge into its existing state.

The scanner returns only its new audit entry rather than the entire accumulated history.

In production, define a clear state contract between graphs. Each subgraph should understand which parent fields it may update and which parent destinations it may target.

Parent navigation limitations

Command.PARENT refers to the closest enclosing graph.

It is not an arbitrary global jump to any node in a deeply nested application.

A subgraph can hand off to another subgraph registered as a parent-level node, but the destination must belong to the targeted parent.

Avoid assuming that every subgraph will be portable when it directly references parent node names. Such references create coupling between the subgraph and its containing workflow.

For reusable processing components, returning structured results and letting a parent coordinator choose the next destination may provide a cleaner architecture.

Parent commands are most valuable when the component is intentionally designed to participate in application-level handoffs.

Resuming with Command

So far, commands have been returned from executing nodes and tools.

There is another important usage pattern: supplying a command as input when resuming a suspended graph.

This is fundamental to human-in-the-loop workflows.

Understanding interrupts

An interrupt pauses graph execution and exposes a payload to the external caller.

For example:

Python
from langgraph.types import interrupt

approved = interrupt({
    "question": "Approve publication?"
})

The graph cannot continue until an external response is provided.

After obtaining that response, the application resumes execution:

Python
graph.invoke(
    Command(resume=True),
    config,
)

The supplied value becomes the return value of the corresponding interrupt() call during resumed execution.

The node can then use that value to update state and choose its next destination.

Requirements for resumption

A resumable workflow requires a checkpointer, an identifiable thread, and a response associated with the suspended interrupt.

The checkpointer stores execution progress. The thread identifier selects the appropriate saved execution.

Without these components, a later invocation cannot reliably reconstruct the interrupted workflow.

Example: Human approval before publication

The following program pauses for publication approval, then uses a node-returned command to select the final destination.

Python
from typing import Literal
from typing_extensions import TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.types import Command, interrupt
from langgraph.checkpoint.memory import InMemorySaver

class State(TypedDict):
    document: str
    status: str

def request_approval(
    state: State,
) -> Command[Literal["publish", "reject"]]:
    print("Entering approval node")

    approved = interrupt({
        "question": "Approve document publication?",
        "document": state["document"],
    })

    if not isinstance(approved, bool):
        raise ValueError("Expected boolean approval")

    return Command(
        update={
            "status": (
                "approved" if approved else "rejected"
            )
        },
        goto="publish" if approved else "reject",
    )

def publish(state: State) -> dict:
    return {"status": "published"}

def reject(state: State) -> dict:
    return {"status": "rejected"}

builder = StateGraph(State)

builder.add_node("approval", request_approval)
builder.add_node("publish", publish)
builder.add_node("reject", reject)

builder.add_edge(START, "approval")
builder.add_edge("publish", END)
builder.add_edge("reject", END)

graph = builder.compile(
    checkpointer=InMemorySaver()
)

config = {
    "configurable": {
        "thread_id": "publication-001"
    }
}

paused = graph.invoke(
    {
        "document": "Annual financial report",
        "status": "pending",
    },
    config,
)

print(paused["__interrupt__"][0].value)

assert paused["status"] == "pending"

resumed = graph.invoke(
    Command(resume=True),
    config,
)

print("Final status:", resumed["status"])

assert resumed["status"] == "published"

Expected output:

Text
Entering approval node
{'question': 'Approve document publication?', 'document': 'Annual financial report'}
Entering approval node
Final status: published

The approval node executes from its beginning twice.

During the first execution, the interrupt suspends the node. During resumed execution, the runtime supplies the saved response when the interrupt is encountered again.

Understanding node re-execution

A common misconception is that LangGraph preserves the Python function’s suspended call stack and continues directly from the next line.

Instead, the interrupted node restarts from its beginning.

Consequently, operations performed before the interrupt may execute again.

Consider this dangerous arrangement:

Python
def approval_node(state):
    create_external_database_record()

    approved = interrupt("Approve?")

    return {"approved": approved}

The database operation could run more than once.

Move irreversible operations into a downstream node that executes only after approval, or protect those operations with idempotency mechanisms.

Tip: Use InMemorySaver for development and tests, but use a persistent checkpointer such as PostgresSaver in production. In-memory checkpoints cannot survive process termination.

Resuming multiple interrupts

Parallel branches may suspend execution independently.

When several interrupts are pending, use their identifiers to associate each response with the appropriate suspended operation.

For example, given a paused graph with two approval requests:

Python
pending = paused["__interrupt__"]

responses = {
    pending[0].id: True,
    pending[1].id: False,
}

result = graph.invoke(
    Command(resume=responses),
    config,
)

In a real application, associate responses with the identifiers shown in the review interface rather than assuming a particular interrupt ordering.

This is especially important for parallel document-processing systems where multiple documents may require independent approval.

New input vs resumed execution

Distinguish a new graph invocation from a resumed invocation.

Starting a new turn uses a normal state input:

Python
graph.invoke(
    {"document": "Another report"},
    config,
)

Resuming an outstanding interrupt uses:

Python
graph.invoke(
    Command(resume=True),
    config,
)

A plain state input begins execution through the graph’s entry flow while retaining applicable checkpointed state when the same thread is reused.

A resume command continues pending execution associated with the selected checkpoint.

Do not use Command(update=...) alone as a substitute for submitting a new user message or starting a new processing job.

See the official interrupt documentation for validation, multiple interrupts, and durable resumption patterns.

Production best practices

Validate dynamic routing decisions

An LLM may recommend a destination, but the application must enforce its allowed transitions.

Map model-generated classifications to known internal node names rather than directly trusting arbitrary strings.

Authorization checks should remain in application code. A model suggesting publication does not mean the document is authorized for publication.

Design explicit state transitions

Use clear processing statuses such as:

  • pending
  • evaluated
  • awaiting_review
  • approved
  • published
  • rejected

Record important transitions in a reducer-backed audit field or an appropriate external audit system.

Keep a distinction between decisions and completed actions. An approval command should not claim that publication succeeded before the publication node actually executes successfully.

Bound repeated routing

Because a command can route back to an earlier node, it can create cycles.

A revision workflow might repeatedly evaluate and improve a document. Without a termination condition, it could consume excessive computation or model tokens.

Maintain explicit attempt counters or business-level stopping conditions. Additionally, configure a reasonable graph execution limit:

Python
result = graph.invoke(
    inputs,
    {"recursion_limit": 30},
)

The recursion limit is a runtime safeguard measured in super-steps, not a replacement for meaningful business termination rules.

Avoid common mistakes

Mistake Consequence Correction
Combining static edges with unintended command routes Additional branches execute Use one intentional routing mechanism
Returning arbitrary model-generated destinations Invalid or unauthorized transitions Validate destinations
Updating shared fields without reducers Concurrent update conflicts Define merge behavior
Omitting the matching tool response Invalid tool-call history Include a matching ToolMessage
Targeting the wrong graph Invalid cross-graph navigation Use Command.PARENT appropriately
Resuming with a different thread ID Saved execution is not selected Reuse the interrupted thread
Performing irreversible actions before interrupts Duplicate external effects Move actions downstream
Using commands without cycle limits Excessive execution Enforce explicit stopping rules

Test every possible transition, including rejected inputs, approval and rejection responses, concurrent updates, and invalid destinations.

For persistent workflows, also test recovery after process restarts, checkpoint compatibility, and repeated requests from the application layer.

Connection to the next lesson

Throughout this chapter, you have progressively expanded your understanding of graph control flow.

Parallel execution introduced concurrent branches and synchronization. Cycles introduced repeated execution. Send introduced runtime-sized task distribution, and Command introduced closely coupled state transitions and dynamic routing.

These features may appear different at the application level, but they are coordinated by the same underlying execution engine.

A command does not independently execute a destination, just as a reducer does not independently schedule another worker. Both express instructions that LangGraph interprets during graph execution.

The next lesson, How graphs execute — the Pregel model, examines that underlying machinery in detail.

You will learn how actors, channels, execution phases, state visibility, super-step boundaries, and termination conditions work together to support predictable orchestration.

That understanding will help you design the chapter’s parallel document-processing project with greater confidence, particularly when dynamic worker distribution, conditional escalation, and human approval must operate within the same workflow.

Exercise

Build an Intelligent Document Review Workflow

Build a document-review workflow that uses Command to update processing state and dynamically route documents according to their quality scores. Documents scoring at least 80 should proceed directly to publication, scores from 50 to 79 should require human approval, and lower scores should be rejected. Implement human approval using interrupt and Command, and record every processing decision in a reducer-backed audit trail.

Python
import operator
from typing import Annotated, Literal
from typing_extensions import TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.types import Command, interrupt
from langgraph.checkpoint.memory import InMemorySaver


class State(TypedDict):
    document: str
    quality_score: int
    status: str
    audit: Annotated[list[str], operator.add]


def evaluate(
    state: State,
) -> Command[Literal["publish", "review", "reject"]]:
    # TODO: Validate the quality score.
    # TODO: Update status and audit.
    # TODO: Route according to the score.
    raise NotImplementedError


def review(
    state: State,
) -> Command[Literal["publish", "reject"]]:
    # TODO: Interrupt execution for human approval.
    # TODO: Route based on the approval decision.
    raise NotImplementedError


def publish(state: State) -> dict:
    # TODO: Update status and audit.
    raise NotImplementedError


def reject(state: State) -> dict:
    # TODO: Update status and audit.
    raise NotImplementedError


builder = StateGraph(State)

builder.add_node("evaluate", evaluate)
builder.add_node("review", review)
builder.add_node("publish", publish)
builder.add_node("reject", reject)

# TODO: Configure the entry and terminal edges.
# Do not add static outgoing edges from Command nodes.

graph = builder.compile(
    checkpointer=InMemorySaver()
)

config = {
    "configurable": {
        "thread_id": "document-review-001"
    },
    "recursion_limit": 20,
}

result = graph.invoke(
    {
        "document": "Quarterly compliance report",
        "quality_score": 65,
        "status": "pending",
        "audit": [],
    },
    config,
)

# TODO: Inspect the interrupt payload.
# TODO: Resume with human approval.
# TODO: Print the final status and audit trail.

Summary

  • Command allows a node to return state updates and dynamic routing instructions in a single result.
  • The update argument follows the same state and reducer semantics as ordinary dictionary-based node returns.
  • The goto argument supports registered node destinations, multiple destinations, Send objects, and graph termination through END.
  • Command adds dynamic transitions rather than replacing existing static outgoing edges.
  • Tools can return Command to modify structured graph state and route execution while preserving valid tool-call message history.
  • Command.PARENT enables a subgraph to transfer execution and state updates to its immediate parent graph.
  • Command with resume supplies external input to a suspended interrupt using the existing checkpointed thread.