langgraph/prebuilt/tool_node.py:616
Overview
UseToolNode when building custom workflows that require fine-grained control over tool execution—for example, custom routing logic, specialized error handling, or non-standard agent architectures.
For standard ReAct-style agents, use create_agent instead. It uses ToolNode internally with sensible defaults for the agent loop, conditional routing, and error handling.
Class Definition
Input Formats
ToolNode accepts multiple input formats:
-
Graph state with
messageskey that has a list of messages:- Common representation for agentic workflows
- Supports custom messages key via
messages_keyparameter
-
Message List:
[AIMessage(..., tool_calls=[...])]- List of messages with tool calls in the last AIMessage
-
Direct Tool Calls:
[{"name": "tool", "args": {...}, "id": "1", "type": "tool_call"}]- Bypasses message parsing for direct tool execution
- For programmatic tool invocation and testing
Output Formats
Output format depends on input type and tool behavior: For Regular tools:- Dict input →
{"messages": [ToolMessage(...)]} - List input →
[ToolMessage(...)]
- Returns
[Command(...)]or mixed list with regular tool outputs Commandcan update state, trigger navigation, or send messages
Parameters
A sequence of tools that can be invoked by this node.Supports:
- BaseTool instances: Tools with schemas and metadata
- Plain functions: Automatically converted to tools with inferred schemas
The name identifier for this node in the graph. Used for debugging and visualization.
Optional metadata tags to associate with the node for filtering and organization.
handle_tool_errors
bool | str | Callable | type[Exception] | tuple[type[Exception], ...]
default:"_default_handle_tool_errors"
Configuration for error handling during tool execution. Supports multiple strategies:
True: Catch all errors and return aToolMessagewith the default error template containing the exception details.str: Catch all errors and return aToolMessagewith this custom error message string.type[Exception]: Only catch exceptions with the specified type and return the default error message for it.tuple[type[Exception], ...]: Only catch exceptions with the specified types and return default error messages for them.Callable[..., str]: Catch exceptions matching the callable’s signature and return the string result of calling it with the exception.False: Disable error handling entirely, allowing exceptions to propagate.
- Catches tool invocation errors (due to invalid arguments provided by the model) and returns a descriptive error message
- Ignores tool execution errors (they will be re-raised)
The key in the state dictionary that contains the message list. This same key will be used for the output
ToolMessage objects.Allows custom state schemas with different message field names.Sync wrapper function to intercept tool execution. Receives
ToolCallRequest and execute callable, returns ToolMessage or Command. Enables retries, caching, request modification, and control flow.Async wrapper function to intercept tool execution. If not provided, falls back to
wrap_tool_call for async execution.Properties
Mapping from tool name to BaseTool instance.
Usage Examples
Basic Usage
State Injection
Custom Error Handling
Store Injection
Runtime Context Access
Tool Call Wrapper for Retries
In a StateGraph
Related Classes and Functions
ToolRuntime
Runtime context automatically injected into tools.When a tool function has a parameter named
runtime with type hint ToolRuntime, the tool execution system will automatically inject an instance containing:state: The current graph statetool_call_id: The ID of the current tool callconfig:RunnableConfigfor the current executioncontext: Runtime context (shared withRuntime)store:BaseStoreinstance for persistent storage (shared withRuntime)stream_writer:StreamWriterfor streaming output (shared withRuntime)
Annotated wrapper is needed - just use runtime: ToolRuntime as a parameter.Defined in: langgraph/prebuilt/tool_node.py:1537Attributes
The current graph state.
Runtime context.
Runnable configuration for the current execution.
Stream writer for streaming output.
The ID of the current tool call.
Persistent store instance.
InjectedState
Annotation for injecting graph state into tool arguments.This annotation enables tools to access graph state without exposing state management details to the language model. Tools annotated with
InjectedState receive state data automatically during execution while remaining invisible to the model’s tool-calling interface.Defined in: langgraph/prebuilt/tool_node.py:1603Parameters
Optional key to extract from the state dictionary. If
None, the entire state is injected. If specified, only that field’s value is injected.Example
InjectedStore
Annotation for injecting persistent store into tool arguments.This annotation enables tools to access LangGraph’s persistent storage system without exposing storage details to the language model. Tools annotated with
InjectedStore receive the store instance automatically during execution while remaining invisible to the model’s tool-calling interface.The store provides persistent, cross-session data storage that tools can use for maintaining context, user preferences, or any other data that needs to persist beyond individual workflow executions.Defined in: langgraph/prebuilt/tool_node.py:1679Example
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.Defined in: langgraph/prebuilt/tool_node.py:1456Parameters
The current graph state to examine for tool calls. Supported formats:
- Dictionary containing a messages key (for
StateGraph) BaseModelinstance with a messages attribute
The key or attribute name containing the message list in the state. This allows customization for graphs using different state schemas.
Returns
Either
'tools' if tool calls are present in the last AIMessage, or '__end__' to terminate the workflow.Example
See Also
- create_react_agent - Factory function that uses
ToolNodeinternally - ValidationNode - Node for validating tool calls without executing them
- Command - Type for returning control flow commands from tools