# tools_condition

> **Function** in `langgraph.prebuilt`

📖 [View in docs](https://reference.langchain.com/python/langgraph.prebuilt/tool_node/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.

## Signature

```python
tools_condition(
    state: list[AnyMessage] | dict[str, Any] | BaseModel,
    messages_key: str = 'messages',
) -> Literal['tools', '__end__']
```

## Description

**Example:**

Basic usage in a ReAct agent:

```python
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:

```python
def custom_condition(state):
    return tools_condition(state, messages_key="chat_history")
```

!!! note
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.

## Parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `state` | `list[AnyMessage] \| dict[str, Any] \| BaseModel` | Yes | 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_key` | `str` | No | The key or attribute name containing the message list in the state. This allows customization for graphs using different state schemas. (default: `'messages'`) |

## Returns

`Literal['tools', '__end__']`

Either `'tools'` if tool calls are present in the last `AIMessage`, or `'__end__'`
to terminate the workflow. These are the standard routing destinations for
tool-calling conditional edges.

---

[View source on GitHub](https://github.com/langchain-ai/langgraph/blob/aa322c13cd5f16a3f6254a931a4104e412cd687c/libs/prebuilt/langgraph/prebuilt/tool_node.py#L1582)