Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
|
2 |
import datetime
|
3 |
import requests
|
4 |
import pytz
|
@@ -7,124 +7,6 @@ from tools.final_answer import FinalAnswerTool
|
|
7 |
|
8 |
from Gradio_UI import GradioUI
|
9 |
|
10 |
-
@tool
|
11 |
-
def get_weather_api_key() -> str:
|
12 |
-
"""Retrieves the OpenWeatherMap API key from an environment variable.
|
13 |
-
|
14 |
-
Returns:
|
15 |
-
The OpenWeatherMap API key, or an error message if not found.
|
16 |
-
"""
|
17 |
-
api_key = '978b53bb6550f5b81b031a823a63f5dc'
|
18 |
-
#api_key = os.getenv("OPENWEATHERMAP_API_KEY")
|
19 |
-
|
20 |
-
return api_key
|
21 |
-
'''
|
22 |
-
@tool
|
23 |
-
def get_weather_forecast(city: str, date: str, api_key: str) -> str:
|
24 |
-
"""Retrieves the weather forecast for a specified city and date using OpenWeatherMap API.
|
25 |
-
|
26 |
-
Args:
|
27 |
-
city: The name of the city.
|
28 |
-
date: The date in YYY-MM-DD format.
|
29 |
-
api_key: Your OpenWeatherMap API key.
|
30 |
-
|
31 |
-
Returns:
|
32 |
-
A string containing the weather forecast, or an error message.
|
33 |
-
"""
|
34 |
-
try:
|
35 |
-
date_obj = datetime.datetime.strptime(date, "%Y-%m-%d").date()
|
36 |
-
today = datetime.date.today()
|
37 |
-
if date_obj < today:
|
38 |
-
return "Cannot get weather from past dates."
|
39 |
-
|
40 |
-
# Convert date to Unix timestamp for OpenWeatherMap API
|
41 |
-
dt = int(datetime.datetime.combine(date_obj, datetime.datetime.min.time()).timestamp())
|
42 |
-
|
43 |
-
# Get latitude and longitude of the city using geocoding API
|
44 |
-
geocoding_url = f"http://api.openweathermap.org/geo/1.0/direct?q={city}&limit=1&appid={api_key}"
|
45 |
-
geocoding_response = requests.get(geocoding_url)
|
46 |
-
geocoding_data = geocoding_response.json()
|
47 |
-
|
48 |
-
if not geocoding_data:
|
49 |
-
return f"Could not find coordinates for {city}."
|
50 |
-
|
51 |
-
lat = geocoding_data[0]["lat"]
|
52 |
-
lon = geocoding_data[0]["lon"]
|
53 |
-
|
54 |
-
# Get historical weather data using One Call API
|
55 |
-
weather_url = f"https://api.openweathermap.org/data/3.0/onecall/day_summary?lat={lat}&lon={lon}&date={dt}&appid={api_key}"
|
56 |
-
weather_response = requests.get(weather_url)
|
57 |
-
weather_data = weather_response.json()
|
58 |
-
|
59 |
-
if "weather" in weather_data:
|
60 |
-
weather_description = weather_data["weather"][0]["description"]
|
61 |
-
temp_max = weather_data["temp"]["max"]
|
62 |
-
return f"{weather_description}, with a high of {temp_max} degrees Celsius."
|
63 |
-
else:
|
64 |
-
return "Weather data not available for the specified date."
|
65 |
-
|
66 |
-
except requests.exceptions.RequestException as e:
|
67 |
-
return f"Error connecting to OpenWeatherMap API: {e}"
|
68 |
-
except ValueError:
|
69 |
-
return "Invalid date format. Please use YYYY-MM-DD."
|
70 |
-
except KeyError:
|
71 |
-
return "Weather data not available or API key is invalid"
|
72 |
-
'''
|
73 |
-
|
74 |
-
@tool
|
75 |
-
def get_weather_forecast(city: str, date: str, api_key: str) -> str:
|
76 |
-
"""Retrieves the weather forecast for a specified city and date using OpenWeatherMap API.
|
77 |
-
|
78 |
-
Args:
|
79 |
-
city: The name of the city.
|
80 |
-
date: The date in YYYY-MM-DD format.
|
81 |
-
api_key: Your OpenWeatherMap API key.
|
82 |
-
|
83 |
-
Returns:
|
84 |
-
A string containing the weather forecast, or an error message.
|
85 |
-
"""
|
86 |
-
try:
|
87 |
-
date_obj = datetime.datetime.strptime(date, "%Y-%m-%d").date()
|
88 |
-
today = datetime.date.today()
|
89 |
-
if date_obj < today:
|
90 |
-
return "Cannot get weather from past dates."
|
91 |
-
|
92 |
-
# Convert date to Unix timestamp for OpenWeatherMap API
|
93 |
-
dt = int(datetime.datetime.combine(date_obj, datetime.datetime.min.time()).timestamp())
|
94 |
-
|
95 |
-
# Get latitude and longitude of the city using geocoding API
|
96 |
-
geocoding_url = f"http://api.openweathermap.org/geo/1.0/direct?q={city}&limit=1&appid={api_key}"
|
97 |
-
geocoding_response = requests.get(geocoding_url)
|
98 |
-
geocoding_data = geocoding_response.json()
|
99 |
-
|
100 |
-
if not geocoding_data:
|
101 |
-
return f"Could not find coordinates for {city}."
|
102 |
-
|
103 |
-
lat = geocoding_data[0]["lat"]
|
104 |
-
lon = geocoding_data[0]["lon"]
|
105 |
-
|
106 |
-
# Get weather data using One Call API day_summary endpoint
|
107 |
-
weather_url = f"https://api.openweathermap.org/data/3.0/onecall/day_summary?lat={lat}&lon={lon}&date={dt}&appid={api_key}"
|
108 |
-
weather_response = requests.get(weather_url)
|
109 |
-
weather_data = weather_response.json()
|
110 |
-
|
111 |
-
if "weather" in weather_data and weather_data["weather"]:
|
112 |
-
weather_description = weather_data["weather"][0]["description"]
|
113 |
-
temp_max = weather_data["temp"]["max"]
|
114 |
-
return f"{weather_description}, with a high of {temp_max} degrees Celsius."
|
115 |
-
elif "message" in weather_data:
|
116 |
-
return f"OpenWeatherMap API Error: {weather_data['message']}"
|
117 |
-
else:
|
118 |
-
return "Weather data not available for the specified date."
|
119 |
-
|
120 |
-
except requests.exceptions.RequestException as e:
|
121 |
-
return f"Error connecting to OpenWeatherMap API: {e}"
|
122 |
-
except ValueError:
|
123 |
-
return "Invalid date format. Please use YYYY-MM-DD."
|
124 |
-
except KeyError:
|
125 |
-
return "Weather data not available or API key is invalid"
|
126 |
-
|
127 |
-
|
128 |
@tool
|
129 |
def calculate_days_until_date(future_date: str) -> int:
|
130 |
"""Calculates the number of days until a specified future date.
|
@@ -156,18 +38,17 @@ def generate_travel_plan(weather_forecast: str, days_until_date: int, city: str)
|
|
156 |
elif "sunny" in weather_forecast.lower():
|
157 |
return f"Enjoy the sunshine in {city}! You are travelling in {days_until_date} days."
|
158 |
else:
|
159 |
-
return f"Travel plan for {city} in {days_until_date} days. Weather is
|
160 |
-
|
161 |
@tool
|
162 |
def get_current_time_in_timezone(timezone: str) -> str:
|
163 |
"""A tool that fetches the current local time in a specified timezone.
|
|
|
164 |
Args:
|
165 |
timezone: A string representing a valid timezone (e.g., 'America/New_York').
|
166 |
"""
|
167 |
try:
|
168 |
-
# Create timezone object
|
169 |
tz = pytz.timezone(timezone)
|
170 |
-
# Get current time in that timezone
|
171 |
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
172 |
return f"The current local time in {timezone} is: {local_time}"
|
173 |
except Exception as e:
|
@@ -176,34 +57,33 @@ def get_current_time_in_timezone(timezone: str) -> str:
|
|
176 |
final_answer = FinalAnswerTool()
|
177 |
|
178 |
# 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:
|
179 |
-
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
|
180 |
|
181 |
model = HfApiModel(
|
182 |
-
max_tokens=2096,
|
183 |
-
temperature=0.5,
|
184 |
-
model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud',
|
185 |
-
#model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
|
186 |
-
custom_role_conversions=None,
|
187 |
)
|
188 |
|
189 |
-
|
190 |
# Import tool from Hub
|
191 |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
|
|
192 |
|
193 |
with open("prompts.yaml", 'r') as stream:
|
194 |
prompt_templates = yaml.safe_load(stream)
|
195 |
-
|
196 |
agent = CodeAgent(
|
197 |
model=model,
|
198 |
-
tools=[
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
], ## add your tools here (don't remove final answer)
|
207 |
max_steps=6,
|
208 |
verbosity_level=1,
|
209 |
grammar=None,
|
@@ -213,5 +93,4 @@ agent = CodeAgent(
|
|
213 |
prompt_templates=prompt_templates
|
214 |
)
|
215 |
|
216 |
-
|
217 |
GradioUI(agent).launch()
|
|
|
1 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
|
2 |
import datetime
|
3 |
import requests
|
4 |
import pytz
|
|
|
7 |
|
8 |
from Gradio_UI import GradioUI
|
9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
@tool
|
11 |
def calculate_days_until_date(future_date: str) -> int:
|
12 |
"""Calculates the number of days until a specified future date.
|
|
|
38 |
elif "sunny" in weather_forecast.lower():
|
39 |
return f"Enjoy the sunshine in {city}! You are travelling in {days_until_date} days."
|
40 |
else:
|
41 |
+
return f"Travel plan for {city} in {days_until_date} days. Weather is {weather_forecast}."
|
42 |
+
|
43 |
@tool
|
44 |
def get_current_time_in_timezone(timezone: str) -> str:
|
45 |
"""A tool that fetches the current local time in a specified timezone.
|
46 |
+
|
47 |
Args:
|
48 |
timezone: A string representing a valid timezone (e.g., 'America/New_York').
|
49 |
"""
|
50 |
try:
|
|
|
51 |
tz = pytz.timezone(timezone)
|
|
|
52 |
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
53 |
return f"The current local time in {timezone} is: {local_time}"
|
54 |
except Exception as e:
|
|
|
57 |
final_answer = FinalAnswerTool()
|
58 |
|
59 |
# 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:
|
60 |
+
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
|
61 |
|
62 |
model = HfApiModel(
|
63 |
+
max_tokens=2096,
|
64 |
+
temperature=0.5,
|
65 |
+
model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud',
|
66 |
+
# model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
|
67 |
+
custom_role_conversions=None,
|
68 |
)
|
69 |
|
|
|
70 |
# Import tool from Hub
|
71 |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
72 |
+
search_tool = DuckDuckGoSearchTool()
|
73 |
|
74 |
with open("prompts.yaml", 'r') as stream:
|
75 |
prompt_templates = yaml.safe_load(stream)
|
76 |
+
|
77 |
agent = CodeAgent(
|
78 |
model=model,
|
79 |
+
tools=[
|
80 |
+
final_answer,
|
81 |
+
image_generation_tool,
|
82 |
+
search_tool, #replace get_weather_forecast and get_weather_api_key
|
83 |
+
calculate_days_until_date,
|
84 |
+
generate_travel_plan,
|
85 |
+
get_current_time_in_timezone,
|
86 |
+
], ## add your tools here (don't remove final answer)
|
|
|
87 |
max_steps=6,
|
88 |
verbosity_level=1,
|
89 |
grammar=None,
|
|
|
93 |
prompt_templates=prompt_templates
|
94 |
)
|
95 |
|
|
|
96 |
GradioUI(agent).launch()
|