OpenAI API error: "The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY env variable"

8k views Asked by At

I'm a little confused about using OpenAI in Python and need a little help to make this code work. I tried several solutions found on StackOverflow, none of them are working.

My goal is to make a Python code that asks two questions to the user, and then the gpt-3.5-turbo-instruct model finds the answer and exports a questions_reponses.csv with it. I will then convert this to XML to import it into a moodle environment.

Error message: OpenAIError: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable

Environnement: MacOS/Thonny

My code:

import pandas as pd

# Configure OpenAI API key

from openai import OpenAI
client = OpenAI()
openai.api_key = 'my secret key openai'


# Prompt user for 2 questions
questions = []
for i in range(2):
    question = input("Posez une question: ")
    questions.append(question)

# Use OpenAI to answer questions
answers = []
for question in questions:
    response = client.Completions.create(
        engine="gpt-3.5-turbo-instruct",
        prompt=f"Question: {question}\nRéponse:",
        max_tokens=1024,
        n=1,
        stop=None,
        temperature=0.7,
    )
    answer = response.choices[0].text.strip()
    answers.append(answer)

# Create a pandas dataframe with questions and answers
df = pd.DataFrame({"Question": questions, "Réponse": answers})

# Export dataframe to CSV file
df.to_csv("questions_reponses.csv", index=False)

print("Le fichier CSV a été créé avec succès.")`

I've tried to set the environment variable OPENAI_API_KEY in my os, but it didn't work (I always get the same error message). So I keep trying to set the key inside the code below. I don't know if my syntax is okay.

Remark on the answer

I am reaching out to the answerer here. As to the rules of Stack Exchange, I must do this in the question.

I've just tried option 1, same error message:

import pandas as pd

# Configure OpenAI API key

    import os
    from openai import OpenAI
    client = OpenAI()
    OpenAI.api_key = os.getenv('OPENAI_API_KEY')

    # Prompt user for 5 questions
    questions = []
    for i in range(1):
        question = input("Posez une question: ")
        questions.append(question)

    # Use OpenAI to answer questions
    answers = []
    for question in questions:
        response = client.Completions.create(
            engine="gpt-3.5-turbo-instruct",
            prompt=f"Question: {question}\nRéponse:",
            max_tokens=1024,
            n=1,
            stop=None,
            temperature=0.7,
        )
        answer = response.choices[0].text.strip()
        answers.append(answer)

    # Create a pandas dataframe with questions and answers
    df = pd.DataFrame({"Question": questions, "Réponse": answers})

    # Export dataframe to CSV file
    df.to_csv("questions_reponses.csv", index=False)

    print("Le fichier CSV a été créé avec succès.")

I've just tried option 2, same error message:

import pandas as pd

# Configure OpenAI API key

    from openai import OpenAI
    client = OpenAI()
    OpenAI.api_key = "sk-xxxxxxxxxxxxxx"




    # Prompt user for 5 questions
    questions = []
    for i in range(1):
        question = input("Posez une question: ")
        questions.append(question)

    # Use OpenAI to answer questions
    answers = []
    for question in questions:
        response = client.Completions.create(
            engine="gpt-3.5-turbo-instruct",
            prompt=f"Question: {question}\nRéponse:",
            max_tokens=1024,
            n=1,
            stop=None,
            temperature=0.7,
        )
        answer = response.choices[0].text.strip()
        answers.append(answer)

    # Create a pandas dataframe with questions and answers
    df = pd.DataFrame({"Question": questions, "Réponse": answers})

    # Export dataframe to CSV file
    df.to_csv("questions_reponses.csv", index=False)

    print("Le fichier CSV a été créé avec succès.")

I don't understand what is going on.

MIND: the answer works, it was just not checked in full

This is a remark from an outsider. As to the check of the heading above: the questioner has only tried the approach 1. With approach 2, it would work, that is why the questioner could already accept the answer.

3

There are 3 answers

6
Rok Benko On

You have two options how to set the OpenAI API key.

OPTION 1 (recommended): Set the OpenAI API key as an environment variable

import os
from openai import OpenAI
client = OpenAI()
OpenAI.api_key = os.getenv('OPENAI_API_KEY')

Note: After you set an environment variable, you need to restart the computer! Only after restarting the computer will the environment variable start working.

OPTION 2

from openai import OpenAI
client = OpenAI()
OpenAI.api_key = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

However, there's a slightly different approach displayed in the official GitHub repository for the OpenAI Python SDK:

import os
from openai import OpenAI
client = OpenAI(
    api_key=os.environ.get("OPENAI_API_KEY"),
)

So, now we have two approaches to setting the OpenAI API key as an environment variable:

OPTION 1 - APPROACH 1

import os
from openai import OpenAI
client = OpenAI()
OpenAI.api_key = os.getenv('OPENAI_API_KEY')

OPTION 1 - APPROACH 2

import os
from openai import OpenAI
client = OpenAI(
    api_key=os.environ.get("OPENAI_API_KEY"),
)

The difference is that the first approach sets the API key after creating the OpenAI class instance, while the second approach allows you to set the API key during instantiation by passing it as a parameter.

I tested the first approach with the newest OpenAI Python SDK version, and it still works.

0
Siddharth On

First pip install python-dotenv

Then set your .env file

OPENAI_API_KEY="*****"

NOW

    import os
    from openai import OpenAI
    from dotenv import load_dotenv
    
    load_dotenv()
    
    client = OpenAI(
        api_key=os.environ.get("OPENAI_API_KEY"),
    )

    //CODE HERE
0
Vivek Chaudhari On

please check the openai version first, above answers might work for older versions

pip show openai

Version: 1.13.3
Summary: The official Python library for the openai API
Home-page: 
Author: 
Author-email: OpenAI <[email protected]>
License: 

following is the another approach to set OPENAI_API_KEY for openai version 1.x.x,

import os
import openai

key = 'sk-xxxxxxxxxxxxxxx' 

OR

key = os.environ['OPENAI_API_KEY']

client = openai.OpenAI(api_key=key)