OpenAI ChatGPT (GPT-3.5) API错误: “状态码: 429, 原因短语: ‘请求过多'”

huangapple go评论89阅读模式
英文:

OpenAI ChatGPT (GPT-3.5) API error: "StatusCode: 429, ReasonPhrase: 'Too Many Requests'"

问题

我正在使用 .net core web api 将请求发送到 OpenAI API。我收到以下错误作为响应。我在我的 OpenAI 帐户中有余额。

我编写的代码和响应如下:

public async Task<string> SendPromptAndGetResponse()
{
    const string requestUri = "https://api.openai.com/v1/chat/completions";
    var requestBody = new
    {
        model = "gpt-3.5-turbo",
        messages = "How are you?",
        temperature = 0,
        max_tokens = 100
    };

    _httpClient.DefaultRequestHeaders.Authorization =
        new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", ApiKey);

    var response = await _httpClient.PostAsync(
        requestUri,
        new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json"));

    response.EnsureSuccessStatusCode();

    var responseBody = JsonConvert.DeserializeObject<ResponseBody>(await response.Content.ReadAsStringAsync());
    return responseBody.Choices[0].Message.Content.Trim();
}

输出:

StatusCode: 429, ReasonPhrase: 'Too Many Requests'
英文:

I am passing requests to the OpenAI API with .net core web api. I am getting the following error as a response. I have a balance in my OpenAI account.

The codes I wrote and the response are as follows:

public async Task&lt;string&gt; SendPromptAndGetResponse()
    {
        const string requestUri = &quot;https://api.openai.com/v1/chat/completions&quot;;
        var requestBody = new
        {
            model = &quot;gpt-3.5-turbo&quot;,
            messages = &quot;How are you?&quot;,
            temperature = 0,
            max_tokens = 100
        };

        _httpClient.DefaultRequestHeaders.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue(&quot;Bearer&quot;, ApiKey);

        var response = await _httpClient.PostAsync(
            requestUri,
            new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, &quot;application/json&quot;));

        response.EnsureSuccessStatusCode();

        var responseBody = JsonConvert.DeserializeObject&lt;ResponseBody&gt;(await response.Content.ReadAsStringAsync());
        return responseBody.Choices[0].Message.Content.Trim();
    }

Output:

StatusCode: 429, ReasonPhrase: &#39;Too Many Requests&#39;

答案1

得分: 1

问题

你没有正确设置 messages 参数。 messages 参数的 rolecontent 属性是必需的。

错误示例:

messages = &quot;How are you?&quot;,

请参阅官方 OpenAI 文档

OpenAI ChatGPT (GPT-3.5) API错误: “状态码: 429, 原因短语: ‘请求过多'”

<br>

解决方法

正确示例:

messages = new[] {
  new { role = &quot;system&quot;, content =  &quot;You are a helpful assistant.&quot; },
  new { role = &quot;user&quot;, content =  &quot;Hello!&quot; },
},

<br>

工作示例

此外,这篇博文可能会对你有所帮助。

免责声明:以下代码和截图的所有权归博客作者 Ricardo Mauro 所有。

步骤 1:安装 Standard.AI.OpenAI C# 库

dotnet add Standard.AI.OpenAI

步骤 2:创建 OpenAI 帐户

步骤 3:创建 OpenAIProxy 类

using Standard.AI.OpenAI.Models.Services.Foundations.ChatCompletions;

namespace ConsoleAppOpenAI;

public interface IOpenAIProxy
{
  Task&lt;ChatCompletionMessage[]&gt; SendChatMessage(string message);
}

步骤 4:创建实现类 OpenAIProxy.cs

using Standard.AI.OpenAI.Clients.OpenAIs;
using Standard.AI.OpenAI.Models.Configurations;
using Standard.AI.OpenAI.Models.Services.Foundations.ChatCompletions;

namespace ConsoleAppOpenAI;

public class OpenAIProxy : IOpenAIProxy
{
  readonly OpenAIClient openAIClient;

	//对话中的所有消息
  readonly List&lt;ChatCompletionMessage&gt; _messages;

  public OpenAIProxy(string apiKey, string organizationId)
  {
    // 使用 API 密钥和组织 ID 初始化配置
    var openAIConfigurations = new OpenAIConfigurations
    {
      ApiKey = apiKey,
      OrganizationId = organizationId
    };

    openAIClient = new OpenAIClient(openAIConfigurations);

    _messages = new();
  }

  void StackMessages(params ChatCompletionMessage[] message)
  {
    _messages.AddRange(message);
  }

  static ChatCompletionMessage[] ToCompletionMessage(
    ChatCompletionChoice[] choices)
    =&gt; choices.Select(x =&gt; x.Message).ToArray();

  //向 OpenAI 发送消息的公共方法
  public Task&lt;ChatCompletionMessage[]&gt; SendChatMessage(string message)
  {
    var chatMsg = new ChatCompletionMessage() 
    { 
      Content = message, 
      Role = &quot;user&quot; 
    };
    return SendChatMessage(chatMsg);
  }
	
  //业务逻辑发生的地方
  async Task&lt;ChatCompletionMessage[]&gt; SendChatMessage(
    ChatCompletionMessage message)
  {
    //我们应该发送所有消息
    //这样我们可以为 Open AI 提供对话的上下文
    StackMessages(message);

    var chatCompletion = new ChatCompletion
    {
      Request = new ChatCompletionRequest
      {
        Model = &quot;gpt-3.5-turbo&quot;,
        Messages = _messages.ToArray(),
        Temperature = 0.2,
        MaxTokens = 800
      }
    };

    var result = await openAIClient
      .ChatCompletions
      .SendChatCompletionAsync(chatCompletion);

    var choices = result.Response.Choices;

    var messages = ToCompletionMessage(choices);

	//也将响应堆叠起来 - 对于 Open AI 一切都是上下文
    StackMessages(messages);

    return messages;
  }
}

步骤 5:设置 API 密钥

IOpenAIProxy chatOpenAI = new OpenAIProxy(
    apiKey: &quot;YOUR-API-KEY&quot;,
    organizationId: &quot;YOUR-ORGANIZATION-ID&quot;);

步骤 6:在我们的应用程序中使用 Chat GPT 模型

var msg = Console.ReadLine();

do
{
  var results = await chatOpenAI.SendChatMessage(msg);

  foreach (var item in results)
  {
    Console.WriteLine($&quot;{item.Role}: {item.Content}&quot;);
  }
  
  Console.WriteLine(&quot;下一个提示:&quot;);
  msg = Console.ReadLine();
  
} while (msg != &quot;再见&quot;);

截图:

OpenAI ChatGPT (GPT-3.5) API错误: “状态码: 429, 原因短语: ‘请求过多'”

英文:

Problem

You didn't set the messages parameter correctly. The role and content properties of the messages parameter are required.

Wrong:

messages = &quot;How are you?&quot;,

See the official OpenAI documentation.

OpenAI ChatGPT (GPT-3.5) API错误: “状态码: 429, 原因短语: ‘请求过多'”

<br>

Solution

Correct:

messages = new[] {
  new { role = &quot;system&quot;, content =  &quot;You are a helpful assistant.&quot; },
  new { role = &quot;user&quot;, content =  &quot;Hello!&quot; },
},

<br>

Working example

Also, this blog post might help you.

DISCLAIMER: All credit for the code and screenshot below goes to the author of the blog, Ricardo Mauro.

STEP 1: Install Standard.AI.OpenAI C# library

dotnet add Standard.AI.OpenAI

STEP 2: Create an OpenAI account

STEP 3: Create the class OpenAIProxy

using Standard.AI.OpenAI.Models.Services.Foundations.ChatCompletions;

namespace ConsoleAppOpenAI;

public interface IOpenAIProxy
{
  Task&lt;ChatCompletionMessage[]&gt; SendChatMessage(string message);
}

STEP 4: Create the implementation class OpenAIProxy.cs

using Standard.AI.OpenAI.Clients.OpenAIs;
using Standard.AI.OpenAI.Models.Configurations;
using Standard.AI.OpenAI.Models.Services.Foundations.ChatCompletions;

namespace ConsoleAppOpenAI;

public class OpenAIProxy : IOpenAIProxy
{
  readonly OpenAIClient openAIClient;

	//all messages in the conversation
  readonly List&lt;ChatCompletionMessage&gt; _messages;

  public OpenAIProxy(string apiKey, string organizationId)
  {
    //initialize the configuration with api key and sub
    var openAIConfigurations = new OpenAIConfigurations
    {
      ApiKey = apiKey,
      OrganizationId = organizationId
    };

    openAIClient = new OpenAIClient(openAIConfigurations);

    _messages = new();
  }

  void StackMessages(params ChatCompletionMessage[] message)
  {
    _messages.AddRange(message);
  }

  static ChatCompletionMessage[] ToCompletionMessage(
    ChatCompletionChoice[] choices)
    =&gt; choices.Select(x =&gt; x.Message).ToArray();

  //Public method to Send messages to OpenAI
  public Task&lt;ChatCompletionMessage[]&gt; SendChatMessage(string message)
  {
    var chatMsg = new ChatCompletionMessage() 
    { 
      Content = message, 
      Role = &quot;user&quot; 
    };
    return SendChatMessage(chatMsg);
  }
	
  //Where business happens
  async Task&lt;ChatCompletionMessage[]&gt; SendChatMessage(
    ChatCompletionMessage message)
  {
    //we should send all the messages
    //so we can give Open AI context of conversation
    StackMessages(message);

    var chatCompletion = new ChatCompletion
    {
      Request = new ChatCompletionRequest
      {
        Model = &quot;gpt-3.5-turbo&quot;,
        Messages = _messages.ToArray(),
        Temperature = 0.2,
        MaxTokens = 800
      }
    };

    var result = await openAIClient
      .ChatCompletions
      .SendChatCompletionAsync(chatCompletion);

    var choices = result.Response.Choices;

    var messages = ToCompletionMessage(choices);

	//stack the response as well - everything is context to Open AI
    StackMessages(messages);

    return messages;
  }
}

STEP 5: Set up the API key

IOpenAIProxy chatOpenAI = new OpenAIProxy(
    apiKey: &quot;YOUR-API-KEY&quot;,
    organizationId: &quot;YOUR-ORGANIZATION-ID&quot;);

STEP 6: Use the Chat GPT model in our application

var msg = Console.ReadLine();

do
{
  var results = await chatOpenAI.SendChatMessage(msg);

  foreach (var item in results)
  {
    Console.WriteLine($&quot;{item.Role}: {item.Content}&quot;);
  }
  
  Console.WriteLine(&quot;Next Prompt:&quot;);
  msg = Console.ReadLine();
  
} while (msg != &quot;bye&quot;);

Screenshot:

OpenAI ChatGPT (GPT-3.5) API错误: “状态码: 429, 原因短语: ‘请求过多'”

huangapple
  • 本文由 发表于 2023年7月27日 19:21:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76779241.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定