Option 1: OpenAI API key not set as an environment variable
Change this...
openai.api_key = os.getenv('sk-xxxxxxxxxxxxxxxxxxxx')
...to this.
openai.api_key = 'sk-xxxxxxxxxxxxxxxxxxxx'
Option 2: OpenAI API key set as an environment variable (recommended)
There are two ways to set the OpenAI API key as an environment variable:
- using an
.env file (easier, but don't forget to create a .gitignore file) or
- using Windows Environment Variables.
Way 1: Using an .env file
Change this...
openai.api_key = os.getenv('sk-xxxxxxxxxxxxxxxxxxxx')
...to this...
openai.api_key = os.getenv('OPENAI_API_KEY')
Also, don't forget to use the python-dotenv package. Your final Python file should look as follows:
# main.py
import os
from dotenv import load_dotenv
from openai import OpenAI
# Load environment variables from the .env file
load_dotenv()
# Initialize OpenAI client with the API key from environment variables
client = OpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
)
It's crucial that you create a .gitignore file not to push the .env file to your GitHub/GitLab and leak your OpenAI API key!
# .gitignore
.env
Way 2: Using Windows Environment Variables (source)
STEP 1: Open System properties and select Advanced system settings

STEP 2: Select Environment Variables

STEP 3: Select New
STEP 4: Add your name/key value pair
Variable name: OPENAI_API_KEY
Variable value: sk-xxxxxxxxxxxxxxxxxxxx
STEP 5: Restart your computer (IMPORTANT!)
Your final Python file should look as follows:
# main.py
import os
from dotenv import load_dotenv
from openai import OpenAI
# Initialize OpenAI client
# It will automatically use your OpenAI API key set via Windows Environment Variables
client = OpenAI()
os.getenv()expects the NAME of the ENV variable, not the value itself. If you're going to just paste the value of the key, I think you can just do:openai.api_key = "xxxxxxxxxx"and paste your key there.