calculator / calc.py
akkikiki's picture
Upload tool
5b92c2d verified
from transformers import Tool
def simple_calculator(expression):
# Find the index of the operator
operator_index = -1
for i, char in enumerate(expression):
if char in ('+', '-', '*', '/'):
operator_index = i
break
# Ensure that an operator was found
if operator_index == -1:
return "Invalid expression"
# Split the expression into the operator and operands
operator = expression[operator_index]
operand1 = float(expression[:operator_index])
operand2 = float(expression[operator_index + 1:])
# Perform the calculation based on the operator
if operator == '+':
result = operand1 + operand2
elif operator == '-':
result = operand1 - operand2
elif operator == '*':
result = operand1 * operand2
elif operator == '/':
result = operand1 / operand2
else:
raise ValueError("Input string is not a valid mathematical expression.")
# Convert the result to a string and return it
return str(result)
# Test the function
expression = "1+3"
result = simple_calculator(expression)
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"]
output_type = "text"
def __call__(self, input_str: str):
return simple_calculator(input_str)