如何在LangGraph中根据工具返回结果路由至特定节点
问题:LangGraph工具执行后的条件路由实现
在使用LangGraph开发智能体时,需要实现工具执行后的精准路由逻辑:
- 基于带条件边的状态图设计
- 当工具返回含
goto字段的Command时,路由至指定节点(如示例中的END) - 无
goto指令时,默认返回主处理节点 - 现有
route_tools_to_node函数暂固定返回主节点,需修改以满足上述需求
当前函数实现
def route_tools_to_node(self, state: State, config: RunnableConfig): # TODO: If a command with goto is returned from the tool, route to that node. Otherwise route to self.name. return self.name
图构建代码片段
def build_graph(self, checkpointer=None) -> CompiledStateGraph: """Build the LangGraph for this workflow.""" workflow = StateGraph(State) # 添加节点 workflow.add_node(self.name, self.process) workflow.add_node( "tools", ToolNode(self.tools), ) # 定义边规则 workflow.set_entry_point(self.name) workflow.add_conditional_edges(self.name, tools_condition) workflow.add_conditional_edges("tools", self.route_tools_to_node) return workflow.compile(checkpointer=checkpointer)
工具返回示例(含goto指令)
@tool def get_user_choice( state: Annotated[State, InjectedState], tool_call_id: Annotated[str, InjectedToolCallId], prompt: str, options: list[OptionBase], ) -> str: # ...业务逻辑实现... return Command( update={ "messages": [ToolMessage("Waiting for user input.", tool_call_id=tool_call_id)], }, goto=END )
解决方案
修改route_tools_to_node函数,从状态中提取工具执行结果,检查是否包含有效goto指令,再返回对应路由节点:
def route_tools_to_node(self, state: State, config: RunnableConfig): # 获取最新的工具执行消息 last_message = state.messages[-1] # 验证消息类型并解析goto指令 if isinstance(last_message, ToolMessage): tool_result = last_message.content # 处理Command实例或序列化后的字典两种情况 if hasattr(tool_result, 'goto') and tool_result.goto is not None: return tool_result.goto elif isinstance(tool_result, dict) and 'goto' in tool_result and tool_result['goto'] is not None: return tool_result['goto'] # 无有效goto指令时,返回主处理节点 return self.name
关键说明
- 工具结果提取:工具执行完成后,结果会以
ToolMessage形式追加到状态的messages列表末尾,取最后一条即可获取最新结果。 - goto指令检查:兼容工具返回
Command实例(直接访问属性)或序列化字典(按键访问)两种场景,确保路由逻辑覆盖所有可能的返回格式。 - 默认路由:未检测到有效
goto指令时,默认返回主处理节点,保证流程稳定性。
额外注意事项
- 确保
State类的messages字段能正确存储ToolMessage对象。 - 若工具返回的是序列化后的
Command(如JSON字符串),需先反序列化为实例或字典再解析goto字段。 - 若使用
END作为终止节点,需确认已通过workflow.add_node(END, ...)或LangGraph内置机制配置好终止逻辑。
内容的提问来源于stack exchange,提问作者Nimish David Mathew
相关产品推荐
相关产品推荐

