Tool Node
Replace the hand-written tools node with LangGraph’s prebuilt ToolNode - and see exactly what it does with good calls, bad calls and crashing tools.
What you will be able to do
- Explain what ToolNode does - and what it does not do
- Build agent -> ToolNode -> agent with MessagesState and tools_condition
- Follow a run message by message: human, AI tool call, tool result, answer
- Know how ToolNode reacts to unknown tools, bad arguments and tool exceptions
- Run the same graph with a model that cannot call tools, by turning structured output into tool calls
- Place ToolNode between create_agent and a fully hand-written loop
The idea, in plain English
In Lesson 3.4 we wrote the tools node ourselves: look up the action, run the function, write the result. ToolNode is LangGraph’s ready-made version. You give it a list of @tool functions, and it runs whatever tools the model asked for.
It works together with two other ready-made pieces: MessagesState (a state that holds the conversation) and tools_condition (a router that sends the graph to the tools or to the end).
Our llama3 cannot make tool calls, so we ran the graph two ways: with a scripted model, and with llama3 through a small bridge. LangGraph 1.2.14, langgraph-prebuilt 1.1.0.
Worked example: A tool-using graph agent: agent -> ToolNode -> agent.
1 - The question enters as a message
invoke() starts with one HumanMessage in messages. The agent node sends the whole list to the model.
"What is the weather in Hyderabad?" - the message list after each step of a real run.
Words you will see in this lesson
A few new names - all ready-made parts of LangGraph.
Tool callA request from the model: "run get_weather with city=Hyderabad". Stored in AIMessage.tool_calls.ToolNodeA ready-made node that runs the tool calls in the last AI message.ToolMessageThe result of one tool call, put back into the conversation.tool_call_idLinks a ToolMessage to the request it answers.MessagesStateA ready-made state with one field, messages, that ADDS new messages instead of replacing.ReducerA rule for how an update is merged. MessagesState’s rule is "append".tools_conditionA ready-made router: tool calls -> "tools", none -> END.An everyday example: a restaurant kitchen
Think of a restaurant again:
- The waiter (the model) takes your order and writes the tickets: "1 dosa, 1 coffee". The waiter does not cook. (Tool calls.)
- The manager (tools_condition) looks: are there tickets? Then send them to the kitchen. No tickets? The order is complete. (The router.)
- The kitchen (ToolNode) cooks exactly what is on the tickets and sends back each plate with its ticket number. (ToolMessages with tool_call_id.)
- The waiter brings the plates and tells you your meal is ready. (The final answer.)
Who does what
ToolNode only executes. Everything else is someone else’s job:
- Two tool calls in one AI message (get_weather and calculate) came back as two ToolMessages: Rainy, 27°C and 96.
- ToolNode is not a stand-alone function. Calling it outside a graph failed with "Missing required config key ... for ‘tools’".
ModelDecides which tool to request, with which arguments.tools_conditionRoutes to ToolNode if the last AI message has tool calls, else to END.ToolNodeRuns the requested tools and returns ToolMessages.Tool (@tool function)Does the actual work.MessagesStateCarries the conversation, appending every message.The graphControls the whole loop.MessagesState: the conversation is the state
In Lesson 3.2, a returned field replaced the old value. MessagesState is different:
- It has one field: messages.
- An update is ADDED to the list (this rule is called a reducer).
- So the agent returns only the new message - {"messages": [response]} - and the whole conversation is kept.
- Our run ended with four messages: human question -> AI with a tool call -> tool result -> AI answer.
tools_condition: the ready-made router
The router after the agent always asks one question: does the last message contain tool calls?
- Yes -> "tools". No -> "__end__". We checked both.
- You could write it yourself: return "tools" if state["messages"][-1].tool_calls else END.
- Because tools_condition returns "tools", the ToolNode must be NAMED "tools". Any other name needs your own router or a path map.
Example 1 - a tool-using agent graph
This is the Lesson 3.4 loop, built from ready-made parts:
- get_weather is a normal @tool function.
- bind_tools(tools) tells a tool-calling model which tools exist. llama3.1 here stands for any model that supports tool calls.
- agent calls the model and returns the new message.
- add_node("tools", ToolNode(tools)) - the ready-made executor.
- add_conditional_edges("agent", tools_condition) - the ready-made router.
- add_edge("tools", "agent") - the edge back: the loop.
from langchain_core.tools import tool
from langchain_ollama import ChatOllama
from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode, tools_condition
@tool
def get_weather(city: str) -> str:
"""Get the weather for a city."""
weather = {"mumbai": "Rainy, 27°C", "delhi": "Sunny, 34°C", "hyderabad": "Cloudy, 29°C"}
return weather.get(city.lower(), "Weather information is not available.")
tools = [get_weather]
model_with_tools = ChatOllama(model="llama3.1", temperature=0).bind_tools(tools) # needs a tool-calling model
def agent(state: MessagesState):
response = model_with_tools.invoke(state["messages"])
return {"messages": [response]} # appended, not replaced
builder = StateGraph(MessagesState)
builder.add_node("agent", agent)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", tools_condition) # -> "tools" or "__end__"
builder.add_edge("tools", "agent")
graph = builder.compile()
result = graph.invoke({"messages": [{"role": "user", "content": "What is the weather in Hyderabad?"}]})
for message in result["messages"]:
print(message.type, message.content or message.tool_calls)human What is the weather in Hyderabad?
ai [{'name': 'get_weather', 'args': {'city': 'Hyderabad'}, 'id': 'c0', 'type': 'tool_call'}]
tool Cloudy, 29°C
ai The weather in Hyderabad is currently cloudy at 29°C.
graph.get_graph() edges
__start__ --> agent; agent -.-> tools; agent -.-> __end__; tools --> agent;
With llama3 instead:
ChatOllama(model="llama3").bind_tools(tools).invoke(...)
ResponseError: llama3:latest does not support tools (status code: 400)Reading Example 1
- Message 1 (human): the question.
- Message 2 (ai): no text - only a tool call, get_weather(city="Hyderabad"), with id c0.
- Message 3 (tool): ToolNode ran it. "Cloudy, 29°C".
- Message 4 (ai): the model read the result and answered. No tool calls, so tools_condition ended the run.
- llama3 cannot make tool calls at all: bind_tools failed with "does not support tools". The next example shows a way around it.
When things go wrong
ToolNode turns most request mistakes into a message the model can read - and the run continues:
- Unknown tool (send_email): "Error: send_email is not a valid tool, try one of [get_weather, calculate]."
- Wrong argument name ({"town": "Mumbai"}): "city: Field required. Please fix the error and try again."
- But an exception INSIDE the tool (TimeoutError) stopped the whole run - by default.
- With ToolNode(tools, handle_tool_errors=True) the exception became a ToolMessage instead, and the model could react.
- Choose on purpose: crash loudly while developing, or let the model see the failure in production.
One AI message, two tool calls
ToolMessage name=get_weather content='Rainy, 27°C' tool_call_id=c0
ToolMessage name=calculate content='96' tool_call_id=c1
send_email (not in the list)
Error: send_email is not a valid tool, try one of [get_weather, calculate]. status=error
get_weather with {"town": "Mumbai"}
Error invoking tool 'get_weather' with kwargs {'town': 'Mumbai'} with error:
city: Field required Please fix the error and try again. status=error
A tool that raises TimeoutError
ToolNode(tools) -> TimeoutError: service timed out (run stops)
ToolNode(tools, handle_tool_errors=True) -> Error: TimeoutError('service timed out')
Please fix your mistakes. status=error
ToolNode(tools).invoke(...) outside a graph
ValueError: Missing required config key 'N/A' for 'tools'.Watch out: By default, a tool’s own exception ends the run. Catch errors inside the tool, or pass handle_tool_errors=True, before a flaky API reaches production.
Example 2 - llama3 through ToolNode
ToolNode does not care WHERE a tool call comes from - only that the last AI message has one. So for llama3:
- The agent asks llama3 for a structured Step (action + input), as in Lesson 3.4.
- It turns the conversation into a short transcript for llama3: Question, Action, Result lines.
- If the action is a tool, it builds a real tool call and wraps it in an AIMessage.
- If the action is final_answer, it returns a normal AIMessage with the text.
- ToolNode and tools_condition are exactly the same as in Example 1.
import uuid
from typing import Literal
from langchain_core.messages import AIMessage
from pydantic import BaseModel, Field
class Step(BaseModel):
action: Literal["get_weather", "calculate", "final_answer"]
action_input: str = Field(description="The city name, the arithmetic expression, or the final answer text")
ARGUMENT = {"get_weather": "city", "calculate": "expression"}
decide = ChatOllama(model="llama3", temperature=0).with_structured_output(Step)
SYSTEM = (
"You answer questions using tools: get_weather(city) and calculate(expression). Choose ONE next action. "
"Use a tool for each piece of information you do not have yet. "
"When the tool results contain everything needed, reply with final_answer."
)
def agent(state: MessagesState):
transcript = []
for m in state["messages"]:
if m.type == "human":
transcript.append(f"Question: {m.content}")
elif m.type == "ai" and m.tool_calls:
call = m.tool_calls[0]
transcript.append(f"Action: {call['name']}({list(call['args'].values())[0]!r})")
elif m.type == "tool":
transcript.append(f"Result: {m.content}")
step = decide.invoke([("system", SYSTEM), ("human", "\n".join(transcript))])
if step.action == "final_answer":
return {"messages": [AIMessage(content=step.action_input)]}
call = {"name": step.action, "args": {ARGUMENT[step.action]: step.action_input},
"id": f"call_{uuid.uuid4().hex[:8]}"}
return {"messages": [AIMessage(content="", tool_calls=[call])]} # a real tool call for ToolNode
# Same graph as above: ToolNode([get_weather, calculate]) and tools_condition, unchanged.Should I bring an umbrella in Mumbai, and what's 12 * 8? (4.2 s)
ai get_weather {'city': 'Mumbai'}
tool Rainy, 27°C
ai calculate {'expression': '12 * 8'}
tool 96
ai Yes, bring an umbrella in Mumbai. The answer to 12 * 8 is 96.
What is the weather in Hyderabad? (10.3 s)
ai get_weather {'city': 'Hyderabad'} tool Cloudy, 29°C
ai get_weather {'city': 'Hyderabad'} tool Cloudy, 29°C <- repeated
ai get_weather {'city': 'Hyderabad'} tool Cloudy, 29°C <- repeated
ai The weather in Hyderabad is Cloudy, 29°C.Reading Example 2
- The umbrella question worked: weather, then the calculation, then the answer - in 4.2 seconds.
- The Hyderabad question repeated get_weather three times (10.3 s). It is the same habit we saw in Lesson 3.4.
- A repeat guard placed before ToolNode would catch it - another reason to own the graph.
Three levels: create_agent, ToolNode, or your own node
More ready-made at the top, more control at the bottom:
- Use create_agent when the standard loop is all you need.
- Use ToolNode when you want to change the loop: add a check, a human approval, or a repeat guard before tools run.
- Write your own tools node when running the tools itself is unusual.
create_agent(model, tools)The whole loop, ready-made (Lesson 2.7). Least code, least control.StateGraph + ToolNode + tools_conditionYou own the graph; running the tools is ready-made.StateGraph + your own tools nodeYou own everything, including running the tools (Lesson 3.4).Tools are actions - be careful
- ToolNode runs whatever the model asks for from your list. A send_email or delete_file tool runs just as easily as get_weather.
- Check the arguments inside each tool.
- Check permissions from your own session - never from arguments the model wrote.
- Put a confirmation in front of anything that cannot be undone. Lesson 3.7 adds human approval as a graph node.
ToolNode at a glance
ToolNodeRuns the tool calls in the last AI message.
from langgraph.prebuilt import ToolNode
tools_conditionRouter: "tools" if there are tool calls, else "__end__".
add_conditional_edges("agent", tools_condition)MessagesStateState with an appending messages list.
StateGraph(MessagesState)
bind_toolsGive a tool-calling model the schemas.
model.bind_tools(tools)
ToolMessageOne result per call, linked by tool_call_id.
message.tool_call_id
handle_tool_errorsTurn tool exceptions into error messages.
ToolNode(tools, handle_tool_errors=True)
Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Add calculate to tools and ask a question that needs both. Count the ToolMessages.”
“Script an AI message calling send_email, then one with the wrong argument name. Read both ToolMessages.”
“Make a tool raise an exception, run it, then pass handle_tool_errors=True and run it again.”
“Replace tools_condition with your own should_continue and rename the node "executor" using a path map.”
“Add a node before ToolNode that skips a tool call already in the history - the 3.4 repeat guard.”
What usually goes wrong
ToolNode knows the tools; the model must too, or it never requests them.
✗ model.invoke(state["messages"])✓ model.bind_tools(tools).invoke(state["messages"])It only executes tool calls already in the last AI message. The agent node calls the model.
Without tools -> agent the model never sees the results.
✗ builder.add_edge("tools", END)✓ builder.add_edge("tools", "agent")By default a tool’s exception stops the run. Handle errors in the tool or set handle_tool_errors=True.
✗ ToolNode(tools)✓ ToolNode(tools, handle_tool_errors=True)Tool calls and results must accumulate. Use MessagesState so updates append.
✗ class State(TypedDict):
messages: list✓ StateGraph(MessagesState)Key points
- ToolNode runs the tool calls in the last AI message and returns one ToolMessage per call.
- It must run inside a graph, and it never calls the model.
- MessagesState appends messages, so the conversation is the state.
- tools_condition routes to "tools" or "__end__"; name the node "tools".
- Unknown tools and bad arguments become error messages; tool exceptions stop the run unless handle_tool_errors=True.
- The model must produce tool calls - llama3 cannot, but structured output can be turned into them.
- create_agent builds this graph for you; ToolNode lets you change it.
Quick check before you move on
Quiz
- 1.
The model calls send_email, which ToolNode does not have. What happens?
- 2.
A tool raises TimeoutError. What happens by default, and how do you change it?
- 3.
Why can the agent node return only the new message?
- 4.
How did llama3 drive ToolNode without tool calling?
Interview questions
What is ToolNode, and what is the difference between a tool and a ToolNode?
A tool performs an operation. ToolNode is the graph node that executes the tool calls a model requested, from a registered list, and returns the results as ToolMessages.
How does a tool-calling graph work?
The agent node calls a model bound to the tools; tools_condition routes to ToolNode if the AI message has tool calls, else to END; ToolNode executes and appends ToolMessages; an edge returns to the agent.
How does ToolNode handle errors?
Unknown tools and invalid arguments become error ToolMessages the model can correct. Exceptions raised inside a tool propagate unless handle_tool_errors is set.
Why use ToolNode instead of create_agent?
To own the graph - add validation, approval, repeat guards or special routing around tool execution - while still using prebuilt execution.
Does adding ToolNode make any model able to use tools?
No. Something must produce tool calls: a tool-calling model, or structured output converted into tool calls by your agent node.
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...