Working through this module?0 of 17 done
Module 09 · Page 10 of 20 · 10 sections

Tools in LangChain

What tools are, how a tool call flows, the tool types and popular built-ins, and how to create custom tools and use several with an agent.

9.1

What are Tools?

  • Tools allow LLMs to interact with external systems (APIs, databases, search engines, etc.).
  • LLMs can call tools to get real-time information, perform actions or execute code.
  • LangChain provides a standard interface to create, integrate and manage tools.
  • Tools are essential for building agents and real-world applications.
9.2

Why Use Tools?

  • Access real-time and external information.
  • Perform actions like search, calculation and API calls.
  • Extend LLM capabilities beyond training data.
  • Useful for building RAG, agents and automation.
  • Easily create custom tools.
  • Integrate with popular services (Google Search, Wikipedia, Python REPL, databases, etc.).
9.3

How Tools Work in LangChain

User Query
LLMDecides to use a tool
ToolExternal system / API / DB
Tool ResultReturns data to LLM
Final ResponseTo user
9.4

Types of Tools in LangChain

Tool TypeDescriptionUse Case
Built-in ToolsPre-built tools provided by LangChainSearch, Wikipedia, Python REPL, etc.
API ToolsCall external APIsWeather, finance, custom APIs
Database ToolsInteract with databasesQuery MySQL, PostgreSQL, etc.
Custom ToolsCreate your own tool using a functionBusiness logic, internal services
ToolkitsCollection of related toolsSerpAPI toolkit, SQL toolkit, etc.
9.5

Popular Built-in Tools

  • SerpAPIWrapper - Google Search
  • WikipediaQueryRun - Wikipedia search
  • PythonREPLTool - Execute Python code
  • RequestsToolkit - Make HTTP requests
  • SQLDatabaseToolkit - Work with SQL databases
  • ArxivQueryRun - Search research papers
  • DuckDuckGoSearchRun - Web search (open source)
  • OpenWeatherMap - Weather information
  • ... and many more via the LangChain community
9.6

Creating a Custom Tool

  • Define a function with input and output.
  • Use the @tool decorator or BaseTool.
  • Provide a clear description for the LLM.
  • It can be used with agents or chains.
9.7

Example 1: SerpAPI Google Search Tool

python
from langchain.agents import initialize_agent, AgentType
from langchain_community.utilities import SerpAPIWrapper
from langchain.tools import Tool
from langchain_openai import ChatOpenAI

# Initialize LLM
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.7)

# Create search tool
search = SerpAPIWrapper()
tools = [Tool(
    name="Google Search",
    func=search.run,
    description="Search the internet for latest information")
]
# Initialize agent
agent = initialize_agent(tools, llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True)

response = agent.invoke({"input": "Who won the IPL 2024?"})
print(response["output"])
9.8

Example 2: Custom Tool (Calculator)

python
from langchain.tools import tool
from langchain.agents import initialize_agent, AgentType
from langchain_openai import ChatOpenAI

@tool
def calculator(expression: str) -> str:
    """Useful for mathematical calculations.
    Input should be a valid Python expression."""
    try:
        return str(eval(expression))
    except Exception as e:
        return f"Error: {str(e)}"

llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.7)
tools = [calculator]

agent = initialize_agent(tools, llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True)

response = agent.invoke({"input": "What is 25 * 4 + 10?"})
print(response["output"])
9.9

Example 3: Using Multiple Tools with an Agent

python
from langchain_community.utilities import SerpAPIWrapper
from langchain.tools import Tool

search_tool = Tool(name="Search", func=SerpAPIWrapper().run,
    description="Search the internet")
calc_tool = calculator  # from previous example

tools = [search_tool, calc_tool]
agent = initialize_agent(tools, llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True)
9.10

Key Takeaways

  • Tools extend LLM capabilities to real-world applications.
  • Use built-in tools for common tasks.
  • Create custom tools for business-specific needs.
  • Tools are the building blocks for powerful agents.
  • Provide clear descriptions for better tool selection.
  • Combine multiple tools for complex workflows.
  • Experiment with different tools and use cases.