LangChain Reference home pageLangChain ReferenceLangChain Reference
  • GitHub
  • Main Docs
Deep Agents
LangChain
LangGraph
Integrations
LangSmith
  • Overview
  • LangGraph Checkpoint
    Checkpoint Postgres
    Store Postgres
    Checkpoint SQLite
    LangGraph Prebuilt
    LangGraph CLI
    LangGraph SDK
    LangGraph Supervisor
    LangGraph Swarm
    ⌘I

    LangChain Assistant

    Ask a question to get started

    Enter to send•Shift+Enter new line

    Menu

    LangGraph Checkpoint
    Checkpoint Postgres
    Store Postgres
    Checkpoint SQLite
    LangGraph Prebuilt
    LangGraph CLI
    LangGraph SDK
    LangGraph Supervisor
    LangGraph Swarm
    Language
    Theme
    Pythonlanggraph.prebuilttool_nodetools_condition
    Function●Since v0.1

    tools_condition

    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.

    Copy
    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.

    Used in Docs

    • Build a custom RAG agent with LangGraph
    • Tools

    Parameters

    NameTypeDescription
    state*list[AnyMessage] | dict[str, Any] | BaseModel

    The current graph state to examine for tool calls. Supported formats:

    • Dictionary containing a messages key (for StateGraph)
    • BaseModel instance with a messages attribute
    messages_keystr
    Default:'messages'

    The key or attribute name containing the message list in the state. This allows customization for graphs using different state schemas.

    View source on GitHub