ESP32调用OpenAI Chat Completions API遇HTTP 400错误求排查
ESP32调用ChatGPT API出现HTTP 400错误的排查与修复
HTTP 400错误表示请求格式或参数不符合API要求,结合你的代码,主要问题和修复方案如下:
核心问题:API端点错误
gpt-3.5-turbo属于聊天模型,必须使用聊天接口端点,你当前使用的是旧的补全接口端点,这是导致400错误的主要原因。
修复步骤
修正API端点
将原代码中的:http.begin("https://api.openai.com/v1/engines/gpt-3.5-turbo/completions");修改为:
http.begin("https://api.openai.com/v1/chat/completions");验证Authorization头构造
确保Authorization头的格式正确,Bearer后必须有一个空格,可调整为更稳妥的拼接方式:String authHeader = "Bearer "; authHeader += apiKey; http.addHeader("Authorization", authHeader);增加调试步骤
在发送请求前打印序列化后的payload,确认格式是否符合要求:Serial.println("Payload:"); Serial.println(payloadStr);同时在错误分支中打印API返回的错误详情,OpenAI通常会给出具体错误原因:
String errorResponse = http.getString(); Serial.println("Error Details: " + errorResponse);
修复后的完整代码示例
#include <ArduinoJson.h> #include <WiFi.h> #include <HTTPClient.h> const char* ssid = "ssid"; const char* password = "password"; const char* apiKey = "api"; const char* userMessage = "Hey there ! how are you ?"; void setup() { Serial.begin(115200); delay(1000); // Connect to Wi-Fi WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi..."); } Serial.println("Connected to WiFi"); // Prepare the JSON payload DynamicJsonDocument payload(1024); payload["model"] = "gpt-3.5-turbo"; JsonArray messages = payload.createNestedArray("messages"); JsonObject systemMessage = messages.createNestedObject(); systemMessage["role"] = "system"; systemMessage["content"] = "You are a helpful assistant."; JsonObject userMessageObject = messages.createNestedObject(); userMessageObject["role"] = "user"; userMessageObject["content"] = userMessage; // Serialize the JSON payload String payloadStr; serializeJson(payload, payloadStr); // 调试:打印payload Serial.println("Payload:"); Serial.println(payloadStr); // Send the request to the OpenAI API HTTPClient http; // 修正后的API端点 http.begin("https://api.openai.com/v1/chat/completions"); http.addHeader("Content-Type", "application/json"); // 构造Authorization头 String authHeader = "Bearer "; authHeader += apiKey; http.addHeader("Authorization", authHeader); int httpResponseCode = http.POST(payloadStr); if (httpResponseCode == 200) { String response = http.getString(); Serial.println("API Response:"); Serial.println(response); } else { Serial.println("HTTP Error: " + String(httpResponseCode)); // 调试:打印错误详情 String errorResponse = http.getString(); Serial.println("Error Details: " + errorResponse); } http.end(); } void loop() { }
内容的提问来源于stack exchange,提问作者user3793520
相关产品推荐
相关产品推荐

