Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,154 +1,92 @@
|
|
| 1 |
-
|
| 2 |
-
import datetime
|
| 3 |
import requests
|
| 4 |
-
import
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|