Custom Tools & Function Calling
By default, Large Language Models are isolated neural networks unable to access real-time data, run math without arithmetic errors, or interact with external software.Tools empower LLMs to browse the live internet, query relational databases, call REST APIs, and execute arbitrary code.
1. Defining Custom Tools with @tool
In modern LangChain, any Python function can be converted into an LLM-callable tool using the@tool decorator. The function’s type annotations and docstring are automatically converted into the JSON Schema used by the model for function calling:
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
# Define custom tool with detailed docstring and type hints
@tool
def calculate_compound_interest(principal: float, annual_rate: float, years: int) -> float:
"""
Calculates total future value using compound interest formula A = P(1 + r)^t.
Args:
principal: Initial invested dollar amount (e.g. 10000.0)
annual_rate: Annual interest rate as a decimal (e.g. 0.08 for 8%)
years: Number of years the money is invested
"""
return round(principal * ((1 + annual_rate) ** years), 2)
@tool
def check_server_uptime(server_hostname: str) -> str:
"""Checks the simulated health and uptime metrics of an internal cloud server."""
# Simulated internal network ping
return f"Server {server_hostname} is HEALTHY. CPU load: 24%. Uptime: 42 days."2. Binding Tools to ChatModels with bind_tools
Once tools are defined, bind them to your ChatModel using bind_tools():
tools = [calculate_compound_interest, check_server_uptime]
llm = ChatOpenAI(model="gpt-4o", temperature=0)
# Bind tool schemas into model's API parameters
llm_with_tools = llm.bind_tools(tools)
# Ask a query requiring arithmetic calculation
response = llm_with_tools.invoke("How much will $15,000 grow to in 10 years at a 7.5% annual return?")
# The model decides to invoke the tool instead of guessing!
print("Tool Calls Generated by LLM:")
for tc in response.tool_calls:
print(f"- Tool: {tc['name']}")
print(f"- Extracted Arguments: {tc['args']}")3. Live Web Search with Tavily Search Tool
Tavily is the search engine optimized specifically for LLMs, returning pre-filtered, concise factual text without HTML clutter or cookie banners:
# Install: pip install langchain-community tavily-python
from langchain_community.tools.tavily_search import TavilySearchResults
# Initialize Tavily search tool (returns top 3 search snippets)
search_tool = TavilySearchResults(max_results=3)
# The model can now search for events after its knowledge cutoff!
search_enabled_llm = llm.bind_tools([search_tool])
query_res = search_enabled_llm.invoke("What are the latest updates in LangChain v0.3 release?")
print(query_res.tool_calls)Explore Related Tools
Hand-picked utilities and calculators related to this tool.
