/*
ESP32 HTTPClient Jokes API Example
https://wokwi.com/projects/342032431249883731
Copyright (C) 2022, Uri Shaked
*/
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
#define BTN_PIN 5
#define TFT_DC 2
#define TFT_CS 15
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
const String url = "https://api.openai.com/v1/chat/completions";
const String apiKey = "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"; // Replace with your OpenAI API key
String prompt = "hello";
String getGPTAnswer() {
HTTPClient http;
http.begin(url);
//http.addHeader("Content-Type", "application/json");
//http.addHeader("Authorization", "Bearer " + apiKey);
http.addHeader("Content-Type", "application/json");
String token_key = String("Bearer ") + apiKey;
http.addHeader("Authorization", token_key);
//String data = "{ \"model\": \"gpt-3.5-turbo-0301\",\"messages\": \[{\"role\": \"user\",\"content\":\ + prompt + "\"\}\]\}";
//String data = ("{ \"model\": \"gpt-3.5-turbo-0301\", \"messages\": ") + prompt + String(", \"temperature\": 0, \"max_tokens\": 7}");
//how to get promptpay callback when payment completed?
String post_body = "{\"model\": \"";
post_body += "gpt-3.5-turbo";//model;
post_body += "\", \"messages\": [{\"role\": \"";
post_body += "assistant";//role;
post_body += "\", \"content\": \"";
post_body += prompt;//content;
post_body += "\"}]}";
int httpResponseCode = http.POST(post_body);
if (httpResponseCode == 200) {
String response = http.getString();
DynamicJsonDocument doc(2048);
DeserializationError error = deserializeJson(doc, response);
if (error) {
Serial.print("deserializeJson() failed: ");
Serial.println(error.c_str());
return "<error>";
}
String answer = doc["choices"][0]["message"]["content"].as<String>();;
http.end();
return answer;
} else {
Serial.print("HTTP POST request failed, error code: ");
Serial.println(httpResponseCode);
http.end();
return "<error>";
}
}
void setup() {
pinMode(BTN_PIN, INPUT_PULLUP);
WiFi.mode(WIFI_STA);
WiFi.disconnect();
WiFi.begin(ssid, password);
tft.begin();
tft.setRotation(1);
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(2);
tft.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(100);
tft.print(".");
}
tft.print("\nOK! IP=");
tft.println(WiFi.localIP());
tft.fillScreen(ILI9341_BLACK);
tft.setCursor(0, 0);
String answer = getGPTAnswer();
tft.setTextColor(ILI9341_GREEN);
tft.println(answer);
Serial.begin(115200);
Serial.println("Enter a prompt:");
}
void loop() {
if (Serial.available()) {
tft.fillScreen(ILI9341_BLACK);
tft.setCursor(0, 0);
tft.setTextColor(ILI9341_WHITE);
tft.println("\nLoading...");
prompt = Serial.readStringUntil('\n');
prompt.trim();
String answer = getGPTAnswer();
Serial.println("Answer: " + answer);
Serial.println("Enter a prompt:");
tft.setTextColor(ILI9341_GREEN);
tft.println(answer);
}
}