Whizzkk commited on
Commit
fbba536
·
verified ·
1 Parent(s): 5511e5c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -123
app.py CHANGED
@@ -1,211 +1,210 @@
1
- from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, load_tool, tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
- from tools.final_answer import FinalAnswerTool
 
7
  from Gradio_UI import GradioUI
8
 
9
- # Weather Tool
10
  @tool
11
- def get_weather(city: str) -> str:
12
- """Fetches current weather information for a specified city.
 
13
  Args:
14
- city: The name of the city to get weather for (e.g., 'London', 'New York')
15
  """
16
  try:
17
- # Using wttr.in API which doesn't require authentication
18
- response = requests.get(f"https://wttr.in/{city}?format=j1", timeout=10)
19
- if response.status_code == 200:
20
- data = response.json()
21
- current = data['current_condition'][0]
22
- weather_desc = current['weatherDesc'][0]['value']
23
- temp_c = current['temp_C']
24
- feels_like = current['FeelsLikeC']
25
- humidity = current['humidity']
26
- wind_speed = current['windspeedKmph']
27
-
28
- return f"Weather in {city}: {weather_desc}, Temperature: {temp_c}°C (feels like {feels_like}°C), Humidity: {humidity}%, Wind: {wind_speed} km/h"
29
- else:
30
- return f"Could not fetch weather data for {city}"
31
  except Exception as e:
32
- return f"Error fetching weather: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  # Calculator Tool
35
  @tool
36
  def calculate(expression: str) -> str:
37
- """Evaluates a mathematical expression safely.
 
38
  Args:
39
  expression: A mathematical expression as a string (e.g., '2 + 2', '10 * 5 + 3')
40
  """
41
  try:
42
- # Safe evaluation of mathematical expressions
43
  allowed_chars = set('0123456789+-*/(). ')
44
  if not all(c in allowed_chars for c in expression):
45
- return "Error: Expression contains invalid characters. Only numbers and basic operators (+, -, *, /, parentheses) are allowed."
46
 
47
  result = eval(expression, {"__builtins__": {}}, {})
48
  return f"Result: {result}"
49
  except Exception as e:
50
  return f"Error calculating expression: {str(e)}"
51
 
52
- # Currency Converter Tool
53
  @tool
54
- def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
55
- """Converts an amount from one currency to another using live exchange rates.
 
56
  Args:
57
- amount: The amount to convert
58
- from_currency: Source currency code (e.g., 'USD', 'EUR', 'GBP')
59
- to_currency: Target currency code (e.g., 'USD', 'EUR', 'GBP')
60
  """
61
  try:
62
- # Using exchangerate-api.com free tier
63
- url = f"https://api.exchangerate-api.com/v4/latest/{from_currency.upper()}"
64
  response = requests.get(url, timeout=10)
65
-
66
  if response.status_code == 200:
67
  data = response.json()
68
- if to_currency.upper() in data['rates']:
69
- rate = data['rates'][to_currency.upper()]
70
- converted = amount * rate
71
- return f"{amount} {from_currency.upper()} = {converted:.2f} {to_currency.upper()} (Rate: {rate:.4f})"
72
- else:
73
- return f"Currency code '{to_currency}' not found"
 
 
74
  else:
75
- return "Error fetching exchange rates"
76
  except Exception as e:
77
- return f"Error converting currency: {str(e)}"
78
 
79
- # Text Analysis Tool
80
  @tool
81
- def analyze_text(text: str) -> str:
82
- """Analyzes text and provides statistics like word count, character count, and reading time.
 
83
  Args:
84
- text: The text to analyze
85
  """
86
  try:
87
- words = text.split()
88
- word_count = len(words)
89
- char_count = len(text)
90
- char_count_no_spaces = len(text.replace(' ', ''))
91
- sentence_count = text.count('.') + text.count('!') + text.count('?')
92
-
93
- # Average reading speed is ~200 words per minute
94
- reading_time_minutes = word_count / 200
95
-
96
- return f"""Text Analysis:
97
- - Words: {word_count}
98
- - Characters (with spaces): {char_count}
99
- - Characters (without spaces): {char_count_no_spaces}
100
- - Sentences: {sentence_count}
101
- - Estimated reading time: {reading_time_minutes:.1f} minutes"""
102
  except Exception as e:
