ChatGPT API Error 429 too many requests

I have a problem with my code on API so i created some simple code that use chatGPT API to answer my question so i try to make it and when i say hi it respond with: Sorry, I couldn’t understand that. Could you please try again? and on the console (inspect element) it says: POST https://api.openai.com/v1/completions 429
(anonymous) @ main.js:10

its always 429 i try to wait like 1 hour, 2 hour but its still error like that, is anybody can help me :slight_smile:
i am in free plan btw.

1 Like

Sharing your code making the API call will help us help you.

4 Likes

I am reporting the same problem and looking for help.

2 Likes

Same Issue.I call createChatCompletion api to test demo.And blocked after 2hour

1 Like
import okhttp3.*;

import java.io.IOException;

public class ChatGPTExample {

    private static final String API_ENDPOINT = "https://api.openai.com/v1/engines/davinci-codex/completions";
    private static final String AUTHORIZATION_TOKEN = "Bearer ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■aOSt01Hv";

    public static void main(String[] args) {
        String prompt = "Hello, ChatGPT!";
        int maxTokens = 5;

        try {
            String response = makeApiRequest(prompt, maxTokens);
            System.out.println(response);
        } catch (IOException | InterruptedException e) {
            System.err.println("Error making API request: " + e.getMessage());
            System.err.println("Please check your network connection and try again.");
        }
    }
    private static String makeApiRequest(String prompt, int maxTokens) throws IOException, InterruptedException {
        OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"prompt\": \"" + prompt + "\", \"max_tokens\": " + maxTokens + "}");
        Request request = new Request.Builder()
                .url(API_ENDPOINT)
                .post(body)
                .addHeader("content-type", "application/json")
                .addHeader("authorization", AUTHORIZATION_TOKEN)
                .build();

        int maxRetries = 1000;
        int delay = 1000; // 1 second delay
        int retryCount = 0;

        while (true) {
            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    return response.body().string();
                }

                if (response.code() == 429) {
                    // Too Many Requests - wait and retry
                    if (retryCount < maxRetries) {
                        retryCount++;
                        Thread.sleep((long) delay * retryCount);
                    } else {
                        throw new IOException("API rate limit exceeded - maximum retries reached");
                    }
                } else {
                    throw new IOException("Unexpected response code: " + response.code());
                }
            } catch (IOException e) {
                if (retryCount < maxRetries) {
                    retryCount++;
                    Thread.sleep((long) delay * retryCount);
                } else {
                    throw e;
                }
            }
        }
    }


}

I just create an API and start with PHP

<?php 
require 'vendor/autoload.php';
function generateChatResponse($message) {
    $openaiApiKey = 'MYKEY';
    $url = 'https://api.openai.com/v1/chat/completions';

    $client = new GuzzleHttp\Client();

    $headers = [
        'Authorization' => 'Bearer ' . $openaiApiKey,
        'Content-Type' => 'application/json',
    ];

    $data = [
        'messages' => [['role' => 'system', 'content' => 'You are a PHP developer.']],
        'max_tokens' => 50, // Adjust the response length as per your requirements.
        'model' => 'gpt-3.5-turbo',
    ];

    $response = $client->post($url, [
        'headers' => $headers,
        'json' => $data,
    ]);

    $responseBody = json_decode($response->getBody(), true);
    $reply = $responseBody['choices'][0]['message']['content'];

    return $reply;
}
$userMessage = 'Hello, how can I integrate ChatGPT with PHP?';
$chatReply = generateChatResponse($userMessage);
echo $chatReply; // Output the generated response

but i am getting ERROR

Client error: `POST https://api.openai.com/v1/chat/completions` resulted in a `429 Too Many Requests` response: { "error": { "message": "You exceeded your current quota, please check your plan and billing details.",

Typically this means you need to add a payment method to your account here OpenAI Platform

2 Likes

Thanks @Foxalabs for your immediate responses. Highly appreciate that.
But from community posts seems like adding card is not resolve the issue. Some people also getting this error after adding card.

Other community members responses awaiting.

There are many reasons you may get 429 error, but as indicated in the message of your specific error, you need to add a credit card.

“message”: “You exceeded your current quota, please check your plan and billing details.”

public async Task GetChatCompletionAsync(string question)
{
var httpClient = _httpClientFactory.CreateClient(“ChtpGPT”);

 //ChatCompletionRequest completionRequest = new()
 //{
 //    Model = "gpt-3.5-turbo",
 //    MaxTokens = 1000,
 //    Messages = [
 //                    new Message()
 //                    {
 //                        Role = "user",
 //                        Content = question,

 //                    }
 //                ]
 //};

 ChatCompletionRequest completionRequest = new()
 {
     Model = "gpt-3.5-turbo", // Use the appropriate model name
     Messages = new List<Message>
    {
     new Message { Role = "user", Content = question }
    }
 };


 using var httpReq = new HttpRequestMessage(HttpMethod.Post, "https://api.openai.com/v1/chat/completions");
 httpReq.Headers.Add("Authorization", $"Bearer {_configuration["OpenAI:ApiKey"]}");

 string requestString = JsonSerializer.Serialize(completionRequest);
 httpReq.Content = new StringContent(requestString, Encoding.UTF8, "application/json");

 using HttpResponseMessage? httpResponse = await httpClient.SendAsync(httpReq);
 httpResponse.EnsureSuccessStatusCode();

 var completionResponse = httpResponse.IsSuccessStatusCode ? JsonSerializer.Deserialize<ChatCompletionResponse>(await httpResponse.Content.ReadAsStringAsync()) : null;

 return completionResponse.Choices?[0]?.Message?.Content;

}

Hi, I have added a credit card and is not working, Try to use PostMan for fast check and still getting this error 429 Too Many Request. “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”: null,
“code”: “insufficient_quota”
} … Also upgrade my quote and nothing same error please advise what else can I do to resolve this issue

I will be able to add credit to the account, and now I can access API