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
2 Likes

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

import os

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

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

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