Ferocious0xide's picture
Update app.py
5591fd4 verified
raw
history blame
8.58 kB
# Import required libraries
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
from typing import Dict, Tuple, Optional
# Utility function for geocoding
def get_coordinates(city: str) -> Optional[Tuple[float, float]]:
"""Get coordinates for any city using Open-Meteo Geocoding API."""
try:
geocoding_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1&language=en&format=json"
response = requests.get(geocoding_url, timeout=10)
if response.status_code == 200:
data = response.json()
if data.get("results"):
result = data["results"][0]
return (result["latitude"], result["longitude"])
return None
except Exception:
return None
# Tool 1: Weather Information
@tool
def get_weather(city: str) -> str:
"""Get current weather information for a specified city.
Args:
city: Name of any city in the world
Returns:
str: Weather information including temperature and conditions
"""
try:
coords = get_coordinates(city)
if not coords:
return f"Sorry, couldn't find coordinates for {city}. Please check the city name and try again."
lat, lon = coords
api_url = "https://api.open-meteo.com/v1/forecast"
params = {
"latitude": lat,
"longitude": lon,
"current": "temperature_2m,wind_speed_10m,relative_humidity_2m",
"hourly": "temperature_2m,relative_humidity_2m,wind_speed_10m"
}
response = requests.get(api_url, params=params, timeout=10)
if response.status_code == 200:
data = response.json()
current = data["current"]
weather_report = (
f"Current weather in {city}:\n"
f"🌡️ Temperature: {current['temperature_2m']}°C\n"
f"💨 Wind Speed: {current['wind_speed_10m']} km/h\n"
f"💧 Humidity: {current.get('relative_humidity_2m', 'N/A')}%\n"
f"\nWould you like to check local bike trails? Use get_bike_trails('{city}')"
)
return weather_report
else:
return f"Error fetching weather data. Status code: {response.status_code}"
except Exception as e:
return f"Error fetching weather data: {str(e)}"
# Tool 2: Biking Conditions
@tool
def check_biking_conditions(city: str) -> str:
"""Check if current weather conditions are good for biking in specified city.
Args:
city: Name of any city in the world
Returns:
str: Assessment of biking conditions based on weather
"""
try:
coords = get_coordinates(city)
if not coords:
return f"Sorry, couldn't find coordinates for {city}."
lat, lon = coords
api_url = "https://api.open-meteo.com/v1/forecast"
params = {
"latitude": lat,
"longitude": lon,
"current": "temperature_2m,wind_speed_10m",
"hourly": "temperature_2m,relative_humidity_2m,wind_speed_10m"
}
response = requests.get(api_url, params=params, timeout=10)
if response.status_code == 200:
data = response.json()
current = data["current"]
temp = current['temperature_2m']
wind_speed = current['wind_speed_10m']
# Assess conditions for biking
conditions = []
if wind_speed > 20:
conditions.append(f"⚠️ Wind speeds are high ({wind_speed} km/h)")
if temp < 10:
conditions.append(f"🌡️ It's cold ({temp}°C) - dress warmly")
elif temp > 30:
conditions.append(f"🌡️ It's hot ({temp}°C) - stay hydrated")
if conditions:
return f"Biking conditions in {city}:\n" + "\n".join(conditions)
else:
return f"👍 Great conditions for biking in {city}! {temp}°C with moderate wind speeds."
else:
return f"Error checking conditions. Status code: {response.status_code}"
except Exception as e:
return f"Error checking biking conditions: {str(e)}"
# Tool 3: Current Time in Timezone
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""A tool that fetches the current local time in a specified timezone.
Args:
timezone: A string representing a valid timezone (e.g., 'America/New_York')
"""
try:
tz = pytz.timezone(timezone)
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
return f"The current local time in {timezone} is: {local_time}"
except Exception as e:
return f"Error fetching time for timezone '{timezone}': {str(e)}"
# Mock trails data for dynamic trail suggestions
MOCK_TRAILS = {
"default_trails": [
{
"name": "{city} Riverside Path",
"difficulty": "Easy",
"length": "5.5 miles",
"description": "Scenic waterfront trail perfect for casual rides",
"features": ["Waterfront views", "Paved path", "Family-friendly"]
},
{
"name": "{city} Urban Loop",
"difficulty": "Moderate",
"length": "8.2 miles",
"description": "Popular city loop with diverse urban scenery",
"features": ["City views", "Mixed terrain", "Cultural spots"]
}
]
}
# Tool 4: Bike Trails
@tool
def get_bike_trails(city: str) -> str:
"""Get information about bike trails in a specified city.
Args:
city: Name of any city in the world
Returns:
str: Information about available bike trails
"""
# Generate dynamic trails for any city
trails = []
for trail_template in MOCK_TRAILS["default_trails"]:
trail = {
"name": trail_template["name"].format(city=city),
"difficulty": trail_template["difficulty"],
"length": trail_template["length"],
"description": trail_template["description"],
"features": trail_template["features"]
}
trails.append(trail)
response = f"🚲 Suggested Bike Trails in {city}:\n\n"
for trail in trails:
response += (
f"📍 {trail['name']}\n"
f" • Difficulty: {trail['difficulty']}\n"
f" • Length: {trail['length']}\n"
f" • Description: {trail['description']}\n"
f" • Features: {', '.join(trail['features'])}\n\n"
)
response += "(Note: These are suggested routes based on typical city features. Always verify local trails and conditions.)"
return response
# Initialize components
final_answer = FinalAnswerTool()
# Initialize the model
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
custom_role_conversions=None,
)
# Import image generation tool from Hub
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
# Example prompts.yaml content - save this in a file named prompts.yaml
PROMPT_TEMPLATES = """
default: |
You are a helpful assistant that provides weather information and local activity suggestions.
When someone asks about the weather, also consider suggesting bike trails and checking biking conditions.
Always provide helpful context about weather conditions for outdoor activities.
"""
# Save prompts to file
with open("prompts.yaml", 'w') as f:
f.write(PROMPT_TEMPLATES)
# Load prompt templates
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
# Initialize agent with all tools
agent = CodeAgent(
model=model,
tools=[
final_answer,
get_weather,
get_bike_trails,
check_biking_conditions,
get_current_time_in_timezone,
image_generation_tool
],
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
# Launch Gradio UI
if __name__ == "__main__":
GradioUI(agent).launch()