#include <Arduino.h>
#include <ArduinoJson.h>
#include <HTTPClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void chatWithGPT(const String& userMessage) {
HTTPClient http;
http.begin("https://api.openai.com/v1/chat/completions");
http.addHeader("Authorization", "Bearer gmzf75QhtvOsT3BlbkFJO0qzW4T5cYZMgJSMHbF9");
http.addHeader("Content-Type", "application/json");
String body = "{\"model\": \"gpt-3.5-turbo\",\"messages\":[{\"role\": \"user\", \"content\": \"" + userMessage + "\"}],\"temperature\": 0}";
int httpCode = http.POST(body);
if (httpCode > 0) {
String payload = http.getString();
//Serial.println(payload);
DynamicJsonDocument doc(2048);
deserializeJson(doc, payload);
String response = doc["choices"][0]["message"]["content"].as<String>();
//Serial.print("ChatGPT: ");
Serial.println(response);
} else {
Serial.println("Error on HTTP request");
}
http.end();
}
void loop() {
Serial.println("---------------------------------");
while (Serial.available() == 0) {
// Wait for user input
}
String userMessage = Serial.readStringUntil('\n');
chatWithGPT(userMessage);
}