├── LICENSE ├── README.md └── src ├── ChatGPTAPI.cpp ├── ChatGPTAPI.h ├── OpenAIAPIToken.h ├── WifiManager.cpp ├── WifiManager.h ├── main.cpp ├── rootCA.h └── wifi_credentials.h /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Tech Life Hacking 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # M5StackChatGPTAPI 2 | 3 | Traditionally, the use of ChatGPT has been primarily in Python and PC-based applications. However, its utilization on edge devices has been restricted due to the scarcity of libraries, with very few, if any, examples available. Bearing this in mind, we have confirmed that ChatGPT can be used on the M5Stack, which is based on the ESP32. C++ development using libraries such as M5Unified and m5stack-avatar is actively conducted on the M5Stack. Consequently, we have implemented the ChatGPT API in C++. 4 | 5 | ![stream](https://www.techlife-hacking.com/wp-content/uploads/2023/06/stream.gif) 6 | 7 | # Example 8 | 9 | ```cpp 10 | #include "ChatGPTAPI.h" 11 | #include 12 | #include "WifiManager.h" 13 | 14 | String inputText = 15 | "Please tell us about Japan's capital city and its one attraction."; 16 | String response; 17 | 18 | // setup ChatGPT API class 19 | String model = "gpt-4"; // or gpt-3.5-turbo 20 | ChatGPTAPI chatGPTAPI(OPENAI_TOKEN, model); 21 | 22 | // setup WiFi 23 | WifiManager wifiManager(WIFI_SSID, WIFI_PASS); 24 | 25 | void setup() 26 | { 27 | M5.begin(); 28 | wifiManager.connect(); 29 | } 30 | 31 | void loop() 32 | { 33 | M5.update(); 34 | 35 | if (M5.BtnA.wasReleased() || 36 | (M5.Touch.getCount() && M5.Touch.getDetail(0).wasClicked())) { 37 | response = chatGPTAPI.requestChatCompletion(inputText); 38 | M5.Lcd.print(response); 39 | M5.Lcd.print("\n"); 40 | } 41 | } 42 | 43 | ``` 44 | -------------------------------------------------------------------------------- /src/ChatGPTAPI.cpp: -------------------------------------------------------------------------------- 1 | #include "ChatGPTAPI.h" 2 | #include "rootCA.h" 3 | 4 | ChatGPTAPI::ChatGPTAPI(const char *token, String model) : token(token), prompt("You are helpful assistant."), maxTokens(100), temperature(1), top_p(1), model(model) 5 | { 6 | client.setCACert(root_ca); 7 | } 8 | 9 | ChatGPTAPI::ChatGPTAPI(const char *token, String prompt, int maxTokens, float temperature, float top_p, String model) : token(token), prompt(prompt), maxTokens(maxTokens), temperature(temperature), top_p(top_p), model(model) 10 | { 11 | client.setCACert(root_ca); 12 | } 13 | 14 | String ChatGPTAPI::requestChatCompletion(String inputText) 15 | { 16 | String url = "https://api.openai.com/v1/chat/completions"; 17 | String payload = "{\"messages\": [{\"role\": \"system\", \"content\": \"" + prompt + "\"}, {\"role\": \"user\", \"content\": \"" + inputText + "\"}],\"max_tokens\":" + String(maxTokens) + ", \"temperature\":" + float(temperature) + ", \"top_p\":" + float(top_p) + ", \"model\": \"" + model + "\"}"; 18 | if (!client.connect("api.openai.com", 443)) 19 | { 20 | Serial.println("connection failed"); 21 | return ""; 22 | } 23 | 24 | client.println("POST " + String(url) + " HTTP/1.1"); 25 | client.println("Host: api.openai.com"); 26 | client.println("Content-Type: application/json"); 27 | client.println("Content-Length: " + String(payload.length())); 28 | client.println("Authorization: Bearer " + String(token)); 29 | client.println("Connection: close"); 30 | client.println(); 31 | client.println(payload); 32 | 33 | while (client.connected()) 34 | { 35 | String line = client.readStringUntil('\n'); 36 | if (line == "\r") 37 | { 38 | break; 39 | } 40 | } 41 | 42 | String response = ""; 43 | while (client.available()) 44 | { 45 | char c = client.read(); 46 | response += c; 47 | } 48 | 49 | client.stop(); 50 | 51 | // Create DynamicJsonDocument based on the size of the response. 52 | DynamicJsonDocument jsonDoc(response.length()); 53 | deserializeJson(jsonDoc, response); 54 | String outputText = jsonDoc["choices"][0]["message"]["content"]; 55 | 56 | return outputText; 57 | } 58 | -------------------------------------------------------------------------------- /src/ChatGPTAPI.h: -------------------------------------------------------------------------------- 1 | #ifndef CHATGPTAPI_H 2 | #define CHATGPTAPI_H 3 | 4 | #include 5 | #include 6 | 7 | class ChatGPTAPI 8 | { 9 | public: 10 | ChatGPTAPI(const char *token, String model); 11 | ChatGPTAPI(const char *token, String prompt, int maxTokens, float temperature, float top_p, String model); 12 | String requestChatCompletion(String inputText); 13 | 14 | private: 15 | const char *token; 16 | String prompt; 17 | int maxTokens; 18 | float temperature; 19 | float top_p; 20 | String model; 21 | WiFiClientSecure client; 22 | }; 23 | 24 | #endif // CHATGPTAPI_H -------------------------------------------------------------------------------- /src/OpenAIAPIToken.h: -------------------------------------------------------------------------------- 1 | // OpenAI API Token 2 | #define OPENAI_TOKEN "YourOPENAI_TOKEN" -------------------------------------------------------------------------------- /src/WifiManager.cpp: -------------------------------------------------------------------------------- 1 | #include "WifiManager.h" 2 | #include 3 | 4 | WifiManager::WifiManager(const char *ssid, const char *password) : ssid(ssid), password(password) {} 5 | 6 | void WifiManager::connect() 7 | { 8 | WiFi.begin(ssid, password); 9 | while (WiFi.status() != WL_CONNECTED) 10 | { 11 | delay(500); 12 | M5.Lcd.print("."); 13 | } 14 | M5.Lcd.print("\nWiFi connected"); 15 | M5.Lcd.print("\nIP address: "); 16 | M5.Lcd.print(WiFi.localIP()); 17 | M5.Lcd.print("\n"); 18 | } 19 | -------------------------------------------------------------------------------- /src/WifiManager.h: -------------------------------------------------------------------------------- 1 | #ifndef WIFIMANAGER_H 2 | #define WIFIMANAGER_H 3 | 4 | #include 5 | 6 | class WifiManager 7 | { 8 | public: 9 | WifiManager(const char *ssid, const char *password); 10 | void connect(); 11 | 12 | private: 13 | const char *ssid; 14 | const char *password; 15 | }; 16 | 17 | #endif // WIFIMANAGER_H 18 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "ChatGPTAPI.h" 3 | #include "WifiManager.h" 4 | #include "wifi_credentials.h" 5 | #include "OpenAIAPIToken.h" 6 | 7 | String inputText = "Where is the capital of USA?"; 8 | String response; 9 | 10 | String model = "gpt-4"; 11 | ChatGPTAPI chatGPTAPI(OPENAI_TOKEN, model); 12 | 13 | // String prompt = "You are helpful assistant."; 14 | // int max_tokens = 100; 15 | // float temperature = 1; 16 | // float top_p = 0.1; 17 | // String model = "gpt-4"; // or gpt-3.5-turbo 18 | // ChatGPTAPI chatGPTAPI(OPENAI_TOKEN, prompt, max_tokens, temperature, top_p, model); 19 | 20 | WifiManager wifiManager(WIFI_SSID, WIFI_PASS); 21 | 22 | void setup() 23 | { 24 | M5.begin(); 25 | wifiManager.connect(); 26 | } 27 | 28 | void loop() 29 | { 30 | M5.update(); 31 | 32 | if (M5.BtnA.wasReleased()) 33 | { 34 | response = chatGPTAPI.requestChatCompletion(inputText); 35 | M5.Lcd.print(response); 36 | M5.Lcd.print("\n"); 37 | } 38 | } -------------------------------------------------------------------------------- /src/rootCA.h: -------------------------------------------------------------------------------- 1 | #ifndef ROOTCA_H 2 | #define ROOTCA_H 3 | const char *root_ca = \ 4 | "-----BEGIN CERTIFICATE-----\n" \ 5 | "MIIDzTCCArWgAwI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DQYJKoZIhvcNAQELBQADggEB\n" \ 20 | "AAUkHd0bsCrrmNaF4zlNXmtXnYJX/OvoMaJXkGUFvhZEOFp3ArnPEELG4ZKk40Un\n" \ 21 | "+ABHLGioVplTVI+tnkDB0A+21w0LOEhsUCxJkAZbZB2LzEgwLt4I4ptJIsCSDBFe\n" \ 22 | "lpKU1fwg3FZs5ZKTv3ocwDfjhUkV+ivhdDkYD7fa86JXWGBPzI6UAPxGezQxPk1H\n" \ 23 | "goE6y/SJXQ7vTQ1unBuCJN0yJV0ReFEQPaA1IwQvZW+cwdFD19Ae8zFnWSfda9J1\n" \ 24 | "CZMRJCQUzym+5iPDuI9yP+kHyCREU3qzuWFloUwOxkgAyXVjBYdwRVKD05WdRerw\n" \ 25 | "6DEdfgkfCv4+3ao8XnTSrLE=\n" \ 26 | "-----END CERTIFICATE-----\n"; 27 | 28 | #endif // ROOTCA_H -------------------------------------------------------------------------------- /src/wifi_credentials.h: -------------------------------------------------------------------------------- 1 | // Wifi Settings 2 | #define WIFI_SSID "YourWiFiSSID" 3 | #define WIFI_PASS "YourWiFiPassword" --------------------------------------------------------------------------------