103
- return f"Error analyzing text: {str(e)}"
104
 
105
- # Random Fact Generator
106
  @tool
107
- def get_random_fact() -> str:
108
- """Fetches a random interesting fact."""
 
 
 
 
 
109
  try:
110
- response = requests.get("https://uselessfacts.jsph.pl/random.json?language=en", timeout=10)
111
- if response.status_code == 200:
112
- fact = response.json()['text']
113
- return f"Random Fact: {fact}"
114
- else:
115
- return "Could not fetch a random fact at this time."
116
  except Exception as e:
117
- return f"Error fetching random fact: {str(e)}"
118
 
119
- # Timezone Converter
120
  @tool
121
- def convert_time_between_timezones(time_str: str, from_timezone: str, to_timezone: str) -> str:
122
- """Converts a time from one timezone to another.
 
123
  Args:
124
- time_str: Time in format 'HH:MM' (24-hour format)
125
- from_timezone: Source timezone (e.g., 'America/New_York')
126
- to_timezone: Target timezone (e.g., 'Asia/Tokyo')
127
  """
128
  try:
129
- # Parse time
130
- time_obj = datetime.datetime.strptime(time_str, "%H:%M").time()
131
-
132
- # Get current date
133
- today = datetime.datetime.now().date()
134
-
135
- # Create datetime object with source timezone
136
- from_tz = pytz.timezone(from_timezone)
137
- dt_from = from_tz.localize(datetime.datetime.combine(today, time_obj))
138
-
139
- # Convert to target timezone
140
- to_tz = pytz.timezone(to_timezone)
141
- dt_to = dt_from.astimezone(to_tz)
142
-
143
- return f"{time_str} in {from_timezone} is {dt_to.strftime('%H:%M')} in {to_timezone}"
144
  except Exception as e:
145
- return f"Error converting time: {str(e)}"
146
 
147
- # URL Shortener (using is.gd)
148
  @tool
149
- def shorten_url(url: str) -> str:
150
- """Shortens a long URL using a URL shortening service.
 
151
  Args:
152
- url: The URL to shorten
153
  """
154
  try:
155
- response = requests.get(f"https://is.gd/create.php?format=simple&url={url}", timeout=10)
 
156
  if response.status_code == 200:
157
- short_url = response.text
158
- return f"Shortened URL: {short_url}"
159
  else:
160
- return "Error shortening URL"
161
  except Exception as e:
162
- return f"Error: {str(e)}"
163
 
 
164
  @tool
165
- def get_current_time_in_timezone(timezone: str) -> str:
166
- """A tool that fetches the current local time in a specified timezone.
 
167
  Args:
168
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
169
  """
170
  try:
171
- tz = pytz.timezone(timezone)
172
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
173
- return f"The current local time in {timezone} is: {local_time}"
 
 
 
174
  except Exception as e:
175
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
176
 
177
- # Initialize tools
178
  final_answer = FinalAnswerTool()
179
- search_tool = DuckDuckGoSearchTool()
180
 
181
- model = InferenceClientModel(
182
  max_tokens=2096,
183
  temperature=0.5,
184
  model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
185
  custom_role_conversions=None,
186
  )
187
 
188
- # Import tool from Hub
189
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
190
 
191
- # Load system prompt from prompt.yaml file
192
  with open("prompts.yaml", 'r') as stream:
193
  prompt_templates = yaml.safe_load(stream)
