trippyrocks commited on
Commit
671b58b
·
verified ·
1 Parent(s): aa27a4c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -7
app.py CHANGED
@@ -19,18 +19,63 @@ def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return
19
  return "What magic will you build ?"
20
 
21
  @tool
22
- def basic_search(q:str)-> str:
23
- """A tool that takes in a query and returns the output from a DuckDuckGo search.
 
 
 
 
 
 
24
  Args:
25
- q: User query
 
 
 
26
  """
27
-
28
  try:
29
- search_tool = DuckDuckGoSearchTool()
30
- results = search_tool(q)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  except Exception as e:
32
- return f"Error: {str(e)}"
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  @tool
35
  def get_current_time_in_timezone(timezone: str) -> str:
36
  """A tool that fetches the current local time in a specified timezone.
 
19
  return "What magic will you build ?"
20
 
21
  @tool
22
+ def extended_calculator(operation: str) -> str:
23
+ """An extended calculator that safely evaluates math expressions.
24
+
25
+ Supports:
26
+ - Basic operations: +, -, *, /, and parentheses.
27
+ - Exponentiation: using either '^' or '**'.
28
+ - Math functions: sqrt, sin, cos, tan, log, exp.
29
+
30
  Args:
31
+ operation: A string mathematical expression (e.g., "2 + 2", "sqrt(16)", "2^3").
32
+
33
+ Returns:
34
+ str: The result of the calculation or an error message.
35
  """
 
36
  try:
37
+ # Replace caret '^' with Python's exponentiation operator '**'
38
+ operation = operation.replace("^", "**")
39
+
40
+ # Define allowed names for math functions and constants.
41
+ safe_env = {
42
+ "sqrt": math.sqrt,
43
+ "sin": math.sin,
44
+ "cos": math.cos,
45
+ "tan": math.tan,
46
+ "log": math.log, # natural logarithm by default
47
+ "exp": math.exp,
48
+ "pi": math.pi,
49
+ "e": math.e,
50
+ "abs": abs,
51
+ "pow": pow,
52
+ }
53
+
54
+ # Use a regex to allow only safe characters (digits, letters, operators, parentheses, commas, and periods)
55
+ # This helps reject inputs with disallowed symbols.
56
+ if not re.match(r'^[0-9a-zA-Z\s+\-*/().,]+$', operation):
57
+ return "Error: Expression contains invalid characters."
58
+
59
+ # Evaluate the expression using the restricted environment.
60
+ result = eval(operation, {"__builtins__": None}, safe_env)
61
+ return f"Result: {result}"
62
+
63
  except Exception as e:
64
+ return f"Error calculating {operation}: {str(e)}"
65
 
66
+ # Example usage:
67
+ if __name__ == "__main__":
68
+ expressions = [
69
+ "2 + 2",
70
+ "3 * (4 + 5)",
71
+ "2^3", # using '^' for exponentiation
72
+ "sqrt(16)",
73
+ "sin(pi/2)",
74
+ "log(e)"
75
+ ]
76
+
77
+ for expr in expressions:
78
+ print(f"{expr} = {extended_calculator(expr)}")
79
  @tool
80
  def get_current_time_in_timezone(timezone: str) -> str:
81
  """A tool that fetches the current local time in a specified timezone.