I'm working on an agent using LangGraph, and I need to implement proper routing after tool execution. My setup uses a state graph with conditional edges, and I want to route to a specific node if the tool returns a goto command, otherwise route back to the main processing node.
Here's my current approach:
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
I need to modify this to check if the last tool call returned a Command with a goto field, and route accordingly.
Here's the relevant part of my graph setup code:
def build_graph(self, checkpointer=None) -> CompiledStateGraph:
"""Build the LangGraph for this workflow."""
workflow = StateGraph(State)
# add nodes
workflow.add_node(self.name, self.process)
workflow.add_node(
"tools",
ToolNode(self.tools),
)
# define edges
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)
For example, one of my tools returns a Command with a goto field that should end the flow:
@tool
def get_user_choice(
state: Annotated[State, InjectedState],
tool_call_id: Annotated[str, InjectedToolCallId],
prompt: str,
options: list[OptionBase],
) -> str:
# ...implementation...
return Command(
update={
"messages": [ToolMessage("Waiting for user input.", tool_call_id=tool_call_id)],
},
goto=END
)
How can I properly implement route_tools_to_node to check if the most recent tool execution returned a Command with a goto field, and route to that node instead of always returning to the main processing node?