Error: 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

I am experiencing the following error message: 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

The API Key is correct.

Does anybody how to solve this?

import os
from openai import OpenAI


client = OpenAI(
    api_key=os.environ.get("API KEY"),
)

    # Call the GPT API
    response = client.chat.completions.create(
        model="gpt-3.5-turbo", 
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": context},   #deleted context variable from this post
        ],
        max_tokens=max_tokens,
        temperature=0.7,
    )

    print(completion.choices[0].message)

1 Like

If you have set the actual variable OPENAI_API_KEY, then you do not need to (improperly) add an API key as client parameter in the python module. It is automatically obtained.

unfortunately, still same error.
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

1 Like

Do you know how to set an environment variable on your operating system?

You can ask ChatGPT how to set one.

1 Like