Skip to main content
Handles tool execution patterns including function calls, state injection, persistent storage, and control flow. Manages parallel execution and error handling. Defined in: langgraph/prebuilt/tool_node.py:616

Overview

Use ToolNode 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:
  1. Graph state with messages key that has a list of messages:
    • Common representation for agentic workflows
    • Supports custom messages key via messages_key parameter
  2. Message List: [AIMessage(..., tool_calls=[...])]
    • List of messages with tool calls in the last AIMessage
  3. 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(...)]
For Command tools:
  • Returns [Command(...)] or mixed list with regular tool outputs
  • Command can update state, trigger navigation, or send messages

Parameters

Sequence[BaseTool | Callable]
required
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
str
default:"'tools'"
The name identifier for this node in the graph. Used for debugging and visualization.
list[str] | None
default:"None"
Optional metadata tags to associate with the node for filtering and organization.
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 a ToolMessage with the default error template containing the exception details.
  • str: Catch all errors and return a ToolMessage with 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.
Defaults to a callable that:
  • 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)
str
default:"'messages'"
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.
ToolCallWrapper | None
default:"None"
Sync wrapper function to intercept tool execution. Receives ToolCallRequest and execute callable, returns ToolMessage or Command. Enables retries, caching, request modification, and control flow.
AsyncToolCallWrapper | None
default:"None"
Async wrapper function to intercept tool execution. If not provided, falls back to wrap_tool_call for async execution.

Properties

dict[str, BaseTool]
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

ToolRuntime

dataclass
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 state
  • tool_call_id: The ID of the current tool call
  • config: RunnableConfig for the current execution
  • context: Runtime context (shared with Runtime)
  • store: BaseStore instance for persistent storage (shared with Runtime)
  • stream_writer: StreamWriter for streaming output (shared with Runtime)
No Annotated wrapper is needed - just use runtime: ToolRuntime as a parameter.Defined in: langgraph/prebuilt/tool_node.py:1537

Attributes

StateT
The current graph state.
ContextT
Runtime context.
RunnableConfig
Runnable configuration for the current execution.
StreamWriter
Stream writer for streaming output.
str | None
The ID of the current tool call.
BaseStore | None
Persistent store instance.

InjectedState

class
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:1603

Parameters

str | None
default:"None"
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

class
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.
InjectedStore annotation requires langchain-core >= 0.3.8
Defined in: langgraph/prebuilt/tool_node.py:1679

Example

tools_condition

function
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:1456

Parameters

list[AnyMessage] | dict[str, Any] | BaseModel
required
The current graph state to examine for tool calls. Supported formats:
  • Dictionary containing a messages key (for StateGraph)
  • BaseModel instance with a messages attribute
str
default:"'messages'"
The key or attribute name containing the message list in the state. This allows customization for graphs using different state schemas.

Returns

Literal['tools', '__end__']
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 ToolNode internally
  • ValidationNode - Node for validating tool calls without executing them
  • Command - Type for returning control flow commands from tools