Error Code 429 - You exceeded your current quota, please check your plan and billing details

Python: 3.12.2, openai: 1.19.0

When I execute client.completions.create(), the error in the title takes place.

Here is the minimal code to reproduce the error.

from openai import OpenAI

apikey = 'sk-***********************************************'
client = OpenAI(
    api_key=apikey,
)

completion = client.completions.create(
    model="gpt-3.5-turbo",
    prompt=[
        {"role": "user", "content": 'Who is the president of the USA?'},
    ],
)
jsontxt = completion["choices"][0]["text"]
print(jsontxt)

My quota is $50 a month and this month’s usage is $0.

I created a new API key but it didn’t work.

I’d appreciate any suggestion. Thank you.

I solved it myself.

The credit balance in the following url was zero. So I charged to it by “Add to credit balance” button.
ttps://platform.openai.com/settings/organization/billing/overview
It looks like the balance is not AUTOMATICALLY charged from your credit card.

In addition, my code was a bit wrong. The one below worked fine.

from openai import OpenAI

apikey = 'sk-*****************************************'
client = OpenAI(
    api_key=apikey,
)

completion = client.chat.completions.create( 
  model = 'gpt-3.5-turbo',
  messages = [ 
    {'role': 'user', 'content': 'Who is the president of the USA?'}
  ],
  temperature = 0  
)

print(completion.choices[0].message.content) # Change message content extraction

I’m getting the same error, but my balance on that URL is $10. Still doesn’t work for me.

The balance shown in the screenshot is the remainder of the $18 that had expired a year ago when an OpenAI account was first created (maybe to just use ChatGPT).

I suspect the vast majority of accounts have now been switched to requiring prepayment before you can use the API. You will see the real paid balance not on “usage”, but “settings”->“payment”.

I don’t have a settings → payment but under settings → billing:


It very clearly thinks that I have credit to spend.

I clearly think you have credit to spend, also.

However, you might not be able to spend them yet.

The API may take several hours before a new purchase becomes spendable, though, despite the user immediately seeing the balance. That’s the likely cause here, a persistent bug that OpenAI seemingly can’t fix.

You can also set monthly limits on what can be spent under usage, but this is unlikely to be a cause unless you are a new convert to prepay and also have a large unsettled monthly bill balance. It also hasn’t worked properly recently to stop spending, anyway.

Then there is the new API key system of “projects” that has even more possibilities for denial based on endpoint rights instead of monetary balance.

paid
The purchase was 35 hours ago, I’m hoping that was enough time.

Under monthly limits, they’re set at $120 which should be way more than I need. I did select the models that I want to allow under project limits, I didn’t have any selected before. I was really excited but re-built and cleared cache and it still didn’t work: Error with OpenAI API request: You exceeded your current quota, please check your plan and billing details.

If you are trying to access GPT-4, that often may need a new API key generated after first payment which activates it.

You may have more tediousness to go through now, where you’ll need to create a “project” for your organization (or have a default project), under which you can configure project rights, and then generate an API key, then needing to be assigned to a project, also with rights.

Hi @sfrrki,
I was facing the same issue earlier but after recharging my account it worked immediately.

Here a few things, you should go and cross-check:

  1. Check usage limits section: link
    Update monthly budget according to your usage

  2. Try testing GPT 4 via OpenAI Playground. As they bill it too, so this way you will be able to check whether your credits are getting used on not.

Try these things and let us know whether this helps or not.

Regards,
GeekyRahul
https://in.linkedin.com/in/rpalsaxena

Arighty

  1. My usage is default with $120 being the limit and $96 being the email threshold. I tried to change these up and it says my upper spending limit is $120 as I’m on Usage Tier 1. I’ll just set them to $50 and $45 respectively and they do seem to change and accept that.

  2. I was able to do messages back and forth with the provided GPT 4 (gpt-4-1106-vision-preview) and they seem to work just fine. Checking my balance, it didn’t go down at all. Was it supposed to for using GPT4?

Thanks for your help Rahul!

Edit: Aha! it took a second to update but I have been billed. I’m down to $9.99.
Edit 2: Still getting the same error on my application: Error with OpenAI API request: You exceeded your current quota, please check your plan and billing details.
Edit 3: my usage on the usage page still says $0.00 / $0 limit. This limit might be the problem.

