调用ChatGPT API的控制台程序报BadRequest错误,请求排查
问题分析与修复方案
导致BadRequest的核心原因
请求内容类型未指定为JSON
使用StringContent传递请求体时,默认的Content-Type是text/plain,但OpenAI的Chat Completions API要求请求体必须是application/json格式,服务器无法解析纯文本格式的JSON数据,因此返回BadRequest。Request类的temperature是字段而非属性
Newtonsoft.Json默认只会序列化带有get/set的属性,你定义的temperature是字段,不会被序列化为JSON的一部分。如果需要传递这个参数,必须改为属性。错误信息排查不足
当前代码仅输出response.RequestMessage,无法获取API返回的具体错误详情,不利于定位问题。
修改后的完整代码
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace GPT { class Program { static async Task Main(string[] args) { string apiKey = "MY_KEY"; string content = "Hello!"; var message = new Message() { role = "user", content = content }; List<Message> messages = new List<Message>(); messages.Add(message); var requestData = new Request() { model = "gpt-3.5-turbo", messages = messages, temperature = 0.7 }; string requestBody = JsonConvert.SerializeObject(requestData); Console.WriteLine(requestBody); string apiUrl = "https://api.openai.com/v1/chat/completions"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); // 指定Content-Type为application/json var contentBody = new StringContent(requestBody, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(apiUrl, contentBody); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine(jsonResponse); } else { // 获取详细错误信息 string errorDetails = await response.Content.ReadAsStringAsync(); Console.WriteLine($"请求失败: {response.StatusCode}\n错误详情: {errorDetails}"); } } } } class Message { public string role { get; set; } = ""; public string content { get; set; } = ""; } class Request { public string model { get; set; } = ""; public List<Message> messages { get; set; } = new List<Message>(); // 改为属性,确保能被序列化 public double temperature { get; set; } = 0.7; } }
额外提示
- 替换
MY_KEY为你的真实OpenAI API密钥。 - 如果仍有问题,查看错误详情中的具体提示,比如API密钥无效、模型名称错误、请求参数格式问题等。
内容的提问来源于stack exchange,提问作者Элла Лебезова
相关产品推荐
相关产品推荐

