Building Weather AI Agent: My First Development Challenge!



Why a Weather Information Agent?

Initially, I considered a more ambitious project, like an RSS feed summarization agent. However, as someone learning independently from scratch, I decided that “quick gratification” was paramount. The weather information agent is the perfect starting point for those, like me, new to AI agent development, thanks to the following advantages:

  • Simple Data Source: You only need to work with one API, like OpenWeatherMap.
  • Straightforward Data Processing: No complex AI processing (e.g., text summarization) is required; simply display the data received from the API!
  • Clear Input/Output: Just enter a city name, and the current weather information appears instantly.
  • Fast Results: You can write the code and run it immediately to see the results, making the development process enjoyable.

Development Schedule (Complete in 3 Days!)

I’ve set a goal to complete this project within 3 days. It’s quicker than you might think, so feel free to use this schedule as your guide!

  • Day 1: Development Environment Setup & API Key Acquisition
  • Day 2: Core Functionality Implementation (API Calls & Data Processing)
  • Day 3: Agent Completion & Testing

Detailed Development Items: Step-by-Step Guide

Now, I’ll walk you through each development phase in detail. Just follow these steps!

Step 1: Prepare Your Development Environment (Day 1 Morning)

This step covers the fundamental setup required for any Python project you’ll undertake in the future.

  1. Install Python:
    • Visit the Official Python Website to download and install the latest version.
    • Crucially, make sure to check the “Add Python.exe to PATH” option during installation! This is vital for using Python commands directly in your terminal.
    • Verify Installation: Open your terminal (Command Prompt on Windows) and type python --version or python3 --version. If you see the version information (e.g., Python 3.x.x), you’re all set.
  2. Install and Configure Visual Studio Code (VS Code):
    • Download and install VS Code from the Official VS Code Website for your operating system.
    • Launch VS Code. Click the ‘Extensions’ icon (the square icon on the left sidebar), search for “Python,” and install the ‘Python’ extension provided by Microsoft (look for the blue checkmark).
  3. Set Up a Virtual Environment:
    • It’s a great habit to manage libraries independently for each project, preventing conflicts with other projects or your system’s global Python installation.
    • In VS Code, go to ‘File’ > ‘Open Folder…’ and create a new folder named my_weather_agent.
    • Open the VS Code terminal (‘Terminal’ > ‘New Terminal’).
    • Create the virtual environment with this command: python -m venv venv
    • Activate the newly created virtual environment:
      • Windows: .\venv\Scripts\activate
      • macOS/Linux: source venv/bin/activate
    • You’ll know it’s successful when (venv) appears before your terminal prompt. Now you can install libraries and run code within this isolated environment.

Step 2: OpenWeatherMap API Key Acquisition and Understanding (Day 1 Afternoon)

We’ll use OpenWeatherMap as the core service to retrieve weather information.

  1. Register with OpenWeatherMap and Get Your API Key:
    • Go to the OpenWeatherMap Website, sign up, and log in.
    • After logging in, click the ‘API keys’ tab at the top. You’ll see an automatically generated default API key. Copy this key and keep it safe! (Never expose it publicly.)
    • Note: It might take a few minutes to up to 2 hours for the API key to become active after issuance.
  2. Briefly Understand the API Documentation:
    • Take a quick look at the Current Weather Data API documentation.
    • The most important things to note are the API call URL and required parameters like q (city name), appid (your API key), units (temperature unit: metric for Celsius), and lang (language: kr for Korean).
    • Familiarize yourself roughly with the JSON response structure returned by the API. You’ll find temp and humidity under the main section, and description within the weather list.

Step 3: Implement Core Functionality (Day 2 Morning)

Now, it’s time to write the Python code that fetches and displays the actual weather information.

  1. Install Required Libraries:
    • requests: Used for making HTTP requests to web APIs.
    • python-dotenv: Used for securely managing API keys by loading them from a .env file.
    • In your activated VS Code terminal, run the following command
pip install requests python-dotenv

  1. Securely Manage Your API Key (.env file):
    • In your project folder (my_weather_agent) within VS Code, create a new file named .env.
    • Save your API key in the .env file like this (no spaces around the equals sign):OPENWEATHER_API_KEY="PASTE_YOUR_API_KEY_HERE"
    • Important: This .env file should never be uploaded to Git (GitHub). (We’ll add it to .gitignore later.)
  2. Create weather_agent.py and Write Code:
    • Create a new Python file named weather_agent.py inside your project folder.
    • Copy and paste the following code. Read through the detailed comments to understand each line and its purpose.
# weather_agent.py

import os
import requests
from dotenv import load_dotenv

# --- 1. Load Configurations ---
load_dotenv() # Loads environment variables from .env file
API_KEY = os.getenv("OPENWEATHER_API_KEY") # Retrieves the API key

BASE_URL = "http://api.openweathermap.org/data/2.5/weather"

if not API_KEY:
    print("Warning: OpenWeatherMap API key is not set in the .env file.")
    print("Please add your key to `.env` in the format `OPENWEATHER_API_KEY=\"YOUR_API_KEY\"`.")
    # Program won't function correctly without the key.

# --- 2. Function to Fetch Weather Data ---
def get_weather_data(city_name):
    """
    Calls the OpenWeatherMap API with the given city name to fetch weather data.
    """
    params = {
        "q": city_name,
        "appid": API_KEY,
        "units": "metric", # Celsius
        "lang": "kr" # Korean description
    }

    try:
        response = requests.get(BASE_URL, params=params)
        response.raise_for_status() # Raises an HTTPError for bad responses (4xx or 5xx)

        weather_data = response.json() # Converts JSON response to a Python dictionary
        return weather_data
    except requests.exceptions.RequestException as e:
        print(f"Network error or API request failed: {e}")
        return None
    except ValueError as e:
        print(f"API response parsing error: {e}. Response content: {response.text[:200]}...")
        return None
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        return None

# --- 3. Function to Display Weather Information Nicely ---
def display_weather_info(weather_data):
    """
    Displays the fetched weather data neatly in the console.
    """
    if weather_data is None:
        print("Could not retrieve weather information. Please check the city name or API key settings.")
        return

    try:
        city = weather_data["name"]
        country = weather_data["sys"]["country"]
        temperature = weather_data["main"]["temp"]
        feels_like = weather_data["main"]["feels_like"]
        humidity = weather_data["main"]["humidity"]
        description = weather_data["weather"][0]["description"]
        wind_speed = weather_data["wind"]["speed"]
        pressure = weather_data["main"]["pressure"]

        print(f"\n--- Current Weather in {city}, {country} ---")
        print(f"Weather Condition: {description.capitalize()}")
        print(f"Current Temperature: {temperature}°C")
        print(f"Feels Like: {feels_like}°C")
        print(f"Humidity: {humidity}%")
        print(f"Wind Speed: {wind_speed} m/s")
        print(f"Pressure: {pressure} hPa")
        print("-----------------------------------\n")
    except KeyError as e:
        print(f"Required information not found in weather data: {e}")
        print("API response structure might be different than expected, or information is missing.")
        print(f"Full API response (for debugging): {weather_data}")
    except IndexError as e:
        print(f"Weather condition information not found: {e}")
        print(f"Full API response (for debugging): {weather_data}")
    except Exception as e:
        print(f"An unexpected error occurred while displaying weather info: {e}")

# --- 4. Main Execution Block ---
if __name__ == "__main__":
    print("Welcome to the AI Weather Information Agent!")
    print("Type 'exit' or 'quit' to stop.")

    while True: # Loop until the user types 'exit' or 'quit'
        city_input = input("Enter the city name to get weather for (e.g., Seoul, Tokyo, New York): ")

        if city_input.lower() in ["exit", "quit"]:
            print("Exiting the weather agent. Thank you for using!")
            break

        if not API_KEY:
            print("Cannot fetch weather information. API key is missing. Please check your .env file.")
            continue

        weather_data = get_weather_data(city_input) # Fetch weather data
        display_weather_info(weather_data) # Display weather information

Step 4: Agent Completion and Testing (Day 3)

You’re almost there! Now, run your code and ensure it works correctly under various conditions.

  1. Execute and Test the Code:
    • In the VS Code terminal (with the virtual environment activated), type python weather_agent.py and press Enter.
    • Normal Operation Test: Enter several city names like Seoul, Tokyo, New York, and confirm that the correct weather information is displayed.
    • Error Handling Test:
      • Enter a non-existent city name, such as asdfasdf or Nocity. Confirm that an appropriate message like “Could not retrieve weather information…” appears.
      • Temporarily disconnect your internet connection and run the script to see if network errors are handled gracefully.
      • Temporarily delete or change the API key in your .env file and verify that the warning about the missing API key is displayed.
    • Exit Test: Type exit or quit to ensure the program terminates cleanly.
  2. Code Cleanup and Comments:
    • Review your code and add comments (#) to explain complex logic or functions, making it easier to understand later.
    • Remove or comment out unnecessary print statements (especially for debugging).
  3. (Optional) Create README.md and Manage Versions with Git/GitHub:
    • Create README.md: In your project folder, create a README.md file. Write a brief overview of your agent, how to install and use it, and its main features, using Markdown syntax.
    • Update .gitignore File: If you don’t have a .gitignore file in your project folder, create one. Add the following lines to prevent sensitive information or unnecessary files from being uploaded to Git:venv/ __pycache__/ .env
    • Git Commit and Push: Use the following commands to manage your code versions and back them up to GitHub: git add ., git commit -m "feat: Initial weather agent complete", git push.