VSCode中C#调用OpenAI接口传递Payload遇BadRequest错误求助
问题:C#调用OpenAI Chat API返回BadRequest错误
我在VSCode中使用C#基于OpenAI Chat API开发代码翻译器,该功能在Postman中测试可正常完成代码翻译,但运行下方代码时收到BadRequest错误:
我怀疑是Payload格式问题,调整后依旧无法解决,恳请帮忙排查。
原始代码
using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace OpenAIProgram { public class CodeTranslator { public static async Task<string> TranslateCodeAsync(string apiKey, string apiUrl, string jsonBody) { string result = string.Empty; try { if (string.IsNullOrEmpty(apiUrl) || string.IsNullOrEmpty(jsonBody)) throw new Exception("Missing parameter for execution"); using var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); var request = new HttpRequestMessage(HttpMethod.Post, apiUrl); request.Headers.Add("Connection", "keep-alive"); request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json"); var response = await httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { result = await response.Content.ReadAsStringAsync(); } else { throw new Exception("Response code was " + response.StatusCode); } } catch (Exception e) { result = e.Message; result += "\n" + e.GetType() + ": " + e.Message; if (e.StackTrace != null) { foreach (var trace in e.StackTrace.Split("\n")) { result += "\n\t" + trace.Trim(); } } } return result; } public static async Task Main() { string apiKey = "---"; string apiUrl = "https://api.openai.com/v1/chat/completions"; string jsonBody = @" { ""model"": ""gpt-3.5-turbo"", ""messages"": [ { ""role"": ""system"", ""content"": ""Ready to Translate ."" }, { ""role"": ""user"", ""content"": ""class FibonacciExample1{public static void main(String[] args){int n1=0,n2=1,n3,i,count=10;System.out.print(n1+"" + n2); for (i = 2; i < count; ++i) { n3 = n1 + n2; System.out.print(\"" + n3 + ""\"); n1 = n2; n2 = n3; }} }"" }, { ""role"": ""system"", ""content"": ""Translate the code from[Java] to[Python].""" } ], ""temperature"": 1.0, ""max_tokens"": 150 }"; // Translate the code string translatedCode = await TranslateCodeAsync(apiKey, apiUrl, jsonBody); Console.WriteLine(translatedCode); } } }
问题排查与解决方案
1. JSON格式转义错误
原始jsonBody中用户消息的Java代码部分存在转义混乱,导致JSON结构无效。比如System.out.print(\"" + n3 + ""\")的转义方式错误,正确的JSON字符串转义应该统一使用\"。
2. 消息角色与顺序问题
Chat API的消息序列需遵循合理逻辑:system角色用于设定上下文,user角色用于提交具体请求。原始代码中最后一条消息用system角色发送翻译指令,不符合API设计逻辑,应改为user角色,或合并到同一条用户消息中。
3. 多余的请求头
手动添加Connection: keep-alive头无必要,HttpClient会自动处理连接管理,多余的头可能引发请求格式问题。
修正后的代码
建议使用对象序列化生成JSON(需引入System.Text.Json),彻底避免手动拼接的格式错误:
using System; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace OpenAIProgram { public class CodeTranslator { // 定义API请求模型 private class ChatCompletionRequest { public string model { get; set; } public ChatMessage[] messages { get; set; } public double temperature { get; set; } public int max_tokens { get; set; } } private class ChatMessage { public string role { get; set; } public string content { get; set; } } public static async Task<string> TranslateCodeAsync(string apiKey, string apiUrl, ChatCompletionRequest requestBody) { string result = string.Empty; try { if (string.IsNullOrEmpty(apiUrl) || requestBody == null) throw new Exception("Missing parameter for execution"); using var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); // 序列化请求对象为JSON string jsonBody = JsonSerializer.Serialize(requestBody); var request = new HttpRequestMessage(HttpMethod.Post, apiUrl); request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json"); var response = await httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { result = await response.Content.ReadAsStringAsync(); } else { // 获取错误详情,帮助排查 string errorContent = await response.Content.ReadAsStringAsync(); throw new Exception($"Response code was {response.StatusCode}. Error details: {errorContent}"); } } catch (Exception e) { result = e.Message; result += "\n" + e.GetType() + ": " + e.Message; if (e.StackTrace != null) { foreach (var trace in e.StackTrace.Split("\n")) { result += "\n\t" + trace.Trim(); } } } return result; } public static async Task Main() { string apiKey = "---"; string apiUrl = "https://api.openai.com/v1/chat/completions"; // 构造正确的请求体 var requestBody = new ChatCompletionRequest { model = "gpt-3.5-turbo", temperature = 1.0, max_tokens = 150, messages = new[] { new ChatMessage { role = "system", content = "你是专业的代码翻译工具,将用户提供的代码准确翻译成指定语言。" }, new ChatMessage { role = "user", content = @"请将以下Java代码翻译成Python: class FibonacciExample1{public static void main(String[] args){int n1=0,n2=1,n3,i,count=10;System.out.print(n1+"" ""+n2); for (i = 2; i < count; ++i) { n3 = n1 + n2; System.out.print("" ""+n3); n1 = n2; n2 = n3; }} }" } } }; // 执行翻译 string translatedCode = await TranslateCodeAsync(apiKey, apiUrl, requestBody); Console.WriteLine(translatedCode); } } }
额外建议
- 捕获错误时,读取响应内容获取OpenAI返回的具体错误信息,比仅返回状态码更有助于排查问题。
- 始终使用序列化工具生成JSON,避免手动拼接导致的格式疏漏。
内容的提问来源于stack exchange,提问作者Jes
相关产品推荐
相关产品推荐

