Error 429 when using GPT-3.5 API in .NET - How can I fix it?

Hello everyone,

I have developed a simple .NET console application that uses the GPT-3.5 API to send text requests to ChatGPT and store the response in the variable “jsonResponse”. The result should then be output to the console. Here is the code:

using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace ChatGPT
{
class ChatGPT
{
static async Task Main(string args)
{
// GPT-3.5 API-Schlüssel
string apiKey = “HereWasTheAPIKey”;

        // Anfrage an die GPT-3.5-API
        string prompt = "Hello, ChatGPT, this is a test. Are you GPT-3.5?";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

            // Die Daten, die an GPT-3.5 gesendet werden
            var requestData = new
            {
                prompt,
                max_tokens = 100 // Maximale Anzahl der generierten Tokens
            };

            string apiUrl = "https://api.openai.com/v1/engines/gpt-3.5-turbo/completions"; // GPT-3.5 API-Endpunkt

            int retryCount = 0;
            int maxRetries = 5; // Anzahl der maximalen Wiederholungsversuche
            int delayInSeconds = 20; // Anfangsverzögerung in Sekunden

            while (retryCount < maxRetries)
            {
                HttpResponseMessage response = await client.PostAsync(apiUrl, new StringContent(JsonSerializer.Serialize(requestData), Encoding.UTF8, "application/json"));

                if (response.IsSuccessStatusCode)
                {
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(jsonResponse);
                    break; // Erfolgreiche Antwort, abbrechen der Schleife
                }
                else if ((int)response.StatusCode == 429)
                {
                    Console.WriteLine($"Fehler 429: Zu viele Anfragen. Warte {delayInSeconds} Sekunden, bevor du es erneut versuchst.");
                    await Task.Delay(TimeSpan.FromSeconds(delayInSeconds));
                    delayInSeconds *= 2; // Verdoppeln der Verzögerung für den nächsten Versuch
                    retryCount++;
                }
                else
                {
                    Console.WriteLine($"Fehler: {response.StatusCode}");
                    break; // Andere Fehler behandeln und die Schleife abbrechen
                }
            }

            Console.ReadKey();
        }
    }
}

}

However, I always run into error 429, which usually indicates too many requests to the API. I already tried to reduce the maximum number of tokens, but that didn’t help.

Does anyone have any experience on how to solve this problem? Any help or hints would be greatly appreciated.

PS: Sorry for the German comments in the code and possibly not perfect translations, as I speak German.

Thanks in advance for your support!

Gutentag! Welcome to the forum…

That might be it…

Model endpoint compatibility

(https://platform.openai.com/docs/models/model-endpoint-compatibility)

Endpoint Latest models
/v1/audio/transcriptions whisper-1
/v1/audio/translations whisper-1
/v1/chat/completions gpt-4, gpt-4-0613, gpt-4-32k, gpt-4-32k-0613, gpt-3.5-turbo, gpt-3.5-turbo-0613, gpt-3.5-turbo-16k, gpt-3.5-turbo-16k-0613
/v1/completions (Legacy) gpt-3.5-turbo-instruct, babbage-002, davinci-002
/v1/embeddings text-embedding-ada-002
/v1/fine_tuning/jobs gpt-3.5-turbo, babbage-002, davinci-002
/v1/moderations text-moderation-stable, text-moderation-latest

This list excludes all of our DALL·E models and our deprecated models.

You then send the model as a parameter…

Thank you very much! What should the corrected code line be then?

I’d recommend using one of the libraries…

Community libraries

(https://platform.openai.com/docs/libraries/community-libraries)

The libraries below are built and maintained by the broader developer community. If you’d like to add a new library here, please follow the instructions in our help center article on adding community libraries. You can also watch our OpenAPI specification repository on GitHub to get timely updates on when we make changes to our API.

Please note that OpenAI does not verify the correctness or security of these projects. Use them at your own risk!

C# / .NET

(https://platform.openai.com/docs/libraries/c-net)

Have you paid for use of the API by purchasing credits? Have you set too low of a hard limit in account settings?

429 - You exceeded your current quota, please check your plan and billing details Cause: You have hit your maximum monthly spend (hard limit) which you can view in the account billing section.
Solution: Apply for a quota increase.