filename:
agent-sandbox/tools/weather.py
branch:
main
back to repo
#!/usr/bin/env python3
import requests
import argparse
# Set a unique User-Agent header (required by the NWS API)
headers = {'User-Agent': 'sandbox_weather_tool ([email protected])'}
def get_coordinates(lat, lon):
"""Retrieve metadata for location to find forecast endpoint URL"""
points_url = f'https://api.weather.gov/points/{lat},{lon}'
points_response = requests.get(points_url, headers=headers)
if points_response.status_code != 200:
print(f"Error fetching point data: {points_response.status_code}")
return None
points_data = points_response.json()
# Extract the forecast URL from the response
forecast_url = points_data['properties']['forecast']
# Retrieve the actual forecast data
forecast_response = requests.get(forecast_url, headers=headers)
if forecast_response.status_code != 200:
print(f"Error fetching forecast: {forecast_response.status_code}")
return None
forecast_data = forecast_response.json()
# Print the detailed forecast
print(forecast_data['properties']['periods'][0]['detailedForecast'])
def main():
parser = argparse.ArgumentParser(
description='Get weather forecast from NWS API',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='''
Examples:
%(prog)s 40.7128 -74.0060 Weather in NYC
%(prog)s 51.5074 -0.1278 Weather in London
%(prog)s 35.6762 139.7671 Weather in Tokyo
'''
)
parser.add_argument('lat', type=float, help='Latitude')
parser.add_argument('lon', type=float, help='Longitude')
args = parser.parse_args()
get_coordinates(args.lat, args.lon)
if __name__ == '__main__':
main()