simple-calculator / calculator.py
ybelkada's picture
Upload tool
f11fed1
raw
history blame
659 Bytes
import re
from transformers import Tool
from huggingface_hub import list_models
class SimpleCalculatorTool(Tool):
name = "simple_calculator"
description = (
"This is a tool that returns the result of a simple mathematical expression written in a string."
)
inputs = ["text"]
outputs = ["text"]
regex = r"(\d+(?:\.\d+)?)(\+|\-|\*|\/)(\d+(?:\.\d+)?)"
def __call__(self, input_str: str):
match = re.match(self.regex, input_str)
if match is None:
raise ValueError("Input string is not a valid mathematical expression.")
return eval(f"{match.group(1)} {match.group(2)} {match.group(3)}")