It says incorrect API though I had correct keys in env ((GoogleColabs)) and my openAI account is loaded 10$

import openai
openai.apikey = os.environ.get(‘OPENAI_API_KEY’)

responses = openai.ChatCompletion.create(
model=“gpt-4o”,
messages=[
{“role”: “system”, “content”: “You are a helpful assistant.”},
{“role”: “user”, “content”: “Who won the world series in 2020?”},
]
)
print(responses)


AuthenticationError Traceback (most recent call last)
in <cell line: 4>()
2 openai.apikey = os.environ.get(‘OPENAI_API_KEY’)
3
----> 4 responses = openai.ChatCompletion.create(
5 model=“gpt-4o”,
6 messages=[

4 frames
/usr/local/lib/python3.10/dist-packages/openai/api_requestor.py in _interpret_response_line(self, rbody, rcode, rheaders, stream)

**AuthenticationError: Incorrect API key provided: [api-key] You can find your API key at https://platform.openai.com/account/api-keys.

The present openai client automatically gets the API key from environment variables.

See what it’s using when it fails on a properly-constructed call:

import openai
try:
    print(openai.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{'role':'user','content': 'sup, bot?'}]
    ).choices[0].message.content)
except:
    print(openai.api_key)
1 Like

Google Colab is convenient, right?
But the environment variables set in Google Colab (referred to as secrets in Colab) need to be retrieved using a dedicated module.

from google.colab import userdata
userdata.get('OPENAI_API_KEY')
from openai import OpenAI
client = OpenAI(api_key=userdata.get('OPENAI_API_KEY'))

Even in Google Colab, directly entering the API key poses a security risk, so it is recommended to set it as a secret and use it.

2 Likes