.NET Core Web API调用OpenAI API遇429请求过多错误求助
.NET Core Web API调用OpenAI API遇429错误(账户有余额)
问题说明
使用.NET Core Web API调用OpenAI的chat/completions接口时,返回429 Too Many Requests错误,但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'
解决办法
- 检查请求频率:OpenAI对gpt-3.5-turbo模型有默认速率限制(每分钟3500次请求/90000 tokens),确认是否短时间内发起了过量请求
- 修复请求格式:代码中
messages字段格式错误,必须是包含角色和内容的对象数组,正确写法应为:
格式错误可能被判定为异常请求,间接触发限制messages = new[] { new { role = "user", content = "How are you?" } } - 添加重试机制:使用Polly等库实现指数退避重试逻辑,遇到429错误时自动延迟重试
- 核对API密钥权限:确认密钥绑定的组织正确,无额外调用限制
- 查看OpenAI后台统计:在OpenAI平台的使用页面,确认是否触发了速率限制或其他账户限制
内容的提问来源于stack exchange,提问作者jancooth
相关产品推荐
相关产品推荐

