2stacks commited on
Commit
19d3f03
·
verified ·
1 Parent(s): 8c5c24b

Added some tools

Browse files
Files changed (1) hide show
  1. app.py +105 -9
app.py CHANGED
@@ -1,22 +1,118 @@
1
  from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
2
- import datetime
3
  import requests
4
  import pytz
5
  import yaml
 
6
  from tools.final_answer import FinalAnswerTool
7
 
8
  from Gradio_UI import GradioUI
9
 
10
  # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
  @tool
12
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- #Keep this format for the description / args / args description but feel free to modify the tool
14
- """A tool that does nothing yet
 
 
 
 
15
  Args:
16
- arg1: the first argument
17
- arg2: the second argument
18
  """
19
- return "What magic will you build ?"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  @tool
22
  def get_current_time_in_timezone(timezone: str) -> str:
@@ -28,7 +124,7 @@ def get_current_time_in_timezone(timezone: str) -> str:
28
  # Create timezone object
29
  tz = pytz.timezone(timezone)
30
  # Get current time in that timezone
31
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
  return f"The current local time in {timezone} is: {local_time}"
33
  except Exception as e:
34
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
@@ -55,7 +151,7 @@ with open("prompts.yaml", 'r') as stream:
55
 
56
  agent = CodeAgent(
57
  model=model,
58
- tools=[final_answer], ## add your tools here (don't remove final answer)
59
  max_steps=6,
60
  verbosity_level=1,
61
  grammar=None,
 
1
  from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
 
2
  import requests
3
  import pytz
4
  import yaml
5
+ from datetime import datetime, timedelta
6
  from tools.final_answer import FinalAnswerTool
7
 
8
  from Gradio_UI import GradioUI
9
 
10
  # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
  @tool
12
+ def get_time_difference(location: str) -> str:
13
+ """
14
+ Calculates and returns the time difference between a specified location and U.S. Eastern Time.
15
+
16
+ This tool fetches the current time for the given location and for the U.S. Eastern Time zone (America/New_York),
17
+ then presents a fun, easy-to-read comparison.
18
+
19
  Args:
20
+ location: The city or timezone to get the local time for (e.g., "London", "Asia/Tokyo", "Europe/Paris").
 
21
  """
22
+
23
+ def get_time_data(timezone: str):
24
+ """Helper function to fetch time data from the World Time API."""
25
+ api_url = f"http://worldtimeapi.org/api/timezone/{timezone}"
26
+ try:
27
+ response = requests.get(api_url)
28
+ # Raise an exception for bad status codes (4xx or 5xx)
29
+ response.raise_for_status()
30
+ return response.json()
31
+ except requests.exceptions.RequestException as e:
32
+ # This handles network errors, bad status codes, etc.
33
+ print(f"API request failed for {timezone}: {e}")
34
+ return None
35
+
36
+ # Step 1: Get U.S. Eastern Time
37
+ et_data = get_time_data("America/New_York")
38
+ if not et_data:
39
+ return "Oops! I couldn't connect to get the U.S. Eastern Time right now. Please try again later."
40
+
41
+ # Step 2: Get time for the user-specified location
42
+ # The API can be picky. We'll try the user's input directly first.
43
+ # If it fails, we'll try to find a matching timezone.
44
+ location_data = get_time_data(location)
45
+
46
+ if not location_data:
47
+ # Try to find a timezone that contains the location string
48
+ try:
49
+ all_timezones_response = requests.get("http://worldtimeapi.org/api/timezone")
50
+ all_timezones_response.raise_for_status()
51
+ all_timezones = all_timezones_response.json()
52
+
53
+ # Find the first timezone that ends with the location name
54
+ found_timezone = next((tz for tz in all_timezones if tz.lower().endswith(f"/{location.lower()}")), None)
55
+
56
+ if found_timezone:
57
+ print(f"Found matching timezone: {found_timezone}")
58
+ location_data = get_time_data(found_timezone)
59
+ else:
60
+ return f"Sorry, I couldn't find a timezone for '{location}'. Try a major city or a standard timezone format like 'Europe/London'."
61
+ except requests.exceptions.RequestException:
62
+ return "Sorry, I'm having trouble searching for that location right now."
63
+
64
+
65
+ if not location_data:
66
+ return f"I tried my best, but I still couldn't find the time for '{location}'. Are you sure it's spelled correctly?"
67
+
68
+ # Step 3: Parse the datetime objects from the API responses
69
+ try:
70
+ et_time = datetime.fromisoformat(et_data['datetime'])
71
+ location_time = datetime.fromisoformat(location_data['datetime'])
72
+ location_timezone_name = location.replace('_', ' ').title()
73
+ et_timezone_name = "U.S. Eastern Time"
74
+ except (ValueError, KeyError):
75
+ return "There was an issue processing the time data. It might be a temporary problem."
76
+
77
+ # Step 4: Calculate the difference
78
+ # We compare based on UTC offset to get the pure time difference
79
+ et_offset_str = et_data['utc_offset']
80
+ location_offset_str = location_data['utc_offset']
81
+
82
+ et_offset = timedelta(hours=int(et_offset_str[1:3]), minutes=int(et_offset_str[4:6]))
83
+ if et_offset_str[0] == '-':
84
+ et_offset = -et_offset
85
+
86
+ location_offset = timedelta(hours=int(location_offset_str[1:3]), minutes=int(location_offset_str[4:6]))
87
+ if location_offset_str[0] == '-':
88
+ location_offset = -location_offset
89
+
90
+ time_difference = location_offset - et_offset
91
+
92
+ # Step 5: Format the output string in a fun way
93
+ diff_total_seconds = time_difference.total_seconds()
94
+ diff_hours = int(diff_total_seconds / 3600)
95
+ diff_minutes = int((diff_total_seconds % 3600) / 60)
96
+
97
+ comparison = ""
98
+ if diff_total_seconds == 0:
99
+ comparison = f"{location_timezone_name} is in the same timezone as {et_timezone_name}!"
100
+ else:
101
+ ahead_or_behind = "ahead of" if diff_total_seconds > 0 else "behind"
102
+ # Format the hours and minutes for readability
103
+ hour_str = f"{abs(diff_hours)} hour{'s' if abs(diff_hours) != 1 else ''}"
104
+ minute_str = f"{abs(diff_minutes)} minute{'s' if abs(diff_minutes) != 1 else ''}"
105
+
106
+ if diff_hours != 0 and diff_minutes != 0:
107
+ comparison = f"{location_timezone_name} is {hour_str} and {minute_str} {ahead_or_behind} {et_timezone_name}."
108
+ elif diff_hours != 0:
109
+ comparison = f"{location_timezone_name} is {hour_str} {ahead_or_behind} {et_timezone_name}."
110
+ else: # Only minutes are different
111
+ comparison = f"{location_timezone_name} is {minute_str} {ahead_or_behind} {et_timezone_name}."
112
+
113
+ return (f"Time check! Right now, it's {et_time.strftime('%-I:%M %p')} in {et_timezone_name}, "
114
+ f"which means it's {location_time.strftime('%-I:%M %p')} in {location_timezone_name}. "
115
+ f"{comparison}")
116
 
117
  @tool
118
  def get_current_time_in_timezone(timezone: str) -> str:
 
124
  # Create timezone object
125
  tz = pytz.timezone(timezone)
126
  # Get current time in that timezone
127
+ local_time = datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
128
  return f"The current local time in {timezone} is: {local_time}"
129
  except Exception as e:
130
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
 
151
 
152
  agent = CodeAgent(
153
  model=model,
154
+ tools=[final_answer, DuckDuckGoSearchTool, image_generation_tool, get_time_difference], ## add your tools here (don't remove final answer)
155
  max_steps=6,
156
  verbosity_level=1,
157
  grammar=None,