alamanna commited on
Commit
952f9a4
·
verified ·
1 Parent(s): 81917a3

Upload ai_agents_course_submission.py

Browse files
Files changed (1) hide show
  1. ai_agents_course_submission.py +213 -0
ai_agents_course_submission.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """AI Agents Course_Submission.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/138KHbO69DpJpUvuTVAvsZ53EyXZAdr6K
8
+ """
9
+
10
+ !pip install smolagents -U
11
+
12
+ pip install duckduckgo-search
13
+
14
+ !pip install requests
15
+
16
+ #login to hugging face
17
+ from huggingface_hub import notebook_login
18
+
19
+ notebook_login()
20
+
21
+ from smolagents import CodeAgent, tool, DuckDuckGoSearchTool, InferenceClientModel
22
+ import requests
23
+
24
+ @tool
25
+ def suggest_outfit(occasion: str) -> str:
26
+ """
27
+ Suggests an outfit based on the occasion.
28
+ Args:
29
+ occasion (str): The type of occasion for the event. Allowed values are:
30
+ - "casual": Outfit for casual event.
31
+ - "formal": Outfit for formal event.
32
+ - "active": Outfit for doing sport.
33
+ - "custom": Custom outfit.
34
+ """
35
+ if occasion == "casual":
36
+ return "T-shirt, Jeans and sneakers."
37
+ elif occasion == "formal":
38
+ return "White shirt, tie, blue suit and Oxford shoes."
39
+ elif occasion == "active":
40
+ return "Jogging trousers, T-shirt and trainers."
41
+ else:
42
+ return "Custom outfit for the fashion advisor."
43
+
44
+ @tool
45
+ def define_coordinates(city: str) -> dict:
46
+ """
47
+ Returns a dictionary with the geographical coordinates of a city.
48
+ Args:
49
+ city (str): A city name.
50
+ Returns:
51
+ A dictionary with the latitude, longitude and timezone of the city
52
+ """
53
+ city = city.strip()
54
+ if not city:
55
+ return {"error": "City name cannot be empty."}
56
+
57
+ url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1"
58
+
59
+ try:
60
+ response = requests.get(url)
61
+ data = response.json()
62
+
63
+ if "results" not in data or not data["results"]:
64
+ return {"error": f"No location found for city: {city}"}
65
+
66
+ result = data["results"][0]
67
+ return {
68
+ "latitude": result["latitude"],
69
+ "longitude": result["longitude"],
70
+ "timezone": result["timezone"]
71
+ }
72
+
73
+ except Exception as e:
74
+ return {"error": str(e)}
75
+
76
+ @tool
77
+ def get_weather(city: str) -> dict:
78
+ """
79
+ Returns a dictionary with the current weather conditions in a city.
80
+ Args:
81
+ city (str): A city name.
82
+ Returns:
83
+ A dictionary with: temperature, wind_speed, weather_code, weather_description and a summary of the current weather.
84
+ """
85
+ coords = define_coordinates(city)
86
+ if "error" in coords:
87
+ return {"error": coords["error"]}
88
+
89
+ url = f'https://api.open-meteo.com/v1/forecast?latitude={coords["latitude"]}&longitude={coords["longitude"]}&current_weather=true&timezone={coords["timezone"]}'
90
+
91
+ try:
92
+ response = requests.get(url)
93
+ data = response.json()
94
+ temperature = data["current_weather"]["temperature"]
95
+ wind_speed = data["current_weather"]["windspeed"]
96
+ weather_code = data["current_weather"]["weathercode"]
97
+
98
+ return {
99
+ "temperature": temperature,
100
+ "wind_speed": wind_speed,
101
+ "weather_code": weather_code,
102
+ }
103
+
104
+
105
+ except Exception as e:
106
+ return {"error": str(e)}
107
+
108
+ @tool
109
+ def classify_weather(city: str) -> str:
110
+ """
111
+ Classifies the weather in the city based on a conversion table.
112
+ Args:
113
+ city (str): A city name.
114
+ Return:
115
+ Weather description based on the following conversion table:
116
+ 0 Clear sky
117
+ 1–3 Mainly clear to partly cloudy
118
+ 45, 48 Fog and depositing rime fog
119
+ 51–57 Drizzle (light to dense)
120
+ 61–67 Rain (light to heavy)
121
+ 71–77 Snow fall (light to heavy)
122
+ 80–82 Rain showers
123
+ 85–86 Snow showers
124
+ 95 Thunderstorm
125
+ 96–99 Thunderstorm with hail
126
+ """
127
+ weather = get_weather(city)
128
+ if "error" in weather:
129
+ return f"Unable to classify weather due to error: {weather['error']}"
130
+
131
+ temperature = weather["temperature"]
132
+ wind_speed = weather["wind_speed"]
133
+ weather_code = weather["weather_code"]
134
+
135
+ if weather_code == 0:
136
+ weather_description = "clear sky"
137
+ elif 1 <= weather_code <= 3:
138
+ weather_description = "mainly clear to partly cloudy"
139
+ elif weather_code in [45, 48]:
140
+ weather_description = "fog or depositing rime fog"
141
+ elif 51 <= weather_code <= 57:
142
+ weather_description = "drizzle (light to dense)"
143
+ elif 61 <= weather_code <= 67:
144
+ weather_description = "rain (light to heavy)"
145
+ elif 71 <= weather_code <= 77:
146
+ weather_description = "snow fall (light to heavy)"
147
+ elif 80 <= weather_code <= 82:
148
+ weather_description = "rain showers"
149
+ elif 85 <= weather_code <= 86:
150
+ weather_description = "snow showers"
151
+ elif weather_code == 95:
152
+ weather_description = "thunderstorm"
153
+ elif 96 <= weather_code <= 99:
154
+ weather_description = "thunderstorm with hail"
155
+ else:
156
+ weather_description = "unknown weather conditions"
157
+
158
+ return (
159
+ f"The current temperature in {city} is {temperature}°C, "
160
+ f"with a wind speed of {wind_speed} km/h. "
161
+ f"Weather description: {weather_description}."
162
+ )
163
+
164
+ agent = CodeAgent(tools=[DuckDuckGoSearchTool(), suggest_outfit, define_coordinates, get_weather, classify_weather], model=InferenceClientModel())
165
+
166
+ response = agent.run("""
167
+ First, find the current weather in Rome.
168
+ Then, classify the weather based on standard weather codes (e.g. clear, rain, snow, etc).
169
+ Third, assess what kind of outfit would be comfortable for a park run given this weather.
170
+ Fourth, call the appropriate tool to suggest an outfit for that context.
171
+ Finally, summarize both the weather and outfit recommendations clearly in one paragraph.
172
+
173
+ """)
174
+ print(response)
175
+
176
+ import json
177
+
178
+ entry = {
179
+ "task_id": "task_id_rome_weather_outfit",
180
+ "model_answer": "The current weather in Rome is clear with a temperature of 29.5°C and a wind speed of 13.0 km/h. A comfortable outfit for a park run in this weather would be jogging trousers, a T-shirt, and trainers.",
181
+ "reasoning_trace": [
182
+ "Step 1: Called get_weather('Rome') to fetch current conditions.",
183
+ "Step 2: Used classify_weather('Rome') to interpret weather code (code 0 = clear sky).",
184
+ "Step 3: Determined that the task involves running in a park, which corresponds to the 'active' occasion.",
185
+ "Step 4: Called suggest_outfit('active') to retrieve clothing suitable for physical activity.",
186
+ "Step 5: Composed a final answer combining weather data and outfit suggestion into one summary."
187
+ ]
188
+ }
189
+
190
+ with open("submission.jsonl", "w") as f:
191
+ f.write(json.dumps(entry) + "\n")
192
+
193
+ from google.colab import files
194
+ files.download("submission.jsonl")
195
+
196
+ more_entries = [
197
+ {
198
+ "task_id": "task_id_milan_weather_outfit",
199
+ "model_answer": "The current weather in Milan is mainly clear with a temperature of 22.3°C and wind speed of 9.5 km/h. A suitable outfit for a walk would be a light jacket, casual trousers, and comfortable shoes.",
200
+ "reasoning_trace": [
201
+ "Step 1: Fetch Milan weather using get_weather('Milan').",
202
+ "Step 2: Interpret code via classify_weather — partly cloudy.",
203
+ "Step 3: Occasion inferred as casual walk.",
204
+ "Step 4: Called suggest_outfit('casual').",
205
+ "Step 5: Merged weather and outfit into a final summary."
206
+ ]
207
+ },
208
+ # Add more entries here as needed
209
+ ]
210
+
211
+ with open("submission.jsonl", "a") as f:
212
+ for entry in more_entries:
213
+ f.write(json.dumps(entry) + "\n")