File size: 1,052 Bytes
5ada353
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from langchain.tools import tool
import ast
import operator

def safe_eval(expr):
    ops = {
        ast.Add: operator.add,
        ast.Sub: operator.sub,
        ast.Mult: operator.mul,
        ast.Div: operator.truediv,
        ast.Pow: operator.pow,
        ast.USub: operator.neg,
    }

    def _eval(node):
        if isinstance(node, ast.Constant):
            return node.n
        elif isinstance(node, ast.BinOp):
            return ops[type(node.op)](_eval(node.left), _eval(node.right))
        elif isinstance(node, ast.UnaryOp):
            return ops[type(node.op)](_eval(node.operand))
        else:
            raise TypeError(f"Unsupported expression: {node}")

    node = ast.parse(expr, mode='eval').body
    return _eval(node)

@tool(description="Performs basic arithmetic calculations on a query string and returns the result as a string.")
def calculator_tool(query: str) -> str:
    try:
        result = safe_eval(query)
        return str(result)
    except Exception as e:
        return f"Error evaluating expression: {e}"