API Reference: ToolNode
The ToolNode is the "hands" of your agent. It is a robust node that runs any plain Python function (a "tool").
This is how your agent interacts with the world:
-
Running code (
run_generated_code) -
Searching a database (
retrieve_relevant_chunks) -
Calling an external API (
Google Search) -
Modifying the state (
increment_retry_count)
Key Features
-
Robust: It runs your tool inside a
try...exceptblock by default. -
Resilient: It supports two separate paths:
next_node(for success) anderror_node(for failure). -
Stateful: It dynamically gathers the arguments for your tool from the
GraphStateusing the input_keys you provide. -
Auditable: If your tool fails, the
ToolNodeautomatically catches the exception and saves the error message tostate.set("last_error", ...)for your other nodes to read.
Example Usage
First, define your "tool." It's just a simple Python function:
def add_numbers(a: int, b: int) -> int:
"""A simple tool that adds two numbers."""
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError("Inputs must be integers")
return a + b
Then, wire it into your graph with a ToolNode:
# The ToolNode will:
# 1. Get `state.get("num1")` and `state.get("num2")`
# 2. Call `add_numbers(num1, num2)`
# 3. Save the result to `state.set("sum_result", ...)`
add_node = ToolNode(
tool_function=add_numbers,
input_keys=["num1", "num2"],
output_key="sum_result",
next_node=success_node,
error_node=failure_node # If the TypeError is raised
)
What it Does
-
When execute(state) is called:
-
It builds a list of inputs by getting each key from self.input_keys.
-
It calls self.tool_function(*inputs).
-
-
If it succeeds:
-
It saves the return value to state.set(self.output_key, ...)
-
It returns self.next_node.
-
-
If it fails:
-
It saves the exception message to state.set("last_error", ...)
-
It returns self.error_node.
-
__init__ Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
tool_function |
Callable |
Yes | The Python function you want to run. |
input_keys |
List[str] |
Yes | A list of keys to read from the 'GraphState'. The values are passed to your tool as positional arguments in order. |
output_key |
str |
Yes | The GraphState key to save the tool's return value to. |
next_node |
BaseNode |
Yes | The node to run if the tool succeeds. |
error_node |
BaseNode |
No | The node to run if the tool fails (raises an Exception). If None, the graph will stop. |