So: it’s working? But where? (where do you see “provided gpt” - there are multiple models you can choose.

But then not working?

So, it looks like its working in the OpenAI playground. That’s where I see the GPT 4 that I’ve called the “provided GPT”:
models

I’m able to use my credits for GPT 4 there. However, I currently have a site that’s deployed which is what’s returning the error provided by the API concerning the quota. I’ve re-built and redeployed it between making these changes in the hope that it would work as it did previously. I could potentially run the backend and front end locally, but since it worked previously I’m hesitant to do that.

There’s others that were given a $0 limit in that screen, killing their API with the move to “projects” as the method for API key rights. But it seemed like it had been fixed in those topics (without OpenAI responding they fixed something.)

I would look at the system environment variable and code, and see if its using an obsolete OPENAI_API_KEY.

You can install Python 3.11 locally, and try this chatbot code that uses your own OS environment variable as API key (or you can hard-code the key). It first sends to moderations to check inputs, which needs a funded account, but doesn’t cost you.

import os, json, urllib.request, urllib.error

headers = {"Content-Type": "application/json",
    # replace {os.environ.get('OPENAI_API_KEY')} with actual key to hard-code
    "Authorization": f"Bearer {os.environ.get('OPENAI_API_KEY')}"}
model = "gpt-3.5-turbo"
system = [{"role": "system", "content": f"You are ChatAPI, an AI assistant."}]
user = [{"role": "user", "content": "Introduce yourself."}]
chat = []
params_template = {"model": model, "max_tokens": 666, "top_p":0.9,}

while not user[0]['content'] == "exit":
    to_moderate =  {"input" : ', '.join([str(d) for d in (chat[-2:] + user)])}
    try:
        req = urllib.request.Request("https://api.openai.com/v1/moderations", \
          headers=headers, data=json.dumps(to_moderate).encode())
        mod = urllib.request.urlopen(req)
        scores = json.loads(mod.read().decode())
        if scores["results"][0]['flagged']:
            print(scores["results"][0]["categories"])
            user = [{"role": "user", "content":
            input("\nMessage Blocked!\nPrompt: ")}]
            continue
    except urllib.error.HTTPError as e:
        print(f"mod error {e.code}: {e.read().decode()}")

    request = {**params_template, **{"messages": system + chat[-10:] + user}}
    try:
        req = urllib.request.Request("https://api.openai.com/v1/chat/completions", \
          headers=headers, data=json.dumps(request).encode())
        response = urllib.request.urlopen(req)
    except urllib.error.HTTPError as e:
        print(f"chat error {e.code}: {e.read().decode()}")
        user = [{"role": "user", "content": input("\nPrompt: ")}]
        continue
    except Exception as e:
        print(f"Error: {e}")
        continue
    else:
        response_body = json.loads(response.read().decode())
        reply = response_body['choices'][0]['message']['content']
        print(reply)
    chat += user + [{"role": "assistant", "content": reply}]
    user = [{"role": "user", "content": input("\nPrompt: ")}]

I’m running this off of my API key in my .env. I’ve updated it with a new key made specifically for the project on open AI’s page for it.

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

module.exports = async function (req, res) {
  if (!process.env.OPENAI_API_KEY) {
    res.status(500).json({
      error: {
        message:
          "OpenAI API key not configured, please follow instructions in README.md",
      },
    });
    return;
  }

  const city = req.body.city || "";
  if (city.trim().length === 0) {
    res.status(400).json({
      error: {
        message: "Please enter a valid city",
      },
    });
    return;
  }

  try {
    const completion = await openai.completions.create({
      model: "gpt-3.5-turbo", 
      prompt: generatePrompt(city),
      temperature: 0.4,
      max_tokens: 350,
    });

Do you want me to run that dianostic? I can also print out a lot of that info on my js end

gpt-3.5-turbo is not a model you can use on the OpenAI completions endpoint.

You could try gpt-3.5-turbo-instruct, but that likely won’t behave like you expect.

You will get an error with what you show. The error expected is not “check your plan”, though.

You can click on the API Reference links, scroll to “chat”, and look at the examples there where you can choose python or node.js, or even paste a curl example into ChatGPT and ask it for simple code in your destination for making a test request.

Yes, that 3.5-turbo can be used with ChatCompletions API not with Completions Endpoint.
If you understand Hindi Language, can try to check this tutorial by me: https://www.youtube.com/watch?v=Zf7RjNIzUhA

Try using client.chat.completions.create, I encourage you to have a look at this notebook.

Hope it helps!