#include #include #include const char* ssid = "MLDEV"; const char* password = "Aysyw2ch?"; const char* openai_api_key = "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"; // Place your API key here const char* openai_endpoint = "https://api.openai.com/v1/chat/completions"; String getChatGPTResponse(String prompt) { HTTPClient http; String response = ""; String payload = "{\"model\": \"gpt-4o-mini\", \"messages\": [{\"role\": \"user\", \"content\": \"" + prompt + "\"}], \"max_tokens\": 50}"; http.begin(openai_endpoint); http.addHeader("Content-Type", "application/json"); http.addHeader("Authorization", "Bearer " + String(openai_api_key)); int httpResponseCode = http.POST(payload); Serial.printf("HTTP Response Code: %d\n", httpResponseCode); if (httpResponseCode == HTTP_CODE_OK) { String serverResponse = http.getString(); Serial.println("Response from OpenAI:"); Serial.println(serverResponse); DynamicJsonDocument doc(2048); DeserializationError error = deserializeJson(doc, serverResponse); if (error) { Serial.print("deserializeJson() failed: "); Serial.println(error.c_str()); response = "Error: Failed to parse JSON."; } else { String content = doc["choices"][0]["message"]["content"].as(); response = content ? content : "Error: No valid response from OpenAI."; } } else { Serial.printf("HTTP Response code: %d\n", httpResponseCode); response = "Error: Failed to connect to OpenAI API."; } http.end(); return response; } void setup() { Serial.begin(115200); Serial.print("Connecting to WiFi"); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.print("."); } Serial.println("\nWiFi connected!"); Serial.println("Type your prompt and press Enter to send it to ChatGPT:"); } void loop() { if (Serial.available()) { String prompt = Serial.readStringUntil('\n'); prompt.trim(); if (!prompt.isEmpty()) { Serial.println("Sending prompt to ChatGPT..."); String chatResponse = getChatGPTResponse(prompt); Serial.println("ChatGPT Response:"); Serial.println(chatResponse); } else { Serial.println("Prompt cannot be empty. Try again."); } } delay(100); }