arduinoartificial-intelligenceopenai-apiarduino-esp32chatgpt-api

OpenAI Chat Completions API error: Why do I get an HTTP error 400 on the ESP32 board?


I was planning to make a project to receive the response given by chatgpt to my ESP32 board for a given text. I tried the following, but after connecting to the WiFi, the serial plotter shows the message HTTP error 400. I double-checked the API key, and it was perfectly OK. Can you please tell me where I got it wrong?

#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);

  // Send the request to the OpenAI API
  HTTPClient http;
  http.begin("https://api.openai.com/v1/engines/gpt-3.5-turbo/completions");
  http.addHeader("Content-Type", "application/json");
  http.addHeader("Authorization", "Bearer " + String(apiKey));
  
  int httpResponseCode = http.POST(payloadStr);
  
  if (httpResponseCode == 200) {
    String response = http.getString();
    Serial.println("API Response:");
    Serial.println(response); // Print the API response
  } else {
    Serial.println("HTTP Error: " + String(httpResponseCode));
  }

  http.end();
}

void loop() {
}

I was expecting to see the response to my text from the OpenAI API, but it returned an HTTP error 400. I am not getting where it went wrong.


Solution

  • Problem

    All Engines API endpoints are deprecated.

    Deprecated

    Solution

    Use the Chat Completions API endpoint.

    Change the URL from this...

    https://api.openai.com/v1/engines/gpt-3.5-turbo/completions
    

    ...to this.

    https://api.openai.com/v1/chat/completions