Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,6 +5,7 @@ import pytz
|
|
| 5 |
import gradio as gr
|
| 6 |
from geopy.geocoders import Nominatim
|
| 7 |
from timezonefinder import TimezoneFinder
|
|
|
|
| 8 |
|
| 9 |
@tool
|
| 10 |
def get_timezone_by_city(city: str) -> str:
|
|
@@ -18,10 +19,8 @@ def get_timezone_by_city(city: str) -> str:
|
|
| 18 |
return f"Error: Expected a string for city, got: {type(city)}"
|
| 19 |
try:
|
| 20 |
geolocator = Nominatim(user_agent="smolagents_bot")
|
| 21 |
-
# Пробуем поиск с полным запросом
|
| 22 |
location = geolocator.geocode(city, language="en")
|
| 23 |
if not location:
|
| 24 |
-
# Пробуем только город (до запятой)
|
| 25 |
city_name = city.split(",")[0].strip()
|
| 26 |
location = geolocator.geocode(city_name, language="en")
|
| 27 |
if not location:
|
|
@@ -49,6 +48,44 @@ def get_current_time_in_timezone(timezone: str) -> str:
|
|
| 49 |
except Exception as e:
|
| 50 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
@tool
|
| 53 |
def final_answer(answer: str) -> str:
|
| 54 |
"""Returns the final answer.
|
|
@@ -71,22 +108,24 @@ prompt_templates = {
|
|
| 71 |
"You are a helpful assistant that responds in the same language as the user's query. "
|
| 72 |
"Detect the language and return only the result, without explanations, images, or repeating instructions. "
|
| 73 |
"If the query contains a city name (e.g., 'Бураево', 'Осиновка', 'Fosnavåg', 'न्यू यॉर्क') or phrases like 'сколько времени', 'what time', 'quelle heure', "
|
| 74 |
-
"
|
|
|
|
|
|
|
| 75 |
"Always return the response via `final_answer()` in a code block like this:\n"
|
| 76 |
"```py\n"
|
| 77 |
"final_answer('YOUR ANSWER HERE')\n"
|
| 78 |
"```\n"
|
| 79 |
-
"Execute tools in sequence: first call get_timezone_by_city(city), then get_current_time_in_timezone(timezone). "
|
| 80 |
"Do NOT include tool calls, formatting like 'Current time in X: ', or invalid dates (e.g., '2023-03-22') inside final_answer(). "
|
| 81 |
-
"If the city is not found or the query is unclear, return an error message in the same language via final_answer(). "
|
| 82 |
"NEVER generate code without the ```py``` block or with invalid syntax. "
|
| 83 |
-
"Do NOT ask for clarifications
|
| 84 |
),
|
| 85 |
"default": "Response: {{question}}",
|
| 86 |
"planning": {
|
| 87 |
"initial_plan": (
|
| 88 |
"Analyze the query: {{question}}. If it contains a city name or phrases like 'сколько времени', "
|
| 89 |
-
"use `get_timezone_by_city` and `
|
| 90 |
"Write code in a code block:\n"
|
| 91 |
"```py\n"
|
| 92 |
"final_answer('YOUR ANSWER HERE')\n"
|
|
@@ -109,16 +148,18 @@ prompt_templates = {
|
|
| 109 |
},
|
| 110 |
"managed_agent": {
|
| 111 |
"execute": (
|
| 112 |
-
"Execute the task: {{question}}. If it contains a city name or phrases like 'сколько времени', use `get_timezone_by_city` and `
|
| 113 |
"Write code in a code block:\n"
|
| 114 |
"```py\n"
|
| 115 |
-
"
|
|
|
|
| 116 |
"timezone = get_timezone_by_city(city)\n"
|
| 117 |
-
"if
|
| 118 |
-
" result = get_current_time_in_timezone(timezone)\n"
|
| 119 |
-
" final_answer(result)\n"
|
| 120 |
-
"else:\n"
|
| 121 |
" final_answer(timezone)\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
"```"
|
| 123 |
),
|
| 124 |
"report": (
|
|
@@ -157,7 +198,7 @@ prompt_templates = {
|
|
| 157 |
|
| 158 |
agent = CodeAgent(
|
| 159 |
model=model,
|
| 160 |
-
tools=[final_answer, get_current_time_in_timezone, get_timezone_by_city],
|
| 161 |
max_steps=3,
|
| 162 |
verbosity_level=2,
|
| 163 |
prompt_templates=prompt_templates,
|
|
@@ -175,5 +216,5 @@ gr.Interface(
|
|
| 175 |
inputs="text",
|
| 176 |
outputs="text",
|
| 177 |
title="Helpful Assistant",
|
| 178 |
-
description="Hello! What city or town are you from? I can tell you the time,
|
| 179 |
).launch()
|
|
|
|
| 5 |
import gradio as gr
|
| 6 |
from geopy.geocoders import Nominatim
|
| 7 |
from timezonefinder import TimezoneFinder
|
| 8 |
+
import requests
|
| 9 |
|
| 10 |
@tool
|
| 11 |
def get_timezone_by_city(city: str) -> str:
|
|
|
|
| 19 |
return f"Error: Expected a string for city, got: {type(city)}"
|
| 20 |
try:
|
| 21 |
geolocator = Nominatim(user_agent="smolagents_bot")
|
|
|
|
| 22 |
location = geolocator.geocode(city, language="en")
|
| 23 |
if not location:
|
|
|
|
| 24 |
city_name = city.split(",")[0].strip()
|
| 25 |
location = geolocator.geocode(city_name, language="en")
|
| 26 |
if not location:
|
|
|
|
| 48 |
except Exception as e:
|
| 49 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 50 |
|
| 51 |
+
@tool
|
| 52 |
+
def get_air_quality(city: str) -> str:
|
| 53 |
+
"""Tool to fetch air quality data for a given city using OpenWeatherMap API.
|
| 54 |
+
Args:
|
| 55 |
+
city: A string representing the city name (e.g., 'Бирск', 'New York').
|
| 56 |
+
Returns:
|
| 57 |
+
A string with air quality index (AQI) and pollutant levels or an error message.
|
| 58 |
+
"""
|
| 59 |
+
if not isinstance(city, str):
|
| 60 |
+
return f"Error: Expected a string for city, got: {type(city)}"
|
| 61 |
+
try:
|
| 62 |
+
geolocator = Nominatim(user_agent="smolagents_bot")
|
| 63 |
+
location = geolocator.geocode(city, language="en")
|
| 64 |
+
if not location:
|
| 65 |
+
city_name = city.split(",")[0].strip()
|
| 66 |
+
location = geolocator.geocode(city_name, language="en")
|
| 67 |
+
if not location:
|
| 68 |
+
return f"Error: City '{city}' not found for air quality data."
|
| 69 |
+
|
| 70 |
+
api_key = os.getenv("OPENWEATHERMAP_API_KEY", "93f518fda8d24cf89aee7050c26b27e9")
|
| 71 |
+
url = f"http://api.openweathermap.org/data/2.5/air_pollution?lat={location.latitude}&lon={location.longitude}&appid={api_key}"
|
| 72 |
+
response = requests.get(url)
|
| 73 |
+
if response.status_code != 200:
|
| 74 |
+
return f"Error fetching air quality for '{city}': API returned status {response.status_code}"
|
| 75 |
+
|
| 76 |
+
data = response.json()
|
| 77 |
+
aqi = data["list"][0]["main"]["aqi"]
|
| 78 |
+
components = data["list"][0]["components"]
|
| 79 |
+
|
| 80 |
+
aqi_description = {1: "Good", 2: "Fair", 3: "Moderate", 4: "Poor", 5: "Very Poor"}
|
| 81 |
+
return (
|
| 82 |
+
f"Air quality in {city}: AQI {aqi} ({aqi_description.get(aqi, 'Unknown')})\n"
|
| 83 |
+
f"PM2.5: {components['pm2_5']} µg/m³, PM10: {components['pm10']} µg/m³\n"
|
| 84 |
+
f"CO: {components['co']} µg/m³, NO2: {components['no2']} µg/m³, SO2: {components['so2']} µg/m³, O3: {components['o3']} µg/m³"
|
| 85 |
+
)
|
| 86 |
+
except Exception as e:
|
| 87 |
+
return f"Error fetching air quality for '{city}': {str(e)}"
|
| 88 |
+
|
| 89 |
@tool
|
| 90 |
def final_answer(answer: str) -> str:
|
| 91 |
"""Returns the final answer.
|
|
|
|
| 108 |
"You are a helpful assistant that responds in the same language as the user's query. "
|
| 109 |
"Detect the language and return only the result, without explanations, images, or repeating instructions. "
|
| 110 |
"If the query contains a city name (e.g., 'Бураево', 'Осиновка', 'Fosnavåg', 'न्यू यॉर्क') or phrases like 'сколько времени', 'what time', 'quelle heure', "
|
| 111 |
+
"or if a city is mentioned in any context (e.g., 'Что там в Бирске?'), treat it as a request for the current time and air quality in that city. "
|
| 112 |
+
"Use `get_timezone_by_city` to find the timezone, `get_current_time_in_timezone` for the time, and `get_air_quality` for air quality data. "
|
| 113 |
+
"Combine results in a single response. "
|
| 114 |
"Always return the response via `final_answer()` in a code block like this:\n"
|
| 115 |
"```py\n"
|
| 116 |
"final_answer('YOUR ANSWER HERE')\n"
|
| 117 |
"```\n"
|
| 118 |
+
"Execute tools in sequence: first call get_timezone_by_city(city), then get_current_time_in_timezone(timezone), then get_air_quality(city). "
|
| 119 |
"Do NOT include tool calls, formatting like 'Current time in X: ', or invalid dates (e.g., '2023-03-22') inside final_answer(). "
|
| 120 |
+
"If the city is not found or the query is unclear (e.g., no city mentioned), return an error message in the same language via final_answer(). "
|
| 121 |
"NEVER generate code without the ```py``` block or with invalid syntax. "
|
| 122 |
+
"Do NOT ask for clarifications or generate responses outside the ```py``` block."
|
| 123 |
),
|
| 124 |
"default": "Response: {{question}}",
|
| 125 |
"planning": {
|
| 126 |
"initial_plan": (
|
| 127 |
"Analyze the query: {{question}}. If it contains a city name or phrases like 'сколько времени', "
|
| 128 |
+
"use `get_timezone_by_city`, `get_current_time_in_timezone`, and `get_air_quality`. "
|
| 129 |
"Write code in a code block:\n"
|
| 130 |
"```py\n"
|
| 131 |
"final_answer('YOUR ANSWER HERE')\n"
|
|
|
|
| 148 |
},
|
| 149 |
"managed_agent": {
|
| 150 |
"execute": (
|
| 151 |
+
"Execute the task: {{question}}. If it contains a city name or phrases like 'сколько времени', use `get_timezone_by_city`, `get_current_time_in_timezone`, and `get_air_quality`. "
|
| 152 |
"Write code in a code block:\n"
|
| 153 |
"```py\n"
|
| 154 |
+
"query = '{{question}}'.strip()\n"
|
| 155 |
+
"city = query.split(' в ')[-1].strip() if ' в ' in query else query\n"
|
| 156 |
"timezone = get_timezone_by_city(city)\n"
|
| 157 |
+
"if timezone.startswith('Error'):\n"
|
|
|
|
|
|
|
|
|
|
| 158 |
" final_answer(timezone)\n"
|
| 159 |
+
"else:\n"
|
| 160 |
+
" time_result = get_current_time_in_timezone(timezone)\n"
|
| 161 |
+
" air_result = get_air_quality(city)\n"
|
| 162 |
+
" final_answer(time_result + '\\n' + air_result)\n"
|
| 163 |
"```"
|
| 164 |
),
|
| 165 |
"report": (
|
|
|
|
| 198 |
|
| 199 |
agent = CodeAgent(
|
| 200 |
model=model,
|
| 201 |
+
tools=[final_answer, get_current_time_in_timezone, get_timezone_by_city, get_air_quality],
|
| 202 |
max_steps=3,
|
| 203 |
verbosity_level=2,
|
| 204 |
prompt_templates=prompt_templates,
|
|
|
|
| 216 |
inputs="text",
|
| 217 |
outputs="text",
|
| 218 |
title="Helpful Assistant",
|
| 219 |
+
description="Hello! What city or town are you from? I can tell you the time, air quality, and more!"
|
| 220 |
).launch()
|