Built-In Tools: Search, Code, Calculator
LangChain Built-In Tools: What You Get Without Building
LangChain ships with an extensive library of pre-built tools for common agent tasks. Before writing custom tools, know what's available — most common needs (search, code execution, file operations, APIs) are already implemented.
Setting Up an Agent with Tools
The modern way to use tools in LangChain is with the tool-calling agent:
from langchain_openai import ChatOpenAI
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
llm = ChatOpenAI(model="gpt-4o", temperature=0)
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant. Use tools to answer questions accurately."),
MessagesPlaceholder(variable_name="chat_history"),
("human", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"), # Required for tool calls
])
def create_agent(tools: list):
agent = create_tool_calling_agent(llm, tools, prompt)
return AgentExecutor(
agent=agent,
tools=tools,
verbose=True, # Print each step
max_iterations=10, # Prevent infinite loops
handle_parsing_errors=True
)
Search Tools
Tavily Search (Recommended)
Best quality real-time web search for agents:
from langchain_community.tools.tavily_search import TavilySearchResults
search = TavilySearchResults(
max_results=5, # Number of results
search_depth="advanced", # "basic" or "advanced"
include_answer=True, # Include Tavily's AI-generated summary
include_raw_content=False
)
# Test it directly
results = search.invoke("latest developments in AI agents 2025")
# Use in agent
agent = create_agent([search])
response = agent.invoke({
"input": "What is the current situation with AI regulation in the EU?",
"chat_history": []
})
DuckDuckGo Search (Free Alternative)
from langchain_community.tools import DuckDuckGoSearchRun, DuckDuckGoSearchResults
# Simple version (returns string)
search_simple = DuckDuckGoSearchRun()
# Structured version (returns list of results with metadata)
search_results = DuckDuckGoSearchResults(num_results=5)
agent = create_agent([search_simple])
Wikipedia
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=2000
)
)
result = wikipedia.invoke("Large Language Model")
Code Execution Tools
Python REPL
Lets the agent write and execute Python code — powerful for calculations, data analysis, and algorithmic tasks:
from langchain_experimental.tools import PythonREPLTool
python_repl = PythonREPLTool()
# Test directly
result = python_repl.invoke("""
import statistics
data = [23, 45, 67, 12, 89, 34, 56]
print(f"Mean: {statistics.mean(data):.2f}")
print(f"Median: {statistics.median(data):.2f}")
print(f"Stdev: {statistics.stdev(data):.2f}")
""")
# In an agent — the agent decides when to write and run code
agent = create_agent([python_repl, search])
response = agent.invoke({
"input": "Calculate compound interest: $10,000 invested for 10 years at 7% annual rate",
"chat_history": []
})
Security warning: Python REPL executes arbitrary code. Only use in trusted environments. For production, use sandboxed execution (Docker container, isolated subprocess, or a service like E2B).
File System Tools
Read Files
from langchain_community.tools.file_management import ReadFileTool, WriteFileTool, ListDirectoryTool
read_tool = ReadFileTool()
write_tool = WriteFileTool()
list_dir = ListDirectoryTool()
file_tools = [read_tool, write_tool, list_dir]
agent = create_agent(file_tools)
response = agent.invoke({
"input": "Read the file 'data.csv' and tell me how many rows it has",
"chat_history": []
})
Retriever as Tool
Turn a vector store retriever into a tool:
from langchain.tools.retriever import create_retriever_tool
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import Chroma
embeddings = OpenAIEmbeddings()
vectorstore = Chroma(persist_directory="./docs_db", embedding_function=embeddings)
retriever_tool = create_retriever_tool(
retriever=vectorstore.as_retriever(search_kwargs={"k": 4}),
name="search_documentation",
description="Search the product documentation for information about features, APIs, and how to use the product. Use this whenever the user asks about how to do something with the product."
)
agent = create_agent([retriever_tool, search])
The description is critical — the LLM decides when to use this tool based entirely on the description. Write it clearly and specify exactly when to use it.
SQL Database Tool
Query a database with natural language:
from langchain_community.utilities import SQLDatabase
from langchain_community.agent_toolkits.sql.toolkit import SQLDatabaseToolkit
db = SQLDatabase.from_uri("sqlite:///customers.db")
# Or: SQLDatabase.from_uri("postgresql://user:pass@host:5432/dbname")
toolkit = SQLDatabaseToolkit(db=db, llm=llm)
tools = toolkit.get_tools()
agent = create_agent(tools)
response = agent.invoke({
"input": "How many customers signed up last month, and what's their average order value?",
"chat_history": []
})
The SQL toolkit includes tools for: listing tables, getting schema, running queries, and checking query validity.
HTTP Request Tool
Make API calls from within an agent:
from langchain_community.tools import RequestsGetTool, RequestsPostTool
from langchain_community.utilities import TextRequestsWrapper
requests_tools = [
RequestsGetTool(requests_wrapper=TextRequestsWrapper()),
RequestsPostTool(requests_wrapper=TextRequestsWrapper())
]
agent = create_agent(requests_tools)
response = agent.invoke({
"input": "Get the current Bitcoin price from the CoinGecko public API",
"chat_history": []
})
Combining Multiple Tools
Agents are most powerful when they can choose from a toolkit:
from langchain_community.tools import (
TavilySearchResults, WikipediaQueryRun, DuckDuckGoSearchRun
)
from langchain_experimental.tools import PythonREPLTool
from langchain.tools.retriever import create_retriever_tool
all_tools = [
TavilySearchResults(max_results=3),
WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(top_k_results=2)),
PythonREPLTool(),
retriever_tool,
]
agent = create_agent(all_tools)
# The agent figures out which tool(s) to use
response = agent.invoke({
"input": "Research the history of Python programming language, then calculate how many years it's been since its creation",
"chat_history": []
})
Tool Selection Best Practices
Descriptions drive tool selection: The LLM picks tools based entirely on their descriptions. Be specific:
- Bad:
description="Search for information" - Good:
description="Search the web for current events, recent news, and information not in the agent's training data. Use when you need up-to-date facts."
Limit the toolkit: Too many tools confuse the agent. Give it what it needs for the task, not every tool available.
Test tools directly first: Call tool.invoke() directly before putting it in an agent. Debug the tool, then debug the agent.
Log tool calls in production: Always track which tools are called and what they return — this is where most agent debugging happens.
Next lesson: Building custom tools — creating tools for your specific use cases.
Get this course's notes on Telegram!
Free cheat sheets, summaries & practice exercises