Course navigation
AgentsLesson 7 of 9

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 Python
Agent Types had multiply 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:

user: What is 24 × 17?
calculator("24*17")
tool: 408
ai: 408
Model sends the expression string. Your function returns the number.

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.
calculator_tool_demo.py
"""calculator_tool_demo.py"""
# ALLOWED char set, then @tool("calculator")
@tool("calculator")
python calculator_tool_demo.py
PowerShell — (.venv) active
(.venv) PS C:\projects\langchain-course> python calculator_tool_demo.py
Question: What is 24 times 17? Use the calculator tool.
calculator returned: 408
Answer: 24 times 17 is 408.
Question: What is (100 + 15) divided by 5? …
calculator returned: 23.0
Answer: (100 + 15) divided by 5 is 23.
Check calculator returned to see what expression ran.

Separate add/sub/mul/div tools: Tools docs.