openai.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

import openai

client = openai.OpenAI()

openai.api_key = ‘sk-’

assistant = client.beta.assistants.create(
name = “Salesman”,
instructions = “You are a salesman that sells villas in bali.”,
tools = [{“type”: “code_interpreter”}],
model = “gpt-4-1106-preview”

thread = client.beta.threads.create()

Student asks question

message = client.beta.threads.messages.create(
thread_id =,
role = “user”,
content = “what is the biggest and most expensive villa in bali”

run = client.beta.threads.runs.create(
thread_id =,
assistant_id =,
instructions = “Please address the user as Maxi.”

import time

run_status = client.beta.threads.runs.retrieve(
thread_id =,
run_id =

if run_status.status == ‘completed’:
messages = client.beta.threads.messages.list(
thread_id =

for msg in
    role = msg.role
    content = msg.content[0].text.value
    print(f"{role.capitalize()}: {content}")

I tried making the assistent in my code but i just get the openai.OpenAIError

how can i solve this?

pass your api key inside client call:

client = OpenAI(api_key=OPENAI_API_KEY)

    response =
    return response.choices[0].message.content

dont forget to import:

from openai import OpenAI
from config import OPENAI_API_KEY

Try to add these two lines in your

import os

os.environ[“OPENAI_API_KEY”] = “your key here”


I was having the same issue while using an IDE.
I fixed my issue by verifying my API key was setup…
(opened the command prompt and typed the command below. It should display your API key: echo %OPENAI_API_KEY%)
I then reset my IDE, and it worked.

1 Like

“from config import OPENAI_API_KEY”

Quick question, where do I create the config file and where do I save it? I am having because of how simple this is to find an answer in the forums

After setting up your .env file (which includes the Open AI API Key), try doing:

import os

from openai import OpenAI

from dotenv import load_dotenv

print(os.environ.get("OPENAI_API_KEY")) #key should now be available
import openai
from apikey import api_data
import pyttsx3
import speech_recognition as sr
import webbrowser



def Reply(question):
    prompt=f'Chando: {question}\n Jarvis: '
    response=completion.create(prompt=prompt, engine="text-davinci-002", stop=['\Chando'], max_tokens=200)
    return answer

engine.setProperty('voice', voices[0].id)

def speak(text):

speak("Hello How Are You? ")

def takeCommand():
    with sr.Microphone() as source:
        r.pause_threshold = 1
        audio = r.listen(source)
        query=r.recognize_google(audio, language='en-in')
        print("Chando Said: {} \n".format(query))
    except Exception as e:
        print("Say That Again....")
        return "None"
    return query

if __name__ == '__main__':
    while True:
        if 'open youtube' in query:
        if 'open google' in query:
        if 'bye' in query:

this is my code which chatGPT gave me to create my assistent
i can’t run this code with an ERROR please guide me i am doing everything well as GPT say’s

File path: invalid escape sequence ‘\C’
response=completion.create(prompt=prompt, engine=“text-davinci-002”, stop=[‘\Chando’], max_tokens=200)
Traceback (most recent call last):
File “z:\AI\Chat-gpt guide AI\Tutorial\”, line 9, in
File “C:\Users\qasee\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\openai\”, line 39, in call
raise APIRemovedInV1(symbol=self._symbol)

You tried to access openai.Completion, but this is no longer supported in openai>=1.0.0 - see the README at github openai openai-python for the API.

You can run openai migrate to automatically upgrade your codebase to use the 1.0.0 interface.

Alternatively, you can pin your installation to the old version, e.g. pip install openai==0.28

A detailed migration guide is available here: github openaiopenai python discussions 742

[Done] exited with code=1 in 1.755 seconds

1 Like

Hi, and welcome to the forum. Let’s get right into answering your code’s concerns.

The first problem I can see is that you tried to access openai.Completion, but this is no longer supported in openai>=1.0.0. You can read the page at github openai openai-python to discover those recent changes.

If you already had an existing code base, you can pin your python installation to the old library version, such as by installing an older library module with pip install openai==0.28

Since the AI hasn’t been trained on any of the recent changes to OpenAI models or APIs, you also can run openai migrate from a python interpreter within your code directory to automatically upgrade your codebase to use the 1.0.0 interface.

Your local user installation of Python 3.12 is a bleeding-edge version. I instead would uninstall that and install 3.10 for “all users”, which is not getting feature changes and does not have problems with libraries needed.

But mostly the fault is in letting AI write code you don’t understand, for models you haven’t researched. What if AI-written code called an AI model that cost you several dollars a question? Then you prompted AI into writing other off-base constructions, when you’d likely have intended to use the whisper audio transcription API of OpenAI .

You should absorb the “chat” section of the API documentation, and then also look at the AI models available and their pricing. If you want to just have code to make your first request, which will produce an error if your API account isn’t funded: