Calculator Tool
Creating Custom Tools used HTML lookup functions. A calculator is the same idea: register @tool, let Python evaluate the expression string.
Python does the math
24 * 17 is easy to get wrong once you stack parentheses and division. Point the agent at a calculator tool so the answer comes from eval on a whitelisted string, not from the model doing arithmetic.
No tool
24 × 17 = ? can slip on bigger expressions
calculator
calculator("24*17")
returns 408
from Pythonmultiply for a single op. This tool takes a full expression string.calculator @tool
One arg: expression. Allow only digits and +-*/(). Return an error string if something else shows up.
Real apps should parse with something safer than eval. The whitelist is enough for this demo.
from langchain.tools import tool
ALLOWED = set("0123456789+-*/(). ")
def run_expression(expression: str) -> str:
expr = expression.strip()
if not expr or not all(ch in ALLOWED for ch in expr):
return "Only numbers and + - * / ( ) allowed"
return str(eval(expr, {"__builtins__": {}}, {}))
@tool("calculator")
def calculator(expression: str) -> str:
"""Evaluate a math expression with +, -, *, / and parentheses."""
return run_expression(expression)When calculator runs:
create_agent
tools=[calculator]. Nothing else changes from the last few lessons.
from langchain.agents import create_agent
agent = create_agent(model="openai:gpt-4o-mini", tools=[calculator])
result = agent.invoke({
"messages": [{"role": "user", "content": "What is 24 * 17? Use calculator."}],
})
print(result["messages"][-1].content)Run the demo
Venv from Project Setup. Download, then:
calculator_tool_demo.py
24×17, then (100+15)/5
OPENAI_API_KEY in .env, same as Tool Calling.python calculator_tool_demo.py
calculator returned to see what expression ran.Separate add/sub/mul/div tools: Tools docs.