10. How to call a tool using ToolNode

In this tutorial, LangGraph's pre-built for calling tools pre-built of ToolNode Covers how to use it.

ToolNode Is LangChain Runnable, which takes the graph status with a list of messages as input and updates the status as a result of the tool call.

It is designed for immediate use with LangGraph's pre-built Agent, and has a suitable redo for the state. messages All keys included StateGraph Can work with

Copy

# Configuration file for managing API keys as environment variables
from dotenv import load_dotenv

# Load API key information
load_dotenv()

Copy

 True 

Copy

# Set up LangSmith tracking. https://smith.langchain.com
# !pip install -qU langchain-teddynote
from langchain_teddynote import logging

# Enter a project name.
logging.langsmith("CH17-LangGraph-Modules")

Copy

Tool definition

First, let's define the tools.

Copy

Next ToolNode Let's look at how to call the tool using.

Copy

ToolNode Calling manually

ToolNode works in graph state with message list.

  • important : At this time, the last message in the list tool_calls Contains properties AIMessage Should be.

First, let's look at how to manually call the tool node.

Copy

Copy

Generally AIMessage There is no need to create manually, it is automatically generated by all LangChain chat models that support tool calls.

Also AIMessage of tool_calls If you pass multiple tool calls to the parameter ToolNode You can use to make parallel tool calls.

Copy

Copy

for use with llm

In order to use a chat model with a tool call function, you must first ensure that the model recognizes the available tools.

This is ChatOpenAI In the model .bind_tools This is done by calling the method.

Copy

Copy

Copy

As you can see, the AI message generated by the chat model already tool_calls Because it is stuffed, ToolNode You can pass it directly to.

Copy

Copy

Use with Agent

Next, within the LangGraph graph ToolNode Let's look at how to use.

Let's set up a graph implementation for Agent. this Agent Receive the query as input and repeatedly call the tools until you get enough information to solve the query.

With the tools you just defined ToolNode And you will use the OpenAI model.

Copy

Copy

I'll run and check the results.

Copy

Copy

Copy

Copy

Copy

Copy

ToolNode It can also handle errors that occur during tool execution.

handle_tool_errors=True You can enable/disable this function by setting (it is enabled by default)

Last updated