(Arduino) Trying to send a web request with OpenAI API

July 30, 2024, 04:55

koukatsuwu

cpp
# include <WiFi.h>

char  ssid = "";
char  password = "";
char * key = "Bearer "; 
//pretend these were filled out

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: system,\
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();
    }
}
This is the code I'm using ^^ I've tried a ton of stuff but I only ever get an error code 400.... For reference, here's the request working
bash
curl https://api.openai.com/v1/chat/completions   -H "Content-Type: application/json"   -H "Authorization: $KEY"   -d '{
    "model": "gpt-3.5-turbo",
    "messages": [
      {
        "role": "system",
        "content": "Why is grass green?."
      }
    ]
  }'
^^ the above command actually returns a ChatGPT-generated response