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