File size: 1,005 Bytes
837e221
e4c7240
 
837e221
 
e4c7240
837e221
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4c7240
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
36
37
38
39
40
41
import math
from typing import Any, Dict

from smolagents import tool


@tool
def perform_calculation(expression: str) -> Dict[str, Any]:
    """
    Safely evaluate a mathematical expression.

    Args:
        expression: Mathematical expression to evaluate

    Returns:
        Dictionary containing the result or error message
    """
    try:
        # Define allowed names
        allowed_names = {
            "abs": abs,
            "round": round,
            "min": min,
            "max": max,
            "sum": sum,
            "len": len,
            "pow": pow,
            "math": math,
        }

        # Clean the expression
        cleaned_expr = expression.strip()

        # Evaluate using safer methods (this is still a simplified example)
        # In a real implementation, use a proper math expression parser
        result = eval(cleaned_expr, {"__builtins__": {}}, allowed_names)

        return {"result": result}
    except Exception as e:
        return {"error": str(e)}