这篇文章我们将 LangGraph中的控制流(边)和状态更新(节点)结合起来使用。比如,我们希望同时执行状态更新并决定下一步要转到哪个节点,且这些操作在同一个节点中完成。而正好 LangGraph 提供了一种方法,可以通过从节点函数返回一个 Command 对象来实现这一点。
def my_node(state: State) -> Command[Literal["my_other_node"]]:
return Command(
# state update
update={
"foo": "bar"},
# control flow
goto="my_other_node"
)
如果我们使用的是 subgraphs(子图) 我们还可以通过 Command 中指定 graph=Command.PARENT这种方式,实现节点从一个子图导航到其他子图。
def my_node(state: State) -> Command[Literal["my_other_node"]]:
return Command(
update={
"foo": "bar"},
goto="other_subgraph", # where `other_subgraph` is a node in the parent graph
graph=Command.PARENT
)
当我们从子图节点向父图节点发送更新的时候,且更新的键同时存在于父图和子图的状态模式中时,我们必须为父图状态中正在更新的键定义一个 reducer。
下面我们开始我们的例子。
定义节点和State
定义 graph State:
class State(TypedDict)