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

Question:

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

Asked By: Ranadip Dutta

||

Answers:

Option 1: OpenAI API not as environmental variable

Change this…

openai.api_key = os.getenv('sk-xxxxxxxxxxxxxxxxxxxx')

…to this.

openai.api_key = 'sk-xxxxxxxxxxxxxxxxxxxx'

Option 2: OpenAI API as an environmental variable (recommended)

Change this…

openai.api_key = os.getenv('sk-xxxxxxxxxxxxxxxxxxxx')

…to this…

openai.api_key = os.getenv('OPENAI_API_KEY')

How to set OpenAI API as an environment variable?

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

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.