Skip to content

calculator

calculator

Calculator tool — safe math evaluation via ast module.

Classes

CalculatorTool

Bases: BaseTool

Safe math calculator using AST-based evaluation.

Functions

safe_eval

safe_eval(expression: str) -> float

Evaluate a math expression safely — Rust backend with Python fallback.

Source code in src/openjarvis/tools/calculator.py
def safe_eval(expression: str) -> float:
    """Evaluate a math expression safely — Rust backend with Python fallback."""
    try:
        from openjarvis._rust_bridge import get_rust_module

        _rust = get_rust_module()
        return float(_rust.CalculatorTool().execute(expression))
    except ImportError:
        import ast as _ast

        tree = _ast.parse(expression, mode="eval")
        return float(_safe_eval_node(tree.body))