AI/OpenAI API

OpenAI API - API KEY Error (Windows - Python)

강서버 2025. 1. 22. 19:01
반응형

[ Error message ]                                                         
Traceback (most recent call last):
  File "c:\devel\langchain\api_test\api_028_test.py", line 5, in <module>
    models = openai.Model.list()
             ^^^^^^^^^^^^^^^^^^^
  File "C:\devel\langchain\.venv\Lib\site-packages\openai\api_resources\abstract\listable_api_resource.py", line 52, in list
    requestor, url = cls.__prepare_list_requestor(
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\devel\langchain\.venv\Lib\site-packages\openai\api_resources\abstract\listable_api_resource.py", line 20, in __prepare_list_requestor
    requestor = api_requestor.APIRequestor(
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\devel\langchain\.venv\Lib\site-packages\openai\api_requestor.py", line 138, in __init__
    self.api_key = key or util.default_api_key()
                          ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\devel\langchain\.venv\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.

 

 

[ Solve ]

 

[ openai version : 1.59.9 ]

> pip install openai==1.59.9

 

Request code : (* Change the API key(api_key) to your own)

 
from openai import OpenAI

client = OpenAI(
  api_key=" sk-proj-GNBxSl-kdZB-S9RreOmCzYl4ZfAp-W472LoTzZkFXCiPEwb75QiwhfpAVnBH7gJ2dfsbkofPNIT3BlbkFJyIkrH58B6WLV_ORxmSVIj2iklcR0zyYQ1gwdheHekSxGkkWBdN2xYmj4KfmrwxSY_f8MA"
)

completion = client.chat.completions.create(
  model="gpt-4o-mini",
  store=True,
  messages=[
    {"role": "user", "content": "write a haiku about ai"}
  ]
)

print(completion.choices[0].message);
 

 

Response :

ChatCompletionMessage(content='Silent circuits buzz,  \nWhispers of thought intertwine—  \nDreams in code arise.', refusal=None, role='assistant', audio=None, function_call=None, tool_calls=None)

 

 

[ openai version : 0.28.0 ]

> pip install openai==0.28.0

 

Request code : (* Change the API key(api_key) to your own)

import openai
 
openai.api_key = "sk-proj-GNBxSl-kdZB-S9RreOmCzYl4ZfAp-W472LoTzZkFXCiPEwb75QiwhfpAVnBH7gJ2dfsbkofPNIT3BlbkFJyIkrH58B6WLV_ORxmSVIj2iklcR0zyYQ1gwdheHekSxGkkWBdN2xYmj4KfmrwxSY_f8MA"

# create a chat completion
chat_completion = openai.ChatCompletion.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello world"}])

# print the chat completion
print(chat_completion.choices[0].message.content)
 

 

Response :

Hello! How can I assist you today?

 

반응형