Conditional routing function for tool-calling workflows.
This utility function implements the standard conditional logic for ReAct-style
agents: if the last AIMessage contains tool calls, route to the tool execution
node; otherwise, end the workflow. This pattern is fundamental to most tool-calling
agent architectures.
The function handles multiple state formats commonly used in LangGraph applications, making it flexible for different graph designs while maintaining consistent behavior.
tools_condition(
state: list[AnyMessage] | dict[str, Any] | BaseModel,
messages_key: str = 'messages'
) -> Literal['tools', '__end__']Example:
Basic usage in a ReAct agent:
from langgraph.graph import StateGraph
from langchain.tools import ToolNode
from langchain.tools.tool_node import tools_condition
from typing_extensions import TypedDict
class State(TypedDict):
messages: list
graph = StateGraph(State)
graph.add_node("llm", call_model)
graph.add_node("tools", ToolNode([my_tool]))
graph.add_conditional_edges(
"llm",
tools_condition, # Routes to "tools" or "__end__"
{"tools": "tools", "__end__": "__end__"},
)
Custom messages key:
def custom_condition(state):
return tools_condition(state, messages_key="chat_history")
This function is designed to work seamlessly with ToolNode and standard
LangGraph patterns. It expects the last message to be an AIMessage when
tool calls are present, which is the standard output format for tool-calling
language models.
| Name | Type | Description |
|---|---|---|
state* | list[AnyMessage] | dict[str, Any] | BaseModel | The current graph state to examine for tool calls. Supported formats:
|
messages_key | str | Default: 'messages'The key or attribute name containing the message list in the state. This allows customization for graphs using different state schemas. |