LangChain Tutorial (Python): building custom tools for beginners
This tutorial shows you how to build a custom LangChain tool in Python, wire it into an agent, and test that the agent can call your tool correctly. You need this when the built-in tools are not enough and you want the model to interact with your own APIs, internal systems, or business logic.
What You'll Need
- •Python 3.10+
- •
langchain - •
langchain-openai - •
openaiAPI key - •Basic familiarity with LangChain agents
- •A terminal and virtual environment
Install the packages:
pip install langchain langchain-openai openai
Set your API key:
export OPENAI_API_KEY="your-api-key-here"
Step-by-Step
- •Start with a simple Python function that does one job well. For beginners, keep the tool deterministic and easy to test before connecting anything external.
from datetime import datetime
def get_current_time(timezone: str = "UTC") -> str:
"""Return the current time for a given timezone label."""
now = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
return f"Current time in {timezone}: {now} UTC"
- •Wrap that function as a LangChain tool using
@tool. This decorator turns a normal Python function into something an agent can call.
from langchain_core.tools import tool
@tool
def get_current_time(timezone: str = "UTC") -> str:
"""Return the current time for a given timezone label."""
from datetime import datetime
now = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
return f"Current time in {timezone}: {now} UTC"
print(get_current_time.name)
print(get_current_time.description)
- •Add a second custom tool so you can see how agents choose between tools. A good beginner pattern is to build tools around small business rules, not broad “do everything” functions.
from langchain_core.tools import tool
@tool
def calculate_simple_interest(principal: float, rate: float, years: float) -> str:
"""Calculate simple interest using principal, rate, and years."""
interest = principal * rate * years
total = principal + interest
return f"Interest: {interest:.2f}, Total: {total:.2f}"
print(calculate_simple_interest.invoke({
"principal": 1000,
"rate": 0.05,
"years": 2
}))
- •Put both tools into an agent. Use a chat model that supports tool calling, then let the agent decide when to invoke your custom code.
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-mini", temperature=0)
tools = [get_current_time, calculate_simple_interest]
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant that uses tools when needed."),
("human", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
])
agent = create_tool_calling_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
- •Run the agent with prompts that should trigger each tool. Keep the questions specific so it is obvious whether the model used your custom logic or answered from memory.
result_1 = executor.invoke({
"input": "What is the current time in Nairobi?"
})
result_2 = executor.invoke({
"input": "Calculate simple interest for principal 5000, rate 0.08, and 3 years."
})
print(result_1["output"])
print(result_2["output"])
Testing It
Run the script and watch the verbose logs from AgentExecutor. You should see the agent deciding to call either get_current_time or calculate_simple_interest instead of answering directly.
If the output looks wrong, check three things first: your API key is set, the model name is valid for your account, and your tool signatures use typed arguments. Tool calls fail most often because of bad input shapes or missing imports.
For better validation, try prompts that are clearly tool-shaped:
- •“Calculate simple interest for principal 12000, rate 0.12, and 1.5 years.”
- •“What is the current time in UTC?”
- •“Use both tools if needed.”
If those work consistently, your custom tool setup is correct.
Next Steps
- •Add structured inputs with Pydantic models for more complex tools.
- •Wrap real services like internal REST APIs or database queries.
- •Learn how to handle tool errors and retries inside agents.
Keep learning
- •The complete AI Agents Roadmap — my full 8-step breakdown
- •Free: The AI Agent Starter Kit — PDF checklist + starter code
- •Work with me — I build AI for banks and insurance companies
By Cyprian Aarons, AI Consultant at Topiax.
Want the complete 8-step roadmap?
Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.
Get the Starter Kit