| name | langchain-tools |
| description | Guide to using tool integrations in LangChain including pre-built toolkits, Tavily, Wikipedia, and custom tools |
| language | python |
langchain-tools (Python)
Overview
Tools enable LLMs to interact with external systems, perform calculations, search the web, query databases, and more. They extend model capabilities beyond text generation, making agents truly actionable.
Key Concepts
- Tools: Functions that agents can call to perform specific tasks
- Tool Calling: Models decide when and how to use tools based on user queries
- Toolkits: Collections of related tools
- Tool Schema: Describes tool parameters using Pydantic models
Tool Selection Decision Table
| Tool/Toolkit | Best For | Package | Key Features |
|---|
| Tavily Search | Web search | langchain-community | AI-optimized search API |
| Wikipedia | Encyclopedia queries | langchain-community | Wikipedia API access |
| DuckDuckGo Search | Privacy-focused search | langchain-community | No API key needed |
| ArXiv | Academic papers | langchain-community | Research paper search |
| Vector Store Tools | Semantic search | Based on vector store | Query your data |
| Custom Tools | Your specific needs | langchain-core | Define any function |
When to Choose Each Tool
Choose Tavily if:
- You need high-quality web search
- You want AI-optimized results
- You're building research/RAG applications
Choose Wikipedia if:
- You need encyclopedic knowledge
- Factual information is required
- Free, no API key needed
Choose Custom Tools if:
- You have specific business logic
- You need to integrate proprietary systems
- Built-in tools don't meet your needs
Code Examples
Tavily Search Tool
from langchain_community.tools.tavily_search import TavilySearchResults
import os
search_tool = TavilySearchResults(
max_results=3,
api_key=os.getenv("TAVILY_API_KEY"),
)
results = search_tool.invoke("Latest AI news")
print(results)
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
model = ChatOpenAI(model="gpt-4")
agent = create_react_agent(model, [search_tool])
response = agent.invoke({
"messages": [{"role": "user", "content": "What's new in AI today?"}]
})
Wikipedia Tool
from langchain_community.tools import WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapper
wikipedia = WikipediaQueryRun(
api_wrapper=WikipediaAPIWrapper(
top_k_results=3,
doc_content_chars_max=4000,
)
)
result = wikipedia.invoke("Artificial Intelligence")
print(result)
DuckDuckGo Search (No API Key)
from langchain_community.tools import DuckDuckGoSearchRun
search_tool = DuckDuckGoSearchRun()
results = search_tool.invoke("LangChain framework")
print(results)
from langchain_community.tools import DuckDuckGoSearchResults
search_tool = DuckDuckGoSearchResults(max_results=5)
results = search_tool.invoke("Python programming")
ArXiv Tool
from langchain_community.tools import ArxivQueryRun
arxiv_tool = ArxivQueryRun()
results = arxiv_tool.invoke("large language models")
print(results)
Custom Tool with @tool Decorator
from langchain_core.tools import tool
from typing import Optional
@tool
def get_weather(location: str, unit: Optional[str] = "celsius") -> str:
"""Get the current weather for a location.
Args:
location: The city name, e.g., 'San Francisco'
unit: Temperature unit, either 'celsius' or 'fahrenheit'
"""
data = fetch_weather(location, unit)
return f"The weather in {location} is {data['temp']}°{unit[0].upper()}"
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
model = ChatOpenAI(model="gpt-4")
agent = create_react_agent(model, [get_weather])
response = agent.invoke({
"messages": [{"role": "user", "content": "What's the weather in London?"}]
})
Custom Tool with Pydantic Schema
from langchain_core.tools import tool
from pydantic import BaseModel, Field
class WeatherInput(BaseModel):
location: str = Field(description="The city name")
unit: str = Field(default="celsius", description="Temperature unit")
@tool("get_weather", args_schema=WeatherInput)
def get_weather(location: str, unit: str = "celsius") -> str:
"""Get the current weather for a location."""
return f"Weather in {location}: 72°{unit[0].upper()}"
Custom Tool - Class-Based
from langchain_core.tools import BaseTool
from pydantic import BaseModel, Field
from typing import Type
class DatabaseInput(BaseModel):
customer_id: str = Field(description="Customer ID to look up")
class DatabaseQueryTool(BaseTool):
name: str = "database_query"
description: str = "Query the customer database for information"
args_schema: Type[BaseModel] = DatabaseInput
def _run(self, customer_id: str) -> str:
"""Use the tool."""
customer = db.get_customer(customer_id)
return str(customer)
async def _arun(self, customer_id: str) -> str:
"""Async version."""
raise NotImplementedError("Async not implemented")
db_tool = DatabaseQueryTool()
Vector Store as Tool
from langchain_core.tools import create_retriever_tool
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_openai import OpenAIEmbeddings
vectorstore = InMemoryVectorStore.from_texts(
["LangChain is a framework...", "Agents use tools..."],
embedding=OpenAIEmbeddings(),
)
retriever_tool = create_retriever_tool(
vectorstore.as_retriever(),
name="knowledge_base",
description="Search the knowledge base for information about LangChain",
)
from langgraph.prebuilt import create_react_agent
agent = create_react_agent(model, [retriever_tool])
Multiple Tools Example
from langchain_openai import ChatOpenAI
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.tools import tool
from langgraph.prebuilt import create_react_agent
search_tool = TavilySearchResults(max_results=3)
@tool
def calculator(expression: str) -> str:
"""Evaluate a mathematical expression.
Args:
expression: A mathematical expression to evaluate (e.g., "2 + 2")
"""
try:
result = eval(expression)
return str(result)
except Exception as e:
return f"Error: {str(e)}"
@tool
def custom_lookup(query: str) -> str:
"""Look up custom information.
Args:
query: The query to look up
"""
return f"Custom result for: {query}"
agent = create_react_agent(
ChatOpenAI(model="gpt-4"),
[search_tool, calculator, custom_lookup],
)
response = agent.invoke({
"messages": [{
"role": "user",
"content": "Search for the population of Tokyo and calculate if it doubled"
}]
})
Tool with Error Handling
from langchain_core.tools import tool
import requests
@tool
def api_call(endpoint: str) -> str:
"""Call external API.
Args:
endpoint: API endpoint to call
"""
try:
response = requests.get(f"https://api.example.com/{endpoint}")
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
return f"API error: {str(e)}"
Toolkits
from langchain_community.agent_toolkits import SQLDatabaseToolkit
from langchain_community.utilities import SQLDatabase
db = SQLDatabase.from_uri("sqlite:///example.db")
toolkit = SQLDatabaseToolkit(db=db, llm=model)
tools = toolkit.get_tools()
agent = create_react_agent(model, tools)
Boundaries
What Agents CAN Do
✅ Use pre-built tools
- Tavily search, Wikipedia, DuckDuckGo
- ArXiv, calculators, web browsers
- Any tool from LangChain community
✅ Create custom tools
- Define functions with @tool decorator
- Implement class-based tools
- Convert retrievers to tools
✅ Combine multiple tools
- Give agents access to many tools
- Let models choose appropriate tools
- Chain tool calls
✅ Handle tool responses
- Parse tool output
- Use results in conversation
- Error handling
What Agents CANNOT Do
❌ Execute arbitrary code safely
- Cannot run untrusted code
- Need sandboxing for code execution
❌ Bypass authentication
- Tools need proper API keys
- Cannot access protected resources without credentials
❌ Guarantee tool selection
- Model decides which tool to use
- Cannot force specific tool usage (without prompting)
Gotchas
1. Import from Correct Package
from langchain.tools import WikipediaQueryRun
from langchain_community.tools import WikipediaQueryRun
Fix: Use langchain-community for tools.
2. API Keys Required
tool = TavilySearchResults()
tool.invoke("query")
import os
tool = TavilySearchResults(api_key=os.getenv("TAVILY_API_KEY"))
Fix: Set required API keys in environment variables.
3. Model Must Support Tools
model = ChatOpenAI(model="gpt-3.5-turbo-instruct")
model = ChatOpenAI(model="gpt-4")
Fix: Use models that support function calling.
4. Tool Description Matters
@tool
def tool1(x: int) -> int:
"""A tool"""
return x * 2
@tool
def double_number(number: int) -> int:
"""Multiply a number by 2. Use this when the user wants to double a value.
Args:
number: The number to double
"""
return number * 2
Fix: Write clear docstrings that help the model know when to use the tool.
5. Type Hints Required
@tool
def my_tool(x):
return x
@tool
def my_tool(x: str) -> str:
"""Process input.
Args:
x: Input string
"""
return x.upper()
Fix: Always include type hints for tool parameters.
Links and Resources
Official Documentation
Package Installation
pip install langchain-community
pip install tavily-python
pip install wikipedia
pip install duckduckgo-search