3

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

Rok Benko
  • 14,265
  • 2
  • 24
  • 49
Ranadip Dutta
  • 8,857
  • 3
  • 29
  • 45
  • 2
    [Please do not upload images of code/data/errors when asking a question.](//meta.stackoverflow.com/q/285551). And you've cut out the most important part of the traceback. – Yevhen Kuzmovych Feb 01 '23 at 16:47
  • 3
    It looks like you pasted your actual API key, but `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. – Everett Feb 01 '23 at 16:48
  • @YevhenKuzmovych: Apologies. I will make sure to follow the standards. Thanks for pointing it out. – Ranadip Dutta Feb 02 '23 at 11:58

1 Answers1

9

Option 1: OpenAI API key not as an environmental variable

Change this...

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

...to this.

openai.api_key = 'sk-xxxxxxxxxxxxxxxxxxxx'


Option 2: OpenAI API key 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 do I set the OpenAI API key as an environmental 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

Rok Benko
  • 14,265
  • 2
  • 24
  • 49