Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

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"

$
0
0

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 keyfrom openai import OpenAIclient = OpenAI()openai.api_key = 'my secret key openai'# Prompt user for 2 questionsquestions = []for i in range(2):    question = input("Posez une question: ")    questions.append(question)# Use OpenAI to answer questionsanswers = []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 answersdf = pd.DataFrame({"Question": questions, "Réponse": answers})# Export dataframe to CSV filedf.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.


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>