Please help. Can't get python quickstart example working - invalid_api_key?

I thought I’d try the openai quickstart python example just to connect to the openai API. I thought it would be a ten min project. It’s maybe 5 or 6 hours later- I don’t even know - and i cant get it working. It’s probably a simple mistake but I’m totally brunt out and can’t absorb anymore info so I’m posting here.

First of all there are credits in my account

Windows 11 computer

I created a project api Key. It a project key staring with “sk-proj-…”

I created an OPENAI_API_KEY environment variable: I verified it’s there.

I did the python quickstart example so I created a venv. (is that screwing things up?)
venv\Scripts\activate
pip install openai.
pip show openai:

Name: openai
Version: 1.64.0
Summary: The official Python library for the openai API
Author:
Author-email: OpenAI support@openai.com
License-Expression: Apache-2.0
Requires: anyio, distro, httpx, jiter, pydantic, sniffio, tqdm, typing-extensions
Required-by:

python --version: 3.13.1

I copied the python quickstart api test program just to call the openai api:

from openai import OpenAI
client = OpenAI()

completion = client.chat.completions.create(
model=“gpt-4o-mini”,
messages=[
{“role”: “system”, “content”: “You are a helpful assistant.”},
{
“role”: “user”,
“content”: “Write a haiku about recursion in programming.”
}
]
)

print(completion.choices[0].message)

I get this error:
(venv) PS C:\My_Programing\Python\todo-openai-function-test> python test_openai.py
An error occurred: Error code: 401 - {‘error’: {‘message’: ‘Incorrect API key provided: [api-key] You can find your API key at https://platform.openai.com/account/api-keys.’, ‘type’: ‘invalid_request_error’, ‘param’: None, ‘code’: ‘invalid_api_key’}}

As i said I’m spent. I’m probably making a simple mistake. I’d be grateful for any advice to get this going.

Thanks.

1 Like

Doesn’t look like you are initializing the client with the API key.

1 Like

Here’s a code snippet:

  • either see all your chat models, or
  • see what you did wrong with authentication
import openai
client=openai.Client()  # automatically imports from env variables
#client=openai.Client(api_key="sk-proj-badkey-hardcoded-override")
starts_with = ["gpt-", "o", "ft:gpt"]
blacklist = ["instruct", "moderation"]
model_response = None
try:
    model_response = client.models.list()  # Makes the API call
    model_dict = model_response.model_dump().get('data', [])
    model_list = sorted([model['id'] for model in model_dict])
    filtered_models = [
        model for model in model_list
        if any(model.startswith(prefix) for prefix in starts_with)
        and not any(bl_item in model for bl_item in blacklist)
    ]
    print(", ".join(filtered_models))
except Exception as err:
    errormsg=err
    print(f"FAIL! Used OPENAI_API_KEY {client.api_key}")
    print(f"Used optional OPENAI_ORG_ID {client.organization}")
    print(f"Used optional OPENAI_PROJECT_ID {client.project}")
    print(f"Used `openai` module version {openai.__version__}")
    print("\n".join(map(str, errormsg.body.values())))

Then: recheck your key is still in your account. OpenAI will delete detected leaked keys, such as ones hardcoded or otherwise sync’d online.

thank you for responding.

However the quickstart only has 3 steps:

  1. Set the environment variable with the api key: setx OPENAI_API_KEY “sk-proj-xxx…”
  2. i confirmed the api key is successfully stored.
  3. install openai: pip install openai.
  4. run the openai python script as per my post.

that’s it. These are openai’s instructions. So I’m assuming the:

client = OpenAI()

line automatically uses the environment variable to initializes the api key.

I’ve also tried setting the api key more explicitly as:

client = OpenAI(
api_key=os.getenv(“OPENAI_API_KEY”) # This will read from environment variable
)

I’ve also tried setting the actual api key directly:
client = OpenAI(
api_key=“sk-proj-…”
)

So again, this is openai’'s quickstart example. I think I’m following the instructions exactly. Does this look correct? Am i doing something wrong?

Thanks.

No, it doesn’t grab anything automatically, you can name the api key variable anything you want, which is why you have to pass it to the client

from openai import OpenAI
import os
api_key = os.environ.get("my_crazy_name_for_api_key")
client = OpenAI(api_key = api_key)

In a pinch, and don’t want to deal with the os library stuff, just do:

from openai import OpenAI
client = OpenAI(api_key ="sk-......")

or in stages without os

from openai import OpenAI
api_key = "sk-......"
client = OpenAI(api_key = api_key)

Frowned upon, sure, but gets you going.

The reason for the os formalism is your code doesn’t have the key hardcoded into it. So it’s thought of as more secure, as you can copy and paste your code around and not expose your key. The os module just obscures the true value of the key, which is what the client really needs as an input. So just put in the key if you are having issues with this step.

The problem is, most people don’t know how to set an environment variable in their environment. Which is the big problem for beginners.

ok.thanks again for responding.

Maybe I’m misunderstanding, but I believe in my pervious post I said that I had tried what you have suggested.

I have tried both ways you have suggest.

when I made my first post i kept it simple and gave the single case of attempting exactly what openai said to do in their quickstart example. But i’ve spent about 5 hours trying this endless different ways.

I’ve also tried just a html/javascript example. Also in that example just to try to keep things simple to get working i set the api key explicitly with api_key=“sk_proj-xx…”. In that case it used the POST method. I stepped through the javascript execution and verified the header data included the api key before it was posted. When it was I get an error back saying I didn’t set the api key. I did. I verified it was set.

In very case I get an error basically saying that I’m not providing an api key. So maybe somehow that is the problem. I believe I set up the api key as instructed.

I’ll try to attach a screenshot of my api key setup below.

I’m wondering if that looks like it is set up ok.

This is crazy frustrating and I’m grateful for any help or advice.

The OpenAI SDKs do in fact obtain credentials from expected environment variables, and this is the recommended method. From https://github.com/openai/openai-python/blob/main/src/openai/_client.py


    ) -> None:
        """Construct a new synchronous openai client instance.

        This automatically infers the following arguments from their corresponding environment variables if they are not provided:
        - `api_key` from `OPENAI_API_KEY`
        - `organization` from `OPENAI_ORG_ID`
        - `project` from `OPENAI_PROJECT_ID`
        """

The provided code snippet in the prior post will print exactly what API key is being attempted by the OpenAI client were an API request to fail.

You should just set environment variables more permanently at a higher level in the OS, by config file or operating system setting.

1 Like

Ok. Problem solved - but i have no idea why :-p

I can connect to the API today.

I created a couple new api keys today and todays keys magically work. The keys i created yesterday, I believe in exactly the same way, still fail. They appear exactly the same. I don’t see any reason why yesterdays don’t work and todays work.

All the call methods work now. Including from the environment variable with the:
client = OpenAI()
call

But it seems totally random. A bit unsettling given i spent probably 7 or 8 hours on this and ultimately don’t understand why the keys from yesterday don’t work and the ones from today work.

But the important thing is I can connect now.

Thanks again for the responses.

1 Like

I think I knew about the default no-arg environment variable assumption, as some code laying around is using it.

But when troubleshooting, better be explicit and don’t assume the SDK will hold your hand.

Yet, all my API calls are sans SDK, and a few lines of straight up python … rather not have the bloat personally.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.