Spaces:
Sleeping
Sleeping
File size: 2,894 Bytes
0f6cef4 | 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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | from smolagents import tool
import re
import math
@tool
def calculator(expression: str) -> str:
"""Evaluate a mathematical expression safely.
Args:
expression: A mathematical expression (e.g., '2 + 2 * 3', 'sqrt(16)')
Returns:
The result of the evaluation
"""
try:
# Clean the expression - remove any non-math characters for safety
# Allow only numbers, basic operators, parentheses, and math functions
safe_chars = r'[\d\s\+\-\*\/\(\)\.\^]|sqrt|pow|log|sin|cos|tan'
# Extract safe parts
safe_parts = re.findall(safe_chars, expression.lower())
safe_expression = ''.join(safe_parts)
if not safe_expression:
return "Error: No valid mathematical expression found"
# Replace ^ with ** for exponentiation
safe_expression = safe_expression.replace('^', '**')
# Define safe functions
safe_dict = {
'sqrt': math.sqrt,
'pow': math.pow,
'log': math.log,
'log10': math.log10,
'sin': math.sin,
'cos': math.cos,
'tan': math.tan,
'pi': math.pi,
'e': math.e
}
# Evaluate safely using eval with limited globals
result = eval(safe_expression, {"__builtins__": {}}, safe_dict)
return f"Result of '{expression}': {result}"
except ZeroDivisionError:
return "Error: Division by zero"
except Exception as e:
return f"Error evaluating expression: {str(e)}. Try: '2 + 2', '3 * 5', 'sqrt(16)', '2 ^ 3'"
@tool
def get_hf_dataset_info(dataset_name: str) -> str:
"""Get information about a Hugging Face dataset.
Args:
dataset_name: Name of the dataset (e.g., 'mnist', 'glue')
Returns:
Dataset information
"""
try:
from huggingface_hub import get_dataset_info
# Handle common dataset names
if dataset_name.lower() == "mnist":
dataset_name = "mnist"
elif dataset_name.lower() == "glue":
dataset_name = "glue"
info = get_dataset_info(dataset_name)
response = f"📊 **Dataset: {info.id}**\n\n"
response += f"**Description:** {info.description[:300]}...\n\n"
response += f"**Downloads:** {info.downloads:,}\n"
response += f"**Last Modified:** {info.lastModified}\n"
response += f"**License:** {info.cardData.get('license', 'Not specified')}\n"
# Show dataset size if available
if hasattr(info, 'size') and info.size:
response += f"**Size:** {info.size}\n"
return response
except Exception as e:
return f"Error getting dataset info: {str(e)}\n\nTry: 'mnist', 'glue', or other Hugging Face dataset names"
|