Working through this module?
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.
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.
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.).
How Tools Work in LangChain
User Query
LLMDecides to use a tool
ToolExternal system / API / DB
Tool ResultReturns data to LLM
Final ResponseTo user
Types of Tools in LangChain
| Tool Type | Description | Use Case |
|---|---|---|
| Built-in Tools | Pre-built tools provided by LangChain | Search, Wikipedia, Python REPL, etc. |
| API Tools | Call external APIs | Weather, finance, custom APIs |
| Database Tools | Interact with databases | Query MySQL, PostgreSQL, etc. |
| Custom Tools | Create your own tool using a function | Business logic, internal services |
| Toolkits | Collection of related tools | SerpAPI toolkit, SQL toolkit, etc. |
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
Creating a Custom Tool
- Define a function with input and output.
- Use the
@tooldecorator orBaseTool. - Provide a clear description for the LLM.
- It can be used with agents or chains.
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"])
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"])
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)
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.