Thursday, December 12, 2024

What is Command in Langgraph

Command can be useful to combine control flow (edges) and state updates (nodes). For example, you might want to BOTH perform state updates AND decide which node to go to next in the SAME node. LangGraph provides a way to do so by returning a Command object from node functions:

def my_node(state: State) -> Command[Literal["my_other_node"]]:

    return Command(

        # state update

        update={"foo": "bar"},

        # control flow

        goto="my_other_node"

    )

For e.g. like this below 

def node_a(state: State) -> Command[Literal["node_b", "node_c"]]:

    print("Called A")

    value = random.choice(["a", "b"])

    # this is a replacement for a conditional edge function

    if value == "a":

        goto = "node_b"

    else:

        goto = "node_c"

    # note how Command allows you to BOTH update the graph state AND route to the next node

    return Command(

        # this is the state update

        update={"foo": value},

        # this is a replacement for an edge

        goto=goto,

    )

References:

https://langchain-ai.github.io/langgraph/how-tos/command/

No comments:

Post a Comment