I am using Visual Studio and Python However, I get 'Incorrect API key' error, the key is valid

import openai
import os
from dotenv import load_dotenv
openai.debug = True
load_dotenv()
api_key = os.getenv(“OPENAI_API_KEY”)

if not api_key:
raise ValueError(“No API key found. Please check your .env file.”)

try:
completion = openai.ChatCompletion.create(
model=“gpt-4.1”,
messages=[
{“role”: “system”, “content”:
“Always answer in a clear and friendly manner.”},
{“role”: “user”, “content”: “Introduce yourself.”}
]
)
except Exception as e:
print(f"Exception occurred: {e}")
else:
print(completion.choices[0].message.content)


And this is the result:
e = AuthenticationError(message=‘Incorrect API key provided: [api-key] You can find your API key at https://platform.openai.com/account/api-keys.’,

Can anyone out there help me?

1 Like

Hi, welcome to the community!

You should create your API KEY on:

API keys - OpenAI API

then copy it and paste in dot env (.env) file. Sample:

OPENAI_API_KEY=YOUR KEY HERE

Your files and dot env (.env) file should look like:

Your code is working on my end:

import openai
import os
from dotenv import load_dotenv

openai.debug = True
load_dotenv()

api_key = os.getenv("OPENAI_API_KEY")
openai.api_key = api_key

if not api_key:
    raise ValueError("No API key found. Please check your .env file.")

try:
    completion = openai.ChatCompletion.create(
        model="gpt-4.1",
        messages=[
            {"role": "system", "content": "Always answer in a clear and friendly manner."},
            {"role": "user", "content": "Introduce yourself."}
        ]
    )
except Exception as e:
    print(f"Exception occurred: {e}")
else:
    print(completion.choices[0].message["content"])

2 Likes

Thank you for your input, polepole. But the thing is, the code tests that the api key. It is retrieved from .env .and there is no failure. on the line 'if not api_key … 'In fact I can see the value in debug. I have am happy to hear the code runs in your environment. Could the failure be due do the speed of the connection? I tried to slow it down by stepping thy the try: loop in debug mode, with no luck…

In fact the Beginning and end of key is display in the final error message: e = AuthenticationError(message=‘Incorrect API key provided: [api-key] You can find your API key at https://platform.openai.com/account/api-keys.’,

That means the key is being received by the model, but it is being rejected for some unknown reaso. I had to use my Google account to join this community. OpenAi would not accept my email, saying they could not verify my identity, or some such language.

1 Like