Discord ChatGPT机器人适配gpt-3.5-turbo时API报错及解决
问题:适配gpt-3.5-turbo时Discord机器人调用OpenAI API报错
约一周前开发了一个将ChatGPT接入Discord服务器的机器人,OpenAI更新模型后,尝试适配gpt-3.5-turbo时运行ask命令出现报错:
Error communicating with OpenAI API. Status code: BadRequest
Error content: {
"error": {
"message": "'messages' is a required property",
"type": "invalid_request_error",
"param": null,
"code": null
}
}
曾尝试在requestBody中添加messages = query,但提示该值为空,陷入困境。问题代码如下:
public async Task<string> GetOpenAiResponse(string query) { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {GptApiKey}"); string prompt = $"User: {query}\nChatGPT:"; // Create a JSON object for the request payload var requestBody = new { prompt = prompt, model = "gpt-3.5-turbo", max_tokens = 150 }; // Serialize the JSON object to a string var jsonContent = JsonConvert.SerializeObject(requestBody); // Use StringContent with the correct content type var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); var response = await client.PostAsync("https://api.openai.com/v1/chat/completions", content); if (response.IsSuccessStatusCode) { string result = await response.Content.ReadAsStringAsync(); // Parsing JSON to extract the response text var jsonResponse = JObject.Parse(result); var choices = jsonResponse["choices"]; var firstChoice = choices.FirstOrDefault(); var text = firstChoice?["text"].ToString(); return text ?? "Unable to parse OpenAI response."; } else { Console.WriteLine($"Error communicating with OpenAI API. Status code: {response.StatusCode}"); string errorContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Error content: {errorContent}"); return "Error communicating with OpenAI API."; } } }
解决方案:修改请求体结构与响应解析逻辑
参考Jon的答案后修改代码,机器人已可正常运行,正确代码如下:
public async Task<string> GetOpenAiResponse(string query) { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {GptApiKey}"); string prompt = $"User: {query}\nChatGPT:"; // Create message objects for the system and user messages var messages = new List<object> { new { role = "system", content = "You are a helpful assistant." }, new { role = "user", content = query } }; // Create a JSON object for the request payload var requestBody = new { model = "gpt-3.5-turbo", messages = messages, max_tokens = 150 }; // Serialize the JSON object to a string var jsonContent = JsonConvert.SerializeObject(requestBody); // Use StringContent with the correct content type var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); var response = await client.PostAsync("https://api.openai.com/v1/chat/completions", content); if (response.IsSuccessStatusCode) { string result = await response.Content.ReadAsStringAsync(); // Parsing JSON to extract the response text var jsonResponse = JObject.Parse(result); var choices = jsonResponse["choices"]; var firstChoice = choices.FirstOrDefault(); var text = firstChoice["message"]["content"].ToString(); return text ?? "Unable to parse OpenAI response."; } else { Console.WriteLine($"Error communicating with OpenAI API. Status code: {response.StatusCode}"); string errorContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Error content: {errorContent}"); return "Error communicating with OpenAI API."; } } }
内容的提问来源于stack exchange,提问作者Voidpool
相关产品推荐
相关产品推荐

