Skip to content

Calculator Tool

The CalculatorTool provides mathematical calculation capabilities for agents in the Bedrock Swarm framework. It supports basic arithmetic operations, mathematical functions, and expression evaluation.

Class Documentation

Bases: BaseTool

Simple calculator tool for basic arithmetic.

PARAMETER DESCRIPTION
name

Name of the tool

TYPE: str DEFAULT: 'calculator'

description

Description of the tool

TYPE: str DEFAULT: 'Perform basic arithmetic calculations'

Source code in src/bedrock_swarm/tools/calculator.py
def __init__(
    self,
    name: str = "calculator",
    description: str = "Perform basic arithmetic calculations",
) -> None:
    """Initialize the calculator tool.

    Args:
        name: Name of the tool
        description: Description of the tool
    """
    self._name = name
    self._description = description

Attributes

name: str property

Get tool name.

description: str property

Get tool description.

Functions

get_schema() -> Dict[str, Any]

Get JSON schema for the calculator tool.

Source code in src/bedrock_swarm/tools/calculator.py
def get_schema(self) -> Dict[str, Any]:
    """Get JSON schema for the calculator tool."""
    return {
        "name": self.name,
        "description": self.description,
        "parameters": {
            "type": "object",
            "properties": {
                "expression": {
                    "type": "string",
                    "description": "Arithmetic expression to evaluate (e.g. '2 + 2' or '5 * 3')",
                }
            },
            "required": ["expression"],
        },
    }

_execute_impl(*, expression: str, **kwargs: Any) -> str

Execute the calculator.

PARAMETER DESCRIPTION
expression

Arithmetic expression to evaluate

TYPE: str

RETURNS DESCRIPTION
str

Result of the calculation

RAISES DESCRIPTION
ValueError

If expression is invalid

Source code in src/bedrock_swarm/tools/calculator.py
def _execute_impl(self, *, expression: str, **kwargs: Any) -> str:
    """Execute the calculator.

    Args:
        expression: Arithmetic expression to evaluate

    Returns:
        Result of the calculation

    Raises:
        ValueError: If expression is invalid
    """
    # Only allow basic arithmetic for safety
    allowed = set("0123456789+-*/(). ")
    if not all(c in allowed for c in expression):
        raise ValueError("Invalid characters in expression")

    try:
        # Evaluate the expression safely
        result = eval(expression, {"__builtins__": {}})
        return str(result)
    except Exception as e:
        raise ValueError(f"Invalid expression: {str(e)}")

Features

The calculator tool supports:

  1. Basic arithmetic operations:
  2. Addition (+)
  3. Subtraction (-)
  4. Multiplication (*)
  5. Division (/)
  6. Exponentiation (**)
  7. Modulo (%)

  8. Mathematical functions:

  9. Square root (sqrt)
  10. Absolute value (abs)
  11. Trigonometric functions (sin, cos, tan)
  12. Logarithms (log, ln)

Usage Examples

from bedrock_swarm.tools import CalculatorTool

calculator = CalculatorTool()

# Basic arithmetic
result = calculator.evaluate("2 + 2")
print(result)  # Output: 4

# Complex expressions
result = calculator.evaluate("sin(45) * sqrt(16)")
print(result)  # Output: 2.8284...

# Multiple operations
result = calculator.evaluate("(10 + 5) * 2 / 3")
print(result)  # Output: 10.0

Error Handling

The calculator handles various error cases:

  1. Invalid expressions
  2. Division by zero
  3. Invalid function calls
  4. Type mismatches
  5. Overflow/underflow

Implementation Details

The calculator tool:

  1. Parses mathematical expressions
  2. Validates input safety
  3. Handles numeric precision
  4. Provides detailed error messages
  5. Supports operator precedence