Getting "insufficient_quota" Error in Python Script but Playground Works (Tier 1 Account)

I have a Tier 1 OpenAI account with access to GPT-4. When I try using the API through a Python script, I get the following error:

openai.RateLimitError: Error code: 429 - {
‘error’: {
‘message’: ‘You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.’,
‘type’: ‘insufficient_quota’,
‘param’: None,
‘code’: ‘insufficient_quota’
}
}

However, when I use the OpenAI Playground, the models (including GPT-4.1) work just fine.
Here’s the code snippet I’m running:

from openai import OpenAI
import os

my_api_key = os.getenv(“OPENAI_API_KEY”)
openai = OpenAI(api_key=my_api_key)

completion = openai.chat.completions.create(
model=‘gpt-4.1’,
messages=[{“role”: “user”, “content”: “What’s 2+2?”}],
)
print(completion.choices[0].message.content)

Have you tried printing the API key the code obtains, to ensure you have set the key you think you are using?

Here’s a better version of finding out the credentials that are used - which are automatic and don’t need you to specify the default environment variable key.

import openai

def get_org_model(client, model="gpt-4o-mini"):
    try:
        return client.models.retrieve(model).id  # Makes test API call
    except Exception as your_error:
        return your_error

def env_info():
    client=openai.Client()  # automatically imports from env variables
    # client=openai.Client(api_key="sk-proj-lengthy-hardcoded-bad-key-test")
    print(f"API test: {get_org_model(client)}")

    org = client.organization or "(no organization set)"
    proj = client.project or "(no project set)"
    api_key = client.api_key or "(no API key set)"
    if len(api_key) > 20:
        elided_key = f"{api_key[:14]}...{api_key[-6:]}"
    else:
        elided_key = "(invalid short API key)"

    print(f"Used `openai` module version {openai.__version__}")
    print(f"API Key: {elided_key}\nOrganization: {org}\nProject: {proj}")

if __name__ == "__main__":
    env_info()

It may be necessary with a recent initial payment or tier upgrade to generate a new project API key.

For this test case, to ensure success, use the default or a new project, and with no restrictions set up on either the project or the key itself.

1 Like