Skip to content

teff.tool.builtin.calculator

teff.tool.builtin.calculator

Calculator tool — AST-based safe evaluation of math expressions.

Classes:

Name Description
CalculatorTool

Evaluate mathematical expressions using AST-based safe eval.

CalculatorTool

Bases: Tool

Evaluate mathematical expressions using AST-based safe eval.

Source code in teff/tool/builtin/calculator.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class CalculatorTool(Tool):
    """Evaluate mathematical expressions using AST-based safe eval."""

    name = "calculator"
    description = "Evaluate mathematical expressions"

    def run(self, expression: str = "") -> str:  # type: ignore[override]
        tree = ast.parse(expression, mode="eval")
        return str(self._eval(tree.body))

    def _eval(self, node):
        if isinstance(node, ast.Constant):
            return node.value
        if isinstance(node, ast.UnaryOp):
            return _OPS[type(node.op)](self._eval(node.operand))
        if isinstance(node, ast.BinOp):
            return _OPS[type(node.op)](self._eval(node.left), self._eval(node.right))
        if isinstance(node, ast.Name) and node.id == "pi":
            import math

            return math.pi
        raise ValueError(f"unsupported: {ast.dump(node)}")