194
-
195
  agent = CodeAgent(
196
  model=model,
197
  tools=[
198
  final_answer,
199
- search_tool,
200
- get_weather,
201
  calculate,
 
 
 
202
  convert_currency,
203
- analyze_text,
204
- get_random_fact,
205
- get_current_time_in_timezone,
206
- convert_time_between_timezones,
207
- shorten_url,
208
- image_generation_tool
209
  ],
210
  max_steps=6,
211
  verbosity_level=1,
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
+ import json
7
+ from tools.final_answer import FinalAnswerTool
8
  from Gradio_UI import GradioUI
9
 
10
+ # Web Search Tool
11
  @tool
12
+ def web_search(query: str) -> str:
13
+ """Search the web using DuckDuckGo for current information.
14
+
15
  Args:
16
+ query: The search query string
17
  """
18
  try:
19
+ search_tool = DuckDuckGoSearchTool()
20
+ results = search_tool(query)
21
+ return results
 
 
 
 
 
 
 
 
 
 
 
22
  except Exception as e:
23
+ return f"Error performing web search: {str(e)}"
24
+
25
+ # Time and Date Tool
26
+ @tool
27
+ def get_current_time_in_timezone(timezone: str) -> str:
28
+ """Get the current local time in a specified timezone.
29
+
30
+ Args:
31
+ timezone: A valid timezone string (e.g., 'America/New_York', 'Europe/London', 'Asia/Tokyo')
32
+ """
33
+ try:
34
+ tz = pytz.timezone(timezone)
35
+ local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S %Z")
36
+ return f"The current local time in {timezone} is: {local_time}"
37
+ except Exception as e:
38
+ return f"Error: Invalid timezone '{timezone}'. {str(e)}"
39
 
40
  # Calculator Tool
41
  @tool
42
  def calculate(expression: str) -> str:
43
+ """Evaluate a mathematical expression safely.
44
+
45
  Args:
46
  expression: A mathematical expression as a string (e.g., '2 + 2', '10 * 5 + 3')
47
  """
48
  try:
49
+ # Safe evaluation using only numbers and basic operators
50
  allowed_chars = set('0123456789+-*/(). ')
51
  if not all(c in allowed_chars for c in expression):
52
+ return "Error: Expression contains invalid characters"
53
 
54
  result = eval(expression, {"__builtins__": {}}, {})
55
  return f"Result: {result}"
56
  except Exception as e:
57
  return f"Error calculating expression: {str(e)}"
58
 
59
+ # Weather Tool
60
  @tool
61
+ def get_weather(city: str) -> str:
62
+ """Get current weather information for a city using wttr.in service.
63
+
64
  Args:
65
+ city: Name of the city to get weather for
 
 
66
  """
67
  try:
68
+ url = f"https://wttr.in/{city}?format=j1"
 
69
  response = requests.get(url, timeout=10)
 
70
  if response.status_code == 200:
71
  data = response.json()
72
+ current = data['current_condition'][0]
73
+ temp_c = current['temp_C']
74
+ temp_f = current['temp_F']
75
+ weather_desc = current['weatherDesc'][0]['value']
76
+ humidity = current['humidity']
77
+ wind_speed = current['windspeedKmph']
78
+
79
+ return f"Weather in {city}: {weather_desc}, Temperature: {temp_c}°C ({temp_f}°F), Humidity: {humidity}%, Wind Speed: {wind_speed} km/h"
80
  else:
81
+ return f"Could not fetch weather for {city}"
82
  except Exception as e:
83
+ return f"Error fetching weather: {str(e)}"
84
 
85
+ # File Reader Tool
86
  @tool
87
+ def read_file(filepath: str) -> str:
88
+ """Read and return the contents of a text file.
89
+
90
  Args:
91
+ filepath: Path to the file to read
92
  """
93
  try:
94
+ with open(filepath, 'r', encoding='utf-8') as f:
95
+ content = f.read()
96
+ return f"File content:\n{content}"
 
 
 
 
 
 
 
 
 
 
 
 
97
  except Exception as e:
98
+ return f"Error reading file: {str(e)}"
99
 
100
+ # File Writer Tool
101
  @tool
102
+ def write_file(filepath: str, content: str) -> str:
103
+ """Write content to a text file.
104
+
105
+ Args:
106
+ filepath: Path where the file should be written
107
+ content: Content to write to the file
108
+ """
109
  try:
110
+ with open(filepath, 'w', encoding='utf-8') as f:
111
+ f.write(content)
112
+ return f"Successfully wrote to {filepath}"
 
 
 
113
  except Exception as e:
114
+ return f"Error writing file: {str(e)}"
115
 
116
+ # Currency Converter Tool
117
  @tool
118
+ def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
119
+ """Convert an amount from one currency to another using live exchange rates.
120
+
121
  Args:
122
+ amount: The amount to convert
123
+ from_currency: The source currency code (e.g., 'USD', 'EUR', 'GBP')
124
+ to_currency: The target currency code (e.g., 'USD', 'EUR', 'GBP')
125
  """
126
  try:
127
+ url = f"https://api.exchangerate-api.com/v4/latest/{from_currency.upper()}"
128
+ response = requests.get(url, timeout=10)
129
+ if response.status_code == 200:
130
+ data = response.json()
131
+ rate = data['rates'].get(to_currency.upper())
132
+ if rate:
133
+ converted = amount * rate
134
+ return f"{amount} {from_currency.upper()} = {converted:.2f} {to_currency.upper()}"
135
+ else:
136
+ return f"Currency code '{to_currency}' not found"
137
+ else:
138
+ return "Error fetching exchange rates"
 
 
 
139
  except Exception as e:
140
+ return f"Error converting currency: {str(e)}"
141
 
142
+ # Wikipedia Summary Tool
143
  @tool
144
+ def get_wikipedia_summary(topic: str) -> str:
145
+ """Get a brief summary from Wikipedia about a topic.
146
+
147
  Args:
148
+ topic: The topic to search for on Wikipedia
149
  """
150
  try:
151
+ url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{topic.replace(' ', '_')}"
152
+ response = requests.get(url, timeout=10)
153
  if response.status_code == 200:
154
+ data = response.json()
155
+ return f"Wikipedia Summary: {data.get('extract', 'No summary available')}"
156
  else:
157
+ return f"Could not find Wikipedia article for '{topic}'"
158
  except Exception as e:
159
+ return f"Error fetching Wikipedia summary: {str(e)}"
160
 
161
+ # List Available Timezones Tool
162
  @tool
163
+ def list_common_timezones(region: str = "all") -> str:
164
+ """List common timezones, optionally filtered by region.
165
+
166
  Args:
167
+ region: Region to filter by (e.g., 'America', 'Europe', 'Asia', 'all')
168
  """
169
  try:
170
+ if region.lower() == "all":
171
+ timezones = pytz.common_timezones[:20] # First 20 for brevity
172
+ return f"Common timezones (first 20): {', '.join(timezones)}"
173
+ else:
174
+ filtered = [tz for tz in pytz.common_timezones if tz.startswith(region)]
175
+ return f"Timezones in {region}: {', '.join(filtered[:30])}"
176
  except Exception as e:
177
+ return f"Error listing timezones: {str(e)}"
178
 
 
179
  final_answer = FinalAnswerTool()
 
180
 
181
+ model = HfApiModel(
182
  max_tokens=2096,
183
  temperature=0.5,
184
  model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
185
  custom_role_conversions=None,
186
  )
187
 
188
+ # Load image generation tool from Hub
189
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
190
 
 
191
  with open("prompts.yaml", 'r') as stream:
192
  prompt_templates = yaml.safe_load(stream)
193
+
194
  agent = CodeAgent(
195
  model=model,
196
  tools=[
197
  final_answer,
198
+ web_search,
199
+ get_current_time_in_timezone,
200
  calculate,
201
+ get_weather,
202
+ read_file,
203
+ write_file,
204
  convert_currency,
205
+ get_wikipedia_summary,
206
+ list_common_timezones,
207
+ image_generation_tool,
 
 
 
208
  ],
209
  max_steps=6,
210
  verbosity_level=1,