#Arduino Giga failing to interact with ChatGPT API

1 messages · Page 1 of 1 (latest)

robust owl
#

Hey I'm getting error code 400 when trying to use an Arduino to send a web request to ChatGPT
Here's the code ```cpp

include <WiFi.h>

char * ssid = "";
char * password = "";
char * key = "Bearer xxxxx"; //deleted all the info for ssid, pass & key because privacy -- pretend it's filled in

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 code (pic related)

And here's the web request working as intended (pic related) so I know my overall request is okay, just the formatting or something with Arduino is what's wrong
teal vault
robust owl
teal vault
robust owl
#

It's a string

#

you put a \ so you can do a new line

teal vault
#

Use only \ before " not for escaping new line

robust owl
#
    String payload = "{\
\"model\": \"gpt-3.5-turbo\",\
\"messages\": [{\
\"role\": \"user\",\
\"content\": \"Why is grass green?\"\
}]\
}";``` is the exact same thing as 
String payload = "{\

"model": "gpt-3.5-turbo","messages": [{"role": "user","content": "Why is grass green?"}]}";```

teal vault
#

Yes and it's wrong

robust owl
#

the difference is it's 1 line in the editor vs multiple lines in the editor

#

it literally makes no functional difference

teal vault
#

Both wrong

#
    String payload = "{
\"model\": \"gpt-3.5-turbo\",
\"messages\": [{
\"role\": \"user\",
\"content\": \"Why is grass green?\"
}]
}";
#

That's a JSON string, it's will be parsed by the server

#

If your JSON is invalid, you have this error

#

It's better to work with object and transform it to JSON when sending it to the server

#

Instead of escaping yourself

robust owl
#

you can't just start a new line in quotes like that

#

you need the backslash

#

this is C++ come on

teal vault
#

Ok man, good luck

flint flume
#

@teal vault just wanted to say that you were right here, in case anyone else is looking at this in the future with the same issues