I keep getting an error 400 from the ChatGPT API when trying to use my Arduino Giga R1 WiFi to send a request
Here's the code
# include <WiFi.h>
char * ssid = "";
char * password = "";
//pretend these are filled in
char * key = "Bearer xxxxxx"; //pretend this is an API key
void setup() {
Serial.begin(9600);
if (!Serial) { delay(5000); }
Serial.print("Connecting to WiFi\n");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) { continue; }
Serial.print("Connected!\n");
WiFiSSLClient client;
Serial.print("Connecting to OpenAI\n");
if (!client.connectSSL("api.openai.com", 443)) {
Serial.print("Connection failed!");
return;
}
Serial.print("Connected!\n");
String payload = "{\
\"model\": \"gpt-3.5-turbo\",\
\"messages\": [{\
\"role\": \"user\",\
\"content\": \"Why is grass green?\"\
}]\
}";
client.println("POST /v1/chat/completions HTTPS/1.0");
client.println("Host: api.openai.com");
client.println("Content-Type: application/json");
client.print("Content-Length: ");
client.println(payload.length());
client.print("Authorization: ");
client.println(key);
client.println();//separate data from headers
client.println(payload);
while (client.available()) {
char c = client.read();
Serial.print(c);
}
if (!client.connected()) {
Serial.print("disconnected\n");
client.stop();
}
}
void loop() {
}
This is the error:
This is an example of the web request working as intended (With the same API key & data)
How can I fix this? What's wrong with my formatting?