File size: 8,575 Bytes
5591fd4
ebaf70b
9b5b26a
 
 
c19d193
6aae614
9b5b26a
ebaf70b
 
5591fd4
ebaf70b
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5b26a
5591fd4
9b5b26a
ebaf70b
 
 
9b5b26a
ebaf70b
 
 
 
9b5b26a
ebaf70b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5b26a
5591fd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
5591fd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6f8024
8c01ffb
5591fd4
c6f8024
 
 
 
 
 
8c01ffb
5591fd4
c6f8024
 
5591fd4
 
 
 
 
 
 
 
 
 
 
 
c6f8024
861422e
 
ebaf70b
c6f8024
8c01ffb
5591fd4
ebaf70b
 
 
 
 
 
 
 
8c01ffb
 
 
 
 
 
861422e
8fe992b
 
ebaf70b
5591fd4
 
1
2
3
4
5
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# 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()