""" Mathematical calculation tools for the Math Agent. Handles complex calculations, statistical analysis, and numerical operations. """ from typing import Any, Dict, List, Union import math from langchain_core.tools import tool @tool def calculate_expression(expression: str) -> float: """ Safely evaluate a mathematical expression. Args: expression: Mathematical expression as string Returns: Result of the calculation """ try: # Use eval safely with limited scope allowed_names = { "abs": abs, "round": round, "min": min, "max": max, "sum": sum, "pow": pow, "sqrt": math.sqrt, "sin": math.sin, "cos": math.cos, "tan": math.tan, "log": math.log, "log10": math.log10, "exp": math.exp, "pi": math.pi, "e": math.e } return eval(expression, {"__builtins__": {}}, allowed_names) except Exception as e: return f"Calculation error: {str(e)}" @tool def percentage_calculation(value: float, total: float) -> float: """ Calculate percentage. Args: value: The value total: The total value Returns: Percentage as decimal """ if total == 0: return 0 return (value / total) * 100 @tool def currency_format(amount: float, currency: str = "USD", decimals: int = 2) -> str: """ Format currency amount. Args: amount: The amount to format currency: Currency code decimals: Number of decimal places Returns: Formatted currency string """ return f"{amount:.{decimals}f}" @tool def statistical_summary(numbers: List[float]) -> Dict[str, float]: """ Calculate basic statistics for a list of numbers. Args: numbers: List of numbers Returns: Dictionary with statistical measures """ if not numbers: return {} return { "mean": sum(numbers) / len(numbers), "median": sorted(numbers)[len(numbers) // 2], "min": min(numbers), "max": max(numbers), "sum": sum(numbers), "count": len(numbers) } # Add more mathematical tools as needed