gustavoemc commited on
Commit
ad52654
·
verified ·
1 Parent(s): 3625359

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -36
app.py CHANGED
@@ -7,8 +7,7 @@ import requests
7
  import pytz
8
  import yaml
9
 
10
- from typing import Dict, Optional, Union
11
- from datetime import datetime
12
  from tools.final_answer import FinalAnswerTool
13
 
14
  from Gradio_UI import GradioUI
@@ -34,26 +33,28 @@ FinalAnswerTool – A built-in tool that lets the agent provide a final answer.
34
  # Tools allow the agent to interact with its environment (e.g., checking time, fetching images, etc.).
35
 
36
  # ✅ Nicaragua Weather Tool
 
 
 
 
37
  @tool
38
  def get_nicaragua_weather(city: str = "Managua") -> str:
39
- """
40
- Fetches real-time weather information for cities in Nicaragua using WeatherAPI service.
41
 
42
  Args:
43
- city (str): The name of the city in Nicaragua to get weather data for. Must be one of:
44
- 'Managua', 'León', 'Granada', 'Matagalpa', or 'Bluefields'. If an invalid
45
- city is provided, defaults to 'Managua'.
46
 
47
  Returns:
48
- str: A formatted string containing current weather information including:
49
- temperature in Celsius, weather description in Spanish, humidity percentage,
50
- and wind speed in km/h.
51
-
52
- Raises:
53
- RequestException: If there's a network error or API request fails
54
- KeyError: If the API response is missing expected data fields
55
  """
56
- # Configuration
 
 
 
 
 
57
  VALID_CITIES = {
58
  "Managua": "12.1328,-86.2504",
59
  "León": "12.4375,-86.8833",
@@ -62,31 +63,22 @@ def get_nicaragua_weather(city: str = "Managua") -> str:
62
  "Bluefields": "12.0137,-83.7647"
63
  }
64
 
65
- # Validate API key
66
- API_KEY = os.getenv("WEATHER_API_KEY")
67
- if not API_KEY:
68
- return "Error: API key is missing. Please add WEATHER_API_KEY in Hugging Face Secrets."
69
-
70
- # Validate city input (case-insensitive)
71
- normalized_input = city.lower().strip()
72
  valid_city = next(
73
- (c for c in VALID_CITIES.keys() if c.lower() == normalized_input),
74
  "Managua"
75
  )
76
-
77
- # Prepare API request
78
- base_url = "http://api.weatherapi.com/v1/current.json"
79
- url = f"{base_url}?key={API_KEY}&q={VALID_CITIES[valid_city]}&lang=es"
80
 
81
  try:
82
  # Make API request
 
83
  response = requests.get(url, timeout=10)
84
  response.raise_for_status()
85
  data = response.json()
86
 
87
- # Extract weather information
88
  current = data["current"]
89
- weather_info = {
90
  "description": current["condition"]["text"],
91
  "temp": current["temp_c"],
92
  "humidity": current["humidity"],
@@ -95,18 +87,18 @@ def get_nicaragua_weather(city: str = "Managua") -> str:
95
 
96
  # Format response
97
  prefix = f"Using Managua instead of {city}. " if valid_city != city else ""
98
- return (f"{prefix}{weather_info['description']}, "
99
- f"{weather_info['temp']}°C, humidity: {weather_info['humidity']}%, "
100
- f"wind speed: {weather_info['wind_speed']} km/h.")
101
 
102
  except requests.Timeout:
103
- return f"Error: Request timed out while fetching weather data for {city}"
104
  except requests.RequestException as e:
105
- return f"Error: Network error while fetching weather data for {city}: {str(e)}"
106
  except KeyError as e:
107
- return f"Error: Invalid data received from weather API: {str(e)}"
108
  except Exception as e:
109
- return f"Error: Unexpected error while fetching weather data for {city}: {str(e)}"
110
 
111
 
112
  # ✅ Nicaragua Biodiversity Facts
 
7
  import pytz
8
  import yaml
9
 
10
+ from typing import Dict
 
11
  from tools.final_answer import FinalAnswerTool
12
 
13
  from Gradio_UI import GradioUI
 
33
  # Tools allow the agent to interact with its environment (e.g., checking time, fetching images, etc.).
34
 
35
  # ✅ Nicaragua Weather Tool
36
+ import os
37
+ import requests
38
+ from typing import Dict
39
+
40
  @tool
41
  def get_nicaragua_weather(city: str = "Managua") -> str:
42
+ """Gets current weather information for a city in Nicaragua.
 
43
 
44
  Args:
45
+ city: The name of the Nicaraguan city to check weather for.
46
+ Valid options are: Managua, León, Granada, Matagalpa, and Bluefields.
47
+ If invalid city provided, defaults to Managua.
48
 
49
  Returns:
50
+ str: Current weather conditions including temperature, description, humidity and wind speed.
 
 
 
 
 
 
51
  """
52
+ # API Configuration
53
+ API_KEY = os.getenv("WEATHER_API_KEY")
54
+ if not API_KEY:
55
+ return "Error: API key is missing. Please add WEATHER_API_KEY in Hugging Face Secrets."
56
+
57
+ # Valid cities and their coordinates
58
  VALID_CITIES = {
59
  "Managua": "12.1328,-86.2504",
60
  "León": "12.4375,-86.8833",
 
63
  "Bluefields": "12.0137,-83.7647"
64
  }
65
 
66
+ # Validate city (case-insensitive)
 
 
 
 
 
 
67
  valid_city = next(
68
+ (c for c in VALID_CITIES if c.lower() == city.lower().strip()),
69
  "Managua"
70
  )
 
 
 
 
71
 
72
  try:
73
  # Make API request
74
+ url = f"http://api.weatherapi.com/v1/current.json?key={API_KEY}&q={VALID_CITIES[valid_city]}&lang=es"
75
  response = requests.get(url, timeout=10)
76
  response.raise_for_status()
77
  data = response.json()
78
 
79
+ # Extract weather data
80
  current = data["current"]
81
+ weather = {
82
  "description": current["condition"]["text"],
83
  "temp": current["temp_c"],
84
  "humidity": current["humidity"],
 
87
 
88
  # Format response
89
  prefix = f"Using Managua instead of {city}. " if valid_city != city else ""
90
+ return (f"{prefix}{weather['description']}, "
91
+ f"{weather['temp']}°C, humidity: {weather['humidity']}%, "
92
+ f"wind speed: {weather['wind_speed']} km/h.")
93
 
94
  except requests.Timeout:
95
+ return f"Error: Request timed out for {city}"
96
  except requests.RequestException as e:
97
+ return f"Error: Network error for {city}: {str(e)}"
98
  except KeyError as e:
99
+ return f"Error: Invalid API response: {str(e)}"
100
  except Exception as e:
101
+ return f"Error: Unexpected error: {str(e)}"
102
 
103
 
104
  # ✅ Nicaragua Biodiversity Facts