3

When attempting to use model.list(), the library encounters an authentication error due to the incorrect configuration of the API key. I've been continuously receiving the error message.

import openai

openai.api_key = "your_api_key"

models = openai.Model.list()

print(models.data[0].id)

chat_completion = openai.Completion.create(
  model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}]
  )

print(chat_completion.choices[0].message.content)`

Error:

Traceback (most recent call last):
  File "C:\Users\USER\gpt1.py", line 6, in <module>
    openai.Model.list()
  File "C:\Python311\Lib\site-packages\openai\api_resources\abstract\listable_api_resource.py", line 52, in list
    requestor, url = cls.__prepare_list_requestor(
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\openai\api_resources\abstract\listable_api_resource.py", line 20, in __prepare_list_requestor
    requestor = api_requestor.APIRequestor(
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\openai\api_requestor.py", line 138, in __init__
    self.api_key = key or util.default_api_key()
                          ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\openai\util.py", line 186, in default_api_key
    raise openai.error.AuthenticationError(
openai.error.AuthenticationError: No API key provided. You can set your API key in code using 'openai.api_key = <API-KEY>', or you can set the environment variable OPENAI_API_KEY=<API-KEY>). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = <PATH>'. You can generate API keys in the OpenAI web interface. See https://platform.openai.com/account/api-keys for details.
Lucas Hendren
  • 2,786
  • 2
  • 18
  • 33

1 Answers1

1

Try setting the environmental variable, and try setting up authentication the same way they do for the models list documenation using the OS environment variable.

import os
import openai
from dotenv import load_dotenv
load_dotenv()

api_key = os.getenv('OPENAI_KEY')
openai.api_key = api_key

Here are instructionsenter link description here for setting environment variables. This is for a juypter notebook, but it shouldnt be that much different from setting them or your own environment.

Lucas Hendren
  • 2,786
  • 2
  • 18
  • 33