Fashion Forecast

Level: Beginner

Language: Python

Gen AI API: OpenAI

Requirements:

Code: Fashion Forecast GitHub Repository

Tutorial

Are you tired of staring at your closet, pondering what to wear, only to step outside and realize you’ve totally misjudged the weather? This sample provides the basic building blocks to create the logic for an app that uses generative AI to curate the perfect ensemble based on the forecast. Rain or shine, you’ll be serving looks that turn heads and withstand elements!

Create a Virtual Environment

We’ll avoid installing everything system-wide and instead do our installations in a virtual environment. Enter the following commands in the terminal:

Mac

pip install virtualenv
python3 -m venv venv
source venv/bin/activate

PC

pip install virtualenv
python -m venv venv
.\venv\Scripts\activate

After activating the virtual environment, install the following libraries:

pip install python-dotenv
pip install openai

Create the Python file

Now that we have our virtual environment activated and packages installed, we’ll create the Python file for our code. Name the file weather.py and add the following import statements:

from dotenv import load_dotenv
import os
from openai import OpenAI
import requests

Get Your API Keys

Switch over to the browser and retrieve your API keys from both OpenAI and Weather API.

Create Environment Variables

Rather than hardcode your API keys into the code, we’ll create a .env file to store the keys. The environment variable for OpenAI is pretty straight-forward, it’s just your API key.

OPENAI_API_KEY=<YOUR API KEY>

As for the Weather API, we’re going to include the /current.json endpoint and append a few additional query parameters. Those query parameters include:

  • API key

  • Zip code

WEATHER_API_CALL=http://api.weatherapi.com/v1/current.json?key=<YOUR API KEY>&q=<ZIP CODE>

Load the Environment Variables

In the weather.py file, load the environment variables so that our code can access both the OpenAI and WeatherAPI keys.

load_dotenv()

Create Variables

Let’s create some variables to minimize the amount of characters we’ll later need to type! First create a client variable and assign it to the OpenAI() function.

client = OpenAI()

Next, create an api_url variable and assign it to the WEATHER_API_CALL variable that contains our Weather API endpoint.

api_url = os.getenv("WEATHER_API_CALL")

Create the getWeather() Function

We’ll keep things tidy by placing the API requests inside a getWeather() function. Let’s format the request within a try/except block so that we can handle potential errors or exceptions that may occur during the request process.

def getWeather():
    try: 
        response = requests.get(api_url)
        response.raise_for_status()

        data = response.json()
        
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP Error: {http_err}")
    except requests.exceptions.RequestException as req_err:
        print(f"Request Error: {req_err}")
    except Exception as err:
        print(f"An error occurred: {err}")

Create Variables for the Response

There’s only a few values we’ll need from the JSON response:

  • location

  • temperature

  • condition

Let’s create variables for those values in the try block and assign the corresponding keys from the JSON response.

location = data['location']['name']
temperature = int(data['current']['temp_f'])
condition = data['current']['condition']['text']

Setup the OpenAPI Prompt

OK, so this is the fun part! We’re now adding in some generative AI to get our generated outfit suggestion that’ll be based on the weather. We’ll use the Chat Completion endpoint. Still in the try block, create a completion variable and assign the function call for creating a Chat Completion.

completion = client.chat.completions.create(

)

Add the Model parameter

We’ll use the gpt-4-turbo model for this sample. However, you’re welcome to use whichever version of the model you prefer.

completion = client.chat.completions.create(
model="gpt-4-turbo",
)

Assign the System and User Roles & Context

Next, we need to assign roles for both the system and the user. The system is the model and the user is you! We can do this within a messages list and place the aforementioned information into two separate dictionaries.

We can tell the system more about their persona and also establish any rules for the model to follow. Since we want to generate an outfit suggestion, I chose Diana Vreeland - former editor-in-chief for Vogue! I also added a few additional details such as minimizing the output to 2 sentences and instructing the model to use the degree symbol.

completion = client.chat.completions.create(
model="gpt-4-turbo",
messages=[
      {"role": "system", "content": "You are a meteorologist who 
        gives the weather report in the style of Diana Vreeland. 
        You provide outfit suggestions according to the temperature. 
        Your report should not exceed 2 sentences. Mention the 
        weather with the ° symbol."},
  ]
)

As for the user, we’ll include a template for a prompt that’ll incorporate the JSON response values from the Weather API call. We can use f-string formatting to keep our code clean!

completion = client.chat.completions.create(
model="gpt-4-turbo",
messages=[
      {"role": "system", "content": "You are a meteorologist who 
        gives the weather report in the style of Diana Vreeland. 
        You provide outfit suggestions according to the temperature. 
        Your report should not exceed 2 sentences. Mention the 
        weather with the ° symbol."},
      {"role": "user", "content": f"Give me the weather report for 
        a {temperature} degree fahrenheit day in {location}. The 
        condition is {condition}."}
  ]
)

Print the Model’s Response

To view the model’s response to our prompt, we can print the content within the message dictionary of the JSON response. Be sure to add the print function within the try block!

print(completion.choices[0].message.content)

Call the getWeather() Function

The final thing we need to add to our code is a call to the getWeather() function. Add the call outside the function.

getWeather()

Get Your Fashion Forecast!

Now that everything’s complete, run the code to get an outfit suggestion based on the current weather. Change the system content as needed to adjust the model’s output. Maybe try a different fashion figure? Whatever you do, enjoy!

Sample Response

Darlings, on this moody 60°F day in Los Angeles, 
where the sun shyly hides behind a veil of clouds, 
consider draping yourself in a lightweight trench - 
a whisper of mystery with the practicality of chic. 
Accessorize with a silk scarf and your most daring 
sunglasses, turning the overcast into your personal stage.
Previous
Previous

From Logic to Intuition: Gen AI Impact on Analytical Thinking

Next
Next

The Future is Fluid