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

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.