pythonopenai-apichatgpt-apigpt-3gpt-4

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


Solution

  • 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:

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