英文:
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<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();
}
Output:
StatusCode: 429, ReasonPhrase: 'Too Many Requests'
答案1
得分: 1
问题
你没有正确设置 messages
参数。 messages
参数的 role
和 content
属性是必需的。
错误示例:
messages = "How are you?",
请参阅官方 OpenAI 文档。
<br>
解决方法
正确示例:
messages = new[] {
new { role = "system", content = "You are a helpful assistant." },
new { role = "user", content = "Hello!" },
},
<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<ChatCompletionMessage[]> 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<ChatCompletionMessage> _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)
=> choices.Select(x => x.Message).ToArray();
//向 OpenAI 发送消息的公共方法
public Task<ChatCompletionMessage[]> SendChatMessage(string message)
{
var chatMsg = new ChatCompletionMessage()
{
Content = message,
Role = "user"
};
return SendChatMessage(chatMsg);
}
//业务逻辑发生的地方
async Task<ChatCompletionMessage[]> SendChatMessage(
ChatCompletionMessage message)
{
//我们应该发送所有消息
//这样我们可以为 Open AI 提供对话的上下文
StackMessages(message);
var chatCompletion = new ChatCompletion
{
Request = new ChatCompletionRequest
{
Model = "gpt-3.5-turbo",
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: "YOUR-API-KEY",
organizationId: "YOUR-ORGANIZATION-ID");
步骤 6:在我们的应用程序中使用 Chat GPT 模型
var msg = Console.ReadLine();
do
{
var results = await chatOpenAI.SendChatMessage(msg);
foreach (var item in results)
{
Console.WriteLine($"{item.Role}: {item.Content}");
}
Console.WriteLine("下一个提示:");
msg = Console.ReadLine();
} while (msg != "再见");
截图:
英文:
Problem
You didn't set the messages
parameter correctly. The role
and content
properties of the messages
parameter are required.
Wrong:
messages = "How are you?",
See the official OpenAI documentation.
<br>
Solution
Correct:
messages = new[] {
new { role = "system", content = "You are a helpful assistant." },
new { role = "user", content = "Hello!" },
},
<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<ChatCompletionMessage[]> 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<ChatCompletionMessage> _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)
=> choices.Select(x => x.Message).ToArray();
//Public method to Send messages to OpenAI
public Task<ChatCompletionMessage[]> SendChatMessage(string message)
{
var chatMsg = new ChatCompletionMessage()
{
Content = message,
Role = "user"
};
return SendChatMessage(chatMsg);
}
//Where business happens
async Task<ChatCompletionMessage[]> 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 = "gpt-3.5-turbo",
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: "YOUR-API-KEY",
organizationId: "YOUR-ORGANIZATION-ID");
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($"{item.Role}: {item.Content}");
}
Console.WriteLine("Next Prompt:");
msg = Console.ReadLine();
} while (msg != "bye");
Screenshot:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论