aniketkno commited on
Commit
3670051
·
verified ·
1 Parent(s): 29000da

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -151
app.py CHANGED
@@ -1,154 +1,92 @@
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
- from tools.weather import WeatherForecast
8
-
9
- from Gradio_UI import GradioUI
10
-
11
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
12
- @tool
13
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
14
- #Keep this format for the description / args / args description but feel free to modify the tool
15
- """A tool that does nothing yet
16
- Args:
17
- arg1: the first argument
18
- arg2: the second argument
19
- """
20
- return "What magic will you build ?"
21
-
22
- @tool
23
- def get_current_time_in_timezone(timezone: str) -> str:
24
- """A tool that fetches the current local time in a specified timezone.
25
- Args:
26
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
27
- """
28
- try:
29
- # Create timezone object
30
- tz = pytz.timezone(timezone)
31
- # Get current time in that timezone
32
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
33
- return f"The current local time in {timezone} is: {local_time}"
34
- except Exception as e:
35
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
36
-
37
- @tool
38
- def get_weather_forecast(city_name: str) -> str:
39
- """A tool that fetches the current weather/temperature of a specified city.
40
- Args:
41
- city_name: A string representing a valid city (e.g., 'Bangalore').
42
- """
43
-
44
- latitude, longitude = get_coordinates_no_api_key(city_name)
45
-
46
- base_url = "https://api.open-meteo.com/v1/forecast" # No API key needed for this version
47
- params = {
48
- "latitude": latitude,
49
- "longitude": longitude,
50
- "hourly": "temperature_2m,precipitation,wind_speed",
51
- "daily": "temperature_2m_max,temperature_2m_min,precipitation_sum",
52
- "forecast_days": 7,
53
- "timezone": "auto"
54
- }
55
-
56
- try:
57
- response = requests.get(base_url, params=params) # No headers needed
58
- response.raise_for_status()
59
- weatherJSON = response.json()
60
- cityName = weatherJSON.get('location').get('name')
61
- cityTemp = weatherJSON.get('hourly').get('temperature_2m')
62
- averageTemp = round(mean(cityTemp), 1)
63
- hourlyunits = weatherJSON.get('hourly_units').get('temperature_2m')
64
- return weather_data
65
- return f"The current Temperature in {cityName} is {averageTemp}{hourlyunits}!"
66
- except requests.exceptions.RequestException as e:
67
- print(f"Error fetching weather data: {e}")
68
- return None
69
- except json.JSONDecodeError as e:
70
- print(f"Error decoding JSON response: {e}")
71
- return None
72
-
73
- def get_coordinates_no_api_key(city_name: str) -> [float, float]:
74
- """Gets coordinates using OpenStreetMap's Nominatim (no API key, but with limitations)."""
75
-
76
- # This approach is less reliable and might have rate limits.
77
- # It's suitable for basic use cases but not for production.
78
-
79
- geocoding_url = "https://nominatim.openstreetmap.org/search" # No API Key needed
80
- params = {
81
- "q": city_name,
82
- "format": "json",
83
- "limit": 1
84
- }
85
-
86
- try:
87
- response = requests.get(geocoding_url, params=params)
88
- response.raise_for_status()
89
- geocoding_data = response.json()
90
-
91
- if geocoding_data: # Check if any results were found
92
- latitude = float(geocoding_data[0]["lat"])
93
- longitude = float(geocoding_data[0]["lon"])
94
- return latitude, longitude
95
- else:
96
- print(f"Could not find coordinates for {city_name}")
97
  return None, None
98
 
99
- except requests.exceptions.RequestException as e:
100
- print(f"Error during geocoding: {e}")
101
- return None, None
102
- except (KeyError, IndexError, ValueError) as e: # Handle more potential errors
103
- print(f"Error parsing geocoding response: {e}")
104
- return None, None
105
-
106
- # def get_weather(city: str) -> str:
107
- # """A tool that fetches the current weather of a specified city.
108
- # Args:
109
- # city: A string representing a valid city (e.g., 'Bangalore').
110
- # """
111
- # try:
112
- # response = requests.get('https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&hourly=temperature_2m&models=bom_access_global')
113
- # weatherJSON = response.json()
114
- # cityName = weatherJSON.get('location').get('name')
115
- # cityTemp = weatherJSON.get('current').get('temp_c')
116
- # cityCondition = weatherJSON.get('current').get('condition').get('text')
117
- # return f"The current Temperature in {cityName} is {cityTemp} and conditions are {cityCondition}"
118
- # except Exception as e:
119
- # return f"Error fetching weather conditions for {city}"
120
-
121
- final_answer = FinalAnswerTool()
122
- weather = WeatherForecast()
123
-
124
- # 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:
125
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
126
-
127
- model = HfApiModel(
128
- max_tokens=2096,
129
- temperature=0.5,
130
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
131
- custom_role_conversions=None,
132
- )
133
-
134
-
135
- # Import tool from Hub
136
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
137
-
138
- with open("prompts.yaml", 'r') as stream:
139
- prompt_templates = yaml.safe_load(stream)
140
-
141
- agent = CodeAgent(
142
- model=model,
143
- tools=[weather, final_answer], ## add your tools here (don't remove final answer)
144
- max_steps=6,
145
- verbosity_level=1,
146
- grammar=None,
147
- planning_interval=None,
148
- name=None,
149
- description=None,
150
- prompt_templates=prompt_templates
151
- )
152
-
153
-
154
- GradioUI(agent).launch()
 
1
+ import json
 
2
  import requests
3
+ from typing import Any, Optional
4
+ from smolagents.tools import Tool
5
+
6
+
7
+ class WeatherForecast(Tool):
8
+ name = "weather_forecast"
9
+ description = "Performs a weather search via open-mateo with openstreetmaps to get latlon then returns the weather results."
10
+ inputs = {'city': {'type': 'string', 'description': 'The name of the city required for weather gathering.'}}
11
+ output_type = "string"
12
+
13
+ def __init__(self, max_results=10, **kwargs):
14
+ super().__init__()
15
+
16
+ def forward(self, city) -> str:
17
+ results = self.get_weather_forecast(city)
18
+ if len(results) == 0:
19
+ raise Exception("No results found! Try a less restrictive/shorter query.")
20
+ postprocessed_results = [f"[{result['title']}]({result['href']})\n{result['body']}" for result in results]
21
+ return "## Search Results\n\n" + "\n\n".join(postprocessed_results)
22
+
23
+
24
+ def get_weather_forecast(self, city_name: str) -> str:
25
+ """A tool that fetches the current weather/temperature of a specified city.
26
+ Args:
27
+ city_name: A string representing a valid city (e.g., 'Bangalore').
28
+ """
29
+
30
+ latitude, longitude = self.get_coordinates(city_name)
31
+
32
+ base_url = "https://api.open-meteo.com/v1/forecast" # No API key needed for this version
33
+ params = {
34
+ "latitude": latitude,
35
+ "longitude": longitude,
36
+ "hourly": "temperature_2m,precipitation,wind_speed",
37
+ "daily": "temperature_2m_max,temperature_2m_min,precipitation_sum",
38
+ "forecast_days": 7,
39
+ "timezone": "auto"
40
+ }
41
+
42
+ try:
43
+ response = requests.get(base_url, params=params) # No headers needed
44
+ response.raise_for_status()
45
+ weatherJSON = response.json()
46
+ cityName = weatherJSON.get('location').get('name')
47
+ cityTemp = weatherJSON.get('hourly').get('temperature_2m')
48
+ averageTemp = round(mean(cityTemp), 1)
49
+ hourlyunits = weatherJSON.get('hourly_units').get('temperature_2m')
50
+ return weather_data
51
+ return f"The current Temperature in {cityName} is {averageTemp}{hourlyunits}!"
52
+ except requests.exceptions.RequestException as e:
53
+ print(f"Error fetching weather data: {e}")
54
+ return None
55
+ except json.JSONDecodeError as e:
56
+ print(f"Error decoding JSON response: {e}")
57
+ return None
58
+
59
+ def get_coordinates(self, city_name: str) -> [float, float]:
60
+ """Gets coordinates using OpenStreetMap's Nominatim (no API key, but with limitations)."""
61
+
62
+ # This approach is less reliable and might have rate limits.
63
+ # It's suitable for basic use cases but not for production.
64
+
65
+ geocoding_url = "https://nominatim.openstreetmap.org/search" # No API Key needed
66
+ params = {
67
+ "q": city_name,
68
+ "format": "json",
69
+ "limit": 3
70
+ }
71
+
72
+ try:
73
+ response = requests.get(geocoding_url, params=params)
74
+ response.raise_for_status()
75
+ geocoding_data = response.json()
76
+ print(geocoding_data)
77
+
78
+ if geocoding_data: # Check if any results were found
79
+ latitude = float(geocoding_data[0]["lat"])
80
+ longitude = float(geocoding_data[0]["lon"])
81
+ return latitude, longitude
82
+ else:
83
+ print(f"Could not find coordinates for {city_name}")
84
+ return None, None
85
+
86
+ except requests.exceptions.RequestException as e:
87
+ print(f"Error during geocoding: {e}")
88
+ return None, None
89
+ except (KeyError, IndexError, ValueError) as e: # Handle more potential errors
90
+ print(f"Error parsing geocoding response: {e}")
 
 
 
 
 
91
  return None, None
92