File size: 659 Bytes
f11fed1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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)}")