Ranadip Dutta
Ranadip Dutta

Reputation: 9183

OpenAI API: openai.api_key = os.getenv() not working

I am just trying some simple functions in Python with OpenAI APIs but running into an error:

I have a valid API secret key which I am using.

Code:

>>> import os
>>> import openai
>>> openai.api_key = os.getenv("I have placed the key here")
>>> response = openai.Completion.create(model="text-davinci-003", prompt="Say this is a test", temperature=0, max_tokens=7)

Simple test

Upvotes: 3

Views: 40467

Answers (2)

Rok Benko
Rok Benko

Reputation: 23088

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

Screenshot 1

STEP 2: Select Environment Variables

Screenshot 2

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()

Upvotes: 15

Juanma Menendez
Juanma Menendez

Reputation: 20229

For me the solution was to add a load_dotenv() call.

from dotenv import load_dotenv
import os

# load environment variables from .env file
load_dotenv()

# get the environment variable
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

Upvotes: 4

Related Questions