zeerafle's picture
Add calculator tool using numexpr for math expressions
3d75873
raw
history blame contribute delete
783 Bytes
import math
import numexpr
from langchain_core.tools import StructuredTool
def calculator(expression: str) -> str:
"""Calculate expression using Python's numexpr library.
Expression should be a single line mathematical expression
that solves the problem.
Examples:
"37593 * 67" for "37593 times 67"
"37593**(1/5)" for "37593^(1/5)"
"""
local_dict = {"pi": math.pi, "e": math.e}
return str(
numexpr.evaluate(
expression.strip(),
global_dict={}, # restrict access to globals
local_dict=local_dict, # add common mathematical functions
)
)
calculator_tool = StructuredTool.from_function(func=calculator)
if __name__ == "__main__":
print(calculator_tool.invoke("551368 / 82"))