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!