Skip to content

Commit f601c64

Browse files
committed
fix: graceful failure if google geolocation api key is missing.
1 parent 01a04ab commit f601c64

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

api/terraform/python/openai_api/lambda_openai_function/function_weather.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,14 @@
3030

3131

3232
# Google Maps API key
33-
gmaps = googlemaps.Client(key=settings.google_maps_api_key)
33+
gmaps = None
34+
try:
35+
gmaps = googlemaps.Client(key=settings.google_maps_api_key)
36+
# pylint: disable=broad-exception-caught
37+
except ValueError as value_error:
38+
print(
39+
f"Could not initialize Google Maps API. Setup the Google Geolocation API service: https://developers.google.com/maps/documentation/geolocation/overview. {value_error}"
40+
)
3441

3542
# Make sure all required weather variables are listed here
3643
# The order of variables in hourly or daily is important to assign them correctly below
@@ -44,6 +51,12 @@
4451
# pylint: disable=too-many-locals
4552
def get_current_weather(location, unit="METRIC"):
4653
"""Get the current weather in a given location as a 24-hour forecast"""
54+
if gmaps is None:
55+
retval = {
56+
"error": "Google Maps Geolocation service is not initialized. Setup the Google Geolocation API service: https://developers.google.com/maps/documentation/geolocation/overview, and add your GOOGLE_MAPS_API_KEY to .env"
57+
}
58+
return json.dumps(retval)
59+
4760
unit = unit or "METRIC"
4861
location = location or "Cambridge, MA, near Kendall Square"
4962
latitude: float = 0.0
@@ -57,8 +70,8 @@ def get_current_weather(location, unit="METRIC"):
5770
longitude = geocode_result[0]["geometry"]["location"]["lng"] or 0
5871
address = geocode_result[0]["formatted_address"]
5972
print(f"Getting weather for {address} ({latitude}, {longitude})")
60-
except googlemaps.exceptions.ApiError as e:
61-
print(f"Google Maps API error getting geo coordinates for {location}: {e}")
73+
except googlemaps.exceptions.ApiError as api_error:
74+
print(f"Google Maps API error getting geo coordinates for {location}: {api_error}")
6275
# pylint: disable=broad-exception-caught
6376
except Exception as e:
6477
print(f"An unexpected error occurred while getting geo coordinates for {location}: {e}")

0 commit comments

Comments
 (0)