Tools

Open in ColabOpen in GitHub

OverView

A tool is an interface that allows agents, chains, or LLMs to interact with the external world.

LangChain provides built-in tools that are easy to use, and it also enables users to easily build custom tools.

You can find the list of tools integrated into LangChain at the link below.

Table of Contents

References


Environment Setup

Set up the environment. You may refer to Environment Setup for more details.

[Note]

  • langchain-opentutorial is a package that provides a set of easy-to-use environment setup, useful functions and utilities for tutorials.

  • You can checkout the langchain-opentutorial for more details.

Environment variables have been set successfully. You can alternatively set API keys, such as OPENAI_API_KEY in a .env file and load them.

[Note] This is not necessary if you've already set the required API keys in previous steps.

Note

When using tools, warning messages may be displayed.

For example, there are security warnings in the REPL environment.PythonREPLTool is a tool for executing Python code and can potentially execute commands (e.g., file system access, network requests) that may pose security risks. In such cases, LangChain or Python itself may output warning messages.

To ignore these warning messages, you can use the following code:

Built-in tools

You can use pre-defined tools and toolkits provided by LangChain.

A tool refers to a single utility, while a toolkit combines multiple tools that can be used as one.

You can find the relevant tools at the link below.

Note

Python REPL Tool

This tool provides a class for executing Python code in a REPL (Read-Eval-Print Loop) environment.

Description

  • Provides a Python shell environment.

  • Executes valid Python commands as input.

  • Use the print(...) function to view results.

Key Features

  • sanitize_input: Option to sanitize input (default: True)

  • python_repl: Instance of PythonREPL (default: executed in the global scope)

Usage

  • Create an instance of PythonREPLTool .

  • Execute Python code using the run , arun , or invoke methods.

Input Sanitization

  • Removes unnecessary spaces, backticks, the keyword "python," and other extraneous elements from the input string.

Below is an example of requesting an LLM to write Python code and returning the results.

Workflow Summary

  1. Request the LLM model to write Python code for a specific task.

  2. Execute the generated code to obtain the results.

  3. Output the results.

Note

I recommend using a model equivalent to or higher than GPT-4.

Search API Tool(Tavily)

This is a tool that implements a search function using the Tavily Search API. It provides two main classes: TavilySearchResults and TavilyAnswer .

API Key Issuance URL

Set the issued API key as an environment variable.

For example, configure the .env file as follows:

TavilySearchResults

Description

  • Calls the Tavily Search API and returns results in JSON format.

  • A search engine optimized for comprehensive, accurate, and reliable results.

  • Useful for answering questions about current events.

Key Parameters

  • max_results (int): Max search results to return(default: 5).

  • search_depth (str): The depth of the search("basic" or "advanced").

  • include_domains (List[str]): A list of domains to specifically include in the search results.

  • exclude_domains (List[str]): A list of domains to specifically exclude from the search results.

  • include_answer (bool): Include a short answer to original query in the search results(defalut: False).

  • include_raw_content (bool): Include cleaned and parsed HTML of each site search results(defalut: False).

  • include_images (bool): Include a list of query related images in the response.(defalut: False)

Return Value

  • A JSON-formatted string containing the search results (url, content).

Image Generation Tool (DALL-E)

  • DallEAPIWrapper Class : A wrapper for OpenAI's DALL-E image generator.

This tool allows easy integration of the DALL-E API to implement text-based image generation functionality. With various configuration options, it can be utilized as a flexible and powerful image generation tool.

Key Properties

  • model : The name of the DALL-E model to use ( dall-e-2, dall-e-3 ).

  • n : Number of images to generate (default: 1).

  • size : Size of the generated image:

    • "dall-e-2": "1024x1024", "512x512", "256x256"

    • "dall-e-3": "1024x1024", "1792x1024", "1024x1792"

  • style : Style of the generated image ( natural , vivid ).

  • quality : Quality of the generated image ( standard, hd ).

  • max_retries : Maximum number of retries for generation.

Key Features

  • Generates images based on text descriptions using the DALL-E API.

Workflow Summary

The following is an example of generating images using the DALL-E Image Generator.

This time, we will use the DallEAPIWrapper to generate images.

The input prompt will request the LLM model to write a prompt for generating images.

Let’s use the previously generated image prompt as input to the DallEAPIWrapper to generate an image.

The image below was generated by DALL-E.

dall-e_image.png

Custom Tools

In addition to the built-in tools provided by LangChain, you can define and use your own custom tools.

To do this, use the @tool decorator provided by the langchain.tools module to convert a function into a tool.

@tool Decorator

This decorator allows you to transform a function into a tool. It provides various options to customize the behavior of the tool.

How to Use

  1. Apply the @tool decorator above the function.

  2. Set the decorator parameters as needed.

Using this decorator, you can easily convert regular Python functions into powerful tools, enabling automated documentation and flexible interface creation.

Tavily Custom Tool: Enhancing Tool Control through Custom Tool Configuration

By using @tool Decorator , you can create a tool with improved control by leveraging the TavilyClient provided by the Tavily package.

Below are the key parameters used in the Tavily.

Basic Search Configuration

  • query (str): The keyword or phrase to search for.

  • search_depth (str): The level of detail for the search. Choose between basic or advanced . (default: basic)

  • topic (str): The topic area of the search. Choose between general or news . (default: general)

  • days (int): The recency of search results. Only results within the specified number of days will be returned. (default: 3)

  • max_results (int): The maximum number of search results to retrieve. (default: 5)

Domain Filtering

  • include_domains (list): A list of domains that must be included in the search results.

  • exclude_domains (list): A list of domains to exclude from the search results.

Detailed Result Settings

  • include_answer (bool): Whether to include answers generated by the API.

  • include_raw_content (bool): Whether to include the original HTML content of the webpage.

  • include_images (bool): Whether to include related image information.

  • format_output (bool): Whether to apply formatting to the search results.

Miscellaneous

  • kwargs : Additional keyword arguments. These may be used for future API updates or special features.

The following example code performs a news search for the query "Tell me about LangChain".

The search conditions used are a maximum of 10 results, within the last 7 days, advanced search, and general topic.

The following example code performs a news search for the query "Latest AI technology trends".

The search conditions used are a maximum of 5 results, within the last 3 days, basic search, and news topic.

The following example code performs a search for the query "Python programming tips".

The search conditions used are a maximum of 3 results, advanced search, and results only from the github.io domain.

The following example code performs a search for the query "Healthy diet".

The search conditions used are a maximum of 7 results, within the last 30 days, basic search, and excluding the domains ads.com and spam.com.

Creating a Custom Tool for Google News Article Search

Implementing a Custom Tool in LangGraph is not just about using basic functionalities; it is a crucial strategy to meet project-specific requirements while optimizing system flexibility, scalability, and performance.

In this example, we will build a Google News RSS-based custom tool and explain why it is a better alternative to LangChain’s existing Google Search Tool.

The LangChain Google Search Tool is suitable for searching the entire web, but it requires API calls, which may lead to usage-based costs. Additionally, since it relies on Google’s indexing, there may be delays in reflecting the latest news.

The Google News RSS-based custom tool is more suitable for quickly retrieving only the latest news. It provides real-time news without relying on Google’s indexing, is free to use without an API key, and offers more intuitive region and language filtering.

Now, let's implement the Google News search functionality by defining the GoogleNews class, which will serve as a tool to search for Google News articles.

Note

  • No API key is required (because it uses RSS feeds).

This tool searches for news articles provided by news.google.com .

Description

  • Uses the Google News search API to retrieve the latest news.

  • Allows searching for news based on keywords.

Key Parameters

  • k (int): Maximum number of search results to return (default: 5).

In the code, you can adjust the search results' language and region by modifying the language (hl), region (gl), and region and language code (ceid).

Note

Save the provided code as google_news.py , and then you can import it in other files using from google_news import GoogleNews .

Last updated