From 1ed56aee85b4c64232f3f6517a8b555140f1c8a8 Mon Sep 17 00:00:00 2001 From: oobabooga <112222186+oobabooga@users.noreply.github.com> Date: Thu, 12 Mar 2026 18:45:19 -0700 Subject: [PATCH] Add a calculate tool --- user_data/tools/calculate.py | 48 ++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 user_data/tools/calculate.py diff --git a/user_data/tools/calculate.py b/user_data/tools/calculate.py new file mode 100644 index 00000000..e88b71a3 --- /dev/null +++ b/user_data/tools/calculate.py @@ -0,0 +1,48 @@ +import ast +import operator + +OPERATORS = { + ast.Add: operator.add, + ast.Sub: operator.sub, + ast.Mult: operator.mul, + ast.Div: operator.truediv, + ast.Pow: operator.pow, + ast.Mod: operator.mod, + ast.USub: operator.neg, +} + + +def _eval(node): + if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)): + return node.value + elif isinstance(node, ast.BinOp) and type(node.op) in OPERATORS: + return OPERATORS[type(node.op)](_eval(node.left), _eval(node.right)) + elif isinstance(node, ast.UnaryOp) and type(node.op) in OPERATORS: + return OPERATORS[type(node.op)](_eval(node.operand)) + raise ValueError(f"Unsupported expression") + + +tool = { + "type": "function", + "function": { + "name": "calculate", + "description": "Evaluate a math expression. Supports +, -, *, /, **, %.", + "parameters": { + "type": "object", + "properties": { + "expression": {"type": "string", "description": "The math expression to evaluate (e.g. '2 * (3 + 4)')."}, + }, + "required": ["expression"] + } + } +} + + +def execute(arguments): + expr = arguments.get("expression", "") + try: + tree = ast.parse(expr, mode='eval') + result = _eval(tree.body) + return {"expression": expr, "result": result} + except Exception as e: + return {"error": str(e)}