HAMMALE commited on
Commit
a870cc3
·
verified ·
1 Parent(s): 8c5c24b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +184 -26
app.py CHANGED
@@ -1,23 +1,13 @@
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:
23
  """A tool that fetches the current local time in a specified timezone.
@@ -25,37 +15,206 @@ def get_current_time_in_timezone(timezone: str) -> str:
25
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
26
  """
27
  try:
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)}"
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- final_answer = FinalAnswerTool()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
40
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- model = HfApiModel(
43
- max_tokens=2096,
44
- temperature=0.5,
45
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
46
- custom_role_conversions=None,
47
- )
 
 
 
 
 
 
48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
  # Import tool from Hub
51
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
 
52
 
 
53
  with open("prompts.yaml", 'r') as stream:
54
  prompt_templates = yaml.safe_load(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,
@@ -65,5 +224,4 @@ agent = CodeAgent(
65
  prompt_templates=prompt_templates
66
  )
67
 
68
-
69
  GradioUI(agent).launch()
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, load_tool, tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
+ import json
7
+ import re
8
  from tools.final_answer import FinalAnswerTool
 
9
  from Gradio_UI import GradioUI
10
 
 
 
 
 
 
 
 
 
 
 
 
11
  @tool
12
  def get_current_time_in_timezone(timezone: str) -> str:
13
  """A tool that fetches the current local time in a specified timezone.
 
15
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
16
  """
17
  try:
 
18
  tz = pytz.timezone(timezone)
 
19
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
20
  return f"The current local time in {timezone} is: {local_time}"
21
  except Exception as e:
22
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
23
 
24
+ @tool
25
+ def calculate_time_difference(timezone1: str, timezone2: str) -> str:
26
+ """Calculate the time difference between two timezones.
27
+ Args:
28
+ timezone1: First timezone (e.g., 'America/New_York')
29
+ timezone2: Second timezone (e.g., 'Asia/Tokyo')
30
+ """
31
+ try:
32
+ tz1 = pytz.timezone(timezone1)
33
+ tz2 = pytz.timezone(timezone2)
34
+ now = datetime.datetime.now(pytz.UTC)
35
+ offset1 = now.astimezone(tz1).utcoffset().total_seconds() / 3600
36
+ offset2 = now.astimezone(tz2).utcoffset().total_seconds() / 3600
37
+ diff = offset2 - offset1
38
+ return f"Time difference: {timezone2} is {diff:+.1f} hours ahead of {timezone1}"
39
+ except Exception as e:
40
+ return f"Error calculating time difference: {str(e)}"
41
 
42
+ @tool
43
+ def get_weather_info(city: str) -> str:
44
+ """Fetch current weather information for a city using wttr.in service.
45
+ Args:
46
+ city: Name of the city (e.g., 'London', 'Paris', 'Tokyo')
47
+ """
48
+ try:
49
+ response = requests.get(f"https://wttr.in/{city}?format=j1", timeout=10)
50
+ if response.status_code == 200:
51
+ data = response.json()
52
+ current = data['current_condition'][0]
53
+ temp_c = current['temp_C']
54
+ feels_like = current['FeelsLikeC']
55
+ desc = current['weatherDesc'][0]['value']
56
+ humidity = current['humidity']
57
+ wind_speed = current['windspeedKmph']
58
+
59
+ return f"Weather in {city}: {desc}, {temp_c}°C (feels like {feels_like}°C), Humidity: {humidity}%, Wind: {wind_speed} km/h"
60
+ else:
61
+ return f"Could not fetch weather for {city}"
62
+ except Exception as e:
63
+ return f"Error fetching weather: {str(e)}"
64
 
65
+ @tool
66
+ def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
67
+ """Convert currency using live exchange rates from an API.
68
+ Args:
69
+ amount: Amount to convert
70
+ from_currency: Source currency code (e.g., 'USD')
71
+ to_currency: Target currency code (e.g., 'EUR')
72
+ """
73
+ try:
74
+ # Using exchangerate-api.com free tier
75
+ url = f"https://api.exchangerate-api.com/v4/latest/{from_currency.upper()}"
76
+ response = requests.get(url, timeout=10)
77
+ if response.status_code == 200:
78
+ data = response.json()
79
+ rate = data['rates'].get(to_currency.upper())
80
+ if rate:
81
+ converted = amount * rate
82
+ return f"{amount} {from_currency.upper()} = {converted:.2f} {to_currency.upper()} (Rate: {rate:.4f})"
83
+ else:
84
+ return f"Currency {to_currency} not found"
85
+ else:
86
+ return "Error fetching exchange rates"
87
+ except Exception as e:
88
+ return f"Error converting currency: {str(e)}"
89
 
90
+ @tool
91
+ def extract_urls_from_text(text: str) -> str:
92
+ """Extract all URLs from a given text.
93
+ Args:
94
+ text: The text to extract URLs from
95
+ """
96
+ url_pattern = r'https?://[^\s<>"{}|\\^`\[\]]+'
97
+ urls = re.findall(url_pattern, text)
98
+ if urls:
99
+ return f"Found {len(urls)} URL(s): " + ", ".join(urls)
100
+ else:
101
+ return "No URLs found in the text"
102
 
103
+ @tool
104
+ def countdown_to_date(target_date: str) -> str:
105
+ """Calculate countdown to a specific date.
106
+ Args:
107
+ target_date: Date in format 'YYYY-MM-DD' (e.g., '2025-12-31')
108
+ """
109
+ try:
110
+ target = datetime.datetime.strptime(target_date, "%Y-%m-%d")
111
+ now = datetime.datetime.now()
112
+ diff = target - now
113
+
114
+ if diff.days < 0:
115
+ return f"The date {target_date} has already passed ({abs(diff.days)} days ago)"
116
+
117
+ days = diff.days
118
+ hours = diff.seconds // 3600
119
+ minutes = (diff.seconds % 3600) // 60
120
+
121
+ return f"Countdown to {target_date}: {days} days, {hours} hours, {minutes} minutes"
122
+ except Exception as e:
123
+ return f"Error parsing date: {str(e)}"
124
+
125
+ @tool
126
+ def generate_random_password(length: int, include_symbols: bool = True) -> str:
127
+ """Generate a random secure password.
128
+ Args:
129
+ length: Length of the password (minimum 8)
130
+ include_symbols: Whether to include special symbols
131
+ """
132
+ import random
133
+ import string
134
+
135
+ if length < 8:
136
+ return "Password length must be at least 8 characters"
137
+
138
+ chars = string.ascii_letters + string.digits
139
+ if include_symbols:
140
+ chars += "!@#$%^&*()_+-=[]{}|;:,.<>?"
141
+
142
+ password = ''.join(random.choice(chars) for _ in range(length))
143
+ return f"Generated password (length {length}): {password}"
144
+
145
+ @tool
146
+ def calculate_age_from_birthdate(birthdate: str) -> str:
147
+ """Calculate age from birthdate.
148
+ Args:
149
+ birthdate: Date in format 'YYYY-MM-DD' (e.g., '1990-05-15')
150
+ """
151
+ try:
152
+ birth = datetime.datetime.strptime(birthdate, "%Y-%m-%d")
153
+ today = datetime.datetime.now()
154
+ age = today.year - birth.year - ((today.month, today.day) < (birth.month, birth.day))
155
+
156
+ next_birthday = datetime.datetime(today.year, birth.month, birth.day)
157
+ if next_birthday < today:
158
+ next_birthday = datetime.datetime(today.year + 1, birth.month, birth.day)
159
+
160
+ days_to_birthday = (next_birthday - today).days
161
+
162
+ return f"Age: {age} years old. Next birthday in {days_to_birthday} days."
163
+ except Exception as e:
164
+ return f"Error calculating age: {str(e)}"
165
+
166
+ @tool
167
+ def list_available_timezones(region: str = "all") -> str:
168
+ """List available timezones for a specific region.
169
+ Args:
170
+ region: Region name (e.g., 'America', 'Europe', 'Asia') or 'all' for common timezones
171
+ """
172
+ if region.lower() == "all":
173
+ common_tz = [
174
+ "UTC", "America/New_York", "America/Los_Angeles", "America/Chicago",
175
+ "Europe/London", "Europe/Paris", "Europe/Berlin", "Asia/Tokyo",
176
+ "Asia/Shanghai", "Asia/Dubai", "Australia/Sydney", "Pacific/Auckland"
177
+ ]
178
+ return "Common timezones: " + ", ".join(common_tz)
179
+ else:
180
+ timezones = [tz for tz in pytz.all_timezones if tz.startswith(region)]
181
+ if timezones:
182
+ return f"Timezones in {region}: " + ", ".join(timezones[:20]) + ("..." if len(timezones) > 20 else "")
183
+ else:
184
+ return f"No timezones found for region '{region}'"
185
+
186
+ final_answer = FinalAnswerTool()
187
+ model = InferenceClientModel(
188
+ max_tokens=2096,
189
+ temperature=0.5,
190
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
191
+ custom_role_conversions=None,
192
+ )
193
 
194
  # Import tool from Hub
195
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
196
+ search_tool = DuckDuckGoSearchTool()
197
 
198
+ # Load system prompt from prompt.yaml file
199
  with open("prompts.yaml", 'r') as stream:
200
  prompt_templates = yaml.safe_load(stream)
201
 
202
  agent = CodeAgent(
203
  model=model,
204
+ tools=[
205
+ final_answer,
206
+ get_current_time_in_timezone,
207
+ calculate_time_difference,
208
+ get_weather_info,
209
+ convert_currency,
210
+ extract_urls_from_text,
211
+ countdown_to_date,
212
+ generate_random_password,
213
+ calculate_age_from_birthdate,
214
+ list_available_timezones,
215
+ image_generation_tool,
216
+ search_tool
217
+ ],
218
  max_steps=6,
219
  verbosity_level=1,
220
  grammar=None,
 
224
  prompt_templates=prompt_templates
225
  )
226
 
 
227
  GradioUI(agent).launch()