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 = thread.id,
role = “user”,
content = “what is the biggest and most expensive villa in bali”
)

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

import time
time.sleep(20)

run_status = client.beta.threads.runs.retrieve(
thread_id = thread.id,
run_id = run.id
)

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

for msg in messages.data:
    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 = client.chat.completions.create(
        model=self.model_name,
        messages=conversation,
        temperature=0,
        top_p=1,
        frequency_penalty=0,    
        presence_penalty=0
    )
    return response.choices[0].message.content

dont forget to import:

from openai import OpenAI
from config import OPENAI_API_KEY
6 Likes

Try to add these two lines in your request.py:

import os

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

3 Likes

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.

3 Likes

“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

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

openai.api_key=api_data

completion=openai.Completion()

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

engine=pyttsx3.init('sapi5')
voices=engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)

def speak(text):
    engine.say(text)
    engine.runAndWait()

speak("Hello How Are You? ")

def takeCommand():
    r=sr.Recognizer()
    with sr.Microphone() as source:
        print('Listening....')
        r.pause_threshold = 1
        audio = r.listen(source)
    try:
        print("Recognizing.....")
        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:
        query=takeCommand().lower()
        ans=Reply(query)
        print(ans)
        speak(ans)
        if 'open youtube' in query:
            webbrowser.open("www.youtube.com")
        if 'open google' in query:
            webbrowser.open("www.google.com")
        if 'bye' in query:
            break

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

ERROR is
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\tempCodeRunnerFile.py”, line 9, in
completion=openai.Completion()
^^^^^^^^^^^^^^^^^^^
File “C:\Users\qasee\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\openai\lib_old_api.py”, line 39, in call
raise APIRemovedInV1(symbol=self._symbol)
openai.lib._old_api.APIRemovedInV1:

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: