├── .gitignore ├── Docs.md ├── LICENSE ├── README.md ├── examples ├── AITranslation │ └── AITranslation.ino ├── ChatGpt │ └── ChatGpt.ino ├── Datatest │ └── Datatest.ino ├── HuggingFace │ └── HuggingFace.ino ├── QuestionAnswering │ └── QuestionAnswering.ino ├── TextGeneration │ └── TextGeneration.ino ├── TextSummarization │ └── TextSummarization.ino └── WebUIInterface │ └── Web_UI_Interface.ino ├── library.properties └── src ├── AIChatbot.cpp └── AIChatbot.h /.gitignore: -------------------------------------------------------------------------------- 1 | # Arduino IDE 2 | build/ 3 | *.bin 4 | *.elf 5 | *.hex 6 | *.db 7 | 8 | # PlatformIO 9 | .pio/ 10 | lib/ 11 | /.vscode/ 12 | Docs.pdf 13 | -------------------------------------------------------------------------------- /Docs.md: -------------------------------------------------------------------------------- 1 | # 🤖AI Chat Library for Arduino💬 2 | 3 | AI Chat Library for Arduino allows you to easily integrate AI chatbot capabilities into your Arduino projects. This library supports multiple AI services, including OpenAI's ChatGPT and Hugging Face APIs, making it versatile and powerful for creating intelligent interactions. 4 | 5 | ## 📋 Project Overview 6 | 7 | The AI Chat Library simplifies the process of connecting your Arduino projects to AI chatbots. It handles API communication, enabling your devices to send messages and receive responses from AI services over the internet. 8 | 9 | ## 🛠️Installation 10 | 11 | 1. **Download the Library**: Clone or download the repository from [GitHub](https://github.com/bayeggex/Arduino-AI-Chat-Library). 12 | 13 | 2. **Import into Arduino IDE**: 14 | - Open Arduino IDE. 15 | - Navigate to **Sketch > Include Library > Add .ZIP Library...** and select the downloaded ZIP file. 16 | 17 | 3. **Install Dependencies**: 18 | - Ensure you have the `WiFi` and `HTTPClient` libraries installed in your Arduino IDE via the Library Manager. 19 | 20 | ## 🚀Usage 21 | 22 | ### 🗝️Setting Up AI Keys 23 | 24 | Before using the AI Chat Library, you need to set your API keys for the respective AI services. Here’s how you can do it in your Arduino sketch: 25 | 26 | ```cpp 27 | #include 28 | 29 | AIChatbot chatbot; 30 | 31 | void setup() { 32 | chatbot.begin(115200); 33 | 34 | // Set API keys 35 | chatbot.setKey("YOUR_CHATGPT_API_KEY", "chatgpt"); 36 | chatbot.setKey("YOUR_HUGGING_FACE_API_KEY", "huggingface"); 37 | 38 | // Connect to WiFi 39 | if (!chatbot.connectWiFi("SSID", "PASSWORD")) { 40 | Serial.println("Failed to connect to WiFi"); 41 | while (true); // Halt if WiFi connection fails 42 | } 43 | 44 | // Select AI service and optionally specify version 45 | chatbot.selectAI("chatgpt", "gpt-3.5-turbo"); 46 | } 47 | 48 | void loop() { 49 | // Update and handle incoming messages 50 | chatbot.update(); 51 | } 52 | ``` 53 | 54 | ### 📄Functions 55 | 56 | ### `begin(long baudRate)` 57 | 58 | - **Description**: Initializes the serial communication with the specified baud rate. 59 | - **Parameters**: 60 | - `baudRate`: The baud rate for serial communication (e.g., 115200). 61 | - **Example**: 62 | ```cpp 63 | chatbot.begin(115200); 64 | 65 | #### `connectWiFi(const char* ssid, const char* password, unsigned long timeoutMs = 10000)` 66 | 67 | - **Description**: Connects to a WiFi network with the given SSID and password. 68 | - **Parameters**: 69 | - `ssid`: WiFi SSID(Name). 70 | - `password`: WiFi password. 71 | - `timeoutMs`: (optional): Connection timeout in milliseconds (default is 10 seconds). 72 | - **Example**: 73 | ```cpp 74 | if (!chatbot.connectWiFi("YourSSID", "YourPassword")) { 75 | Serial.println("WiFi connection failed"); 76 | } 77 | 78 | #### `selectAI(const String& aiName, const String& aiVersion = "gpt-3.5-turbo")` 79 | 80 | - **Description**: Selects the AI service to use. 81 | - **Parameters**: 82 | - `aiName`: Name of the AI service (e.g., "chatgpt", "huggingface"). 83 | - `aiVersion` (optional): Version of the AI model to use (default: "gpt-3.5-turbo"). 84 | - **Example**: 85 | ```cpp 86 | chatbot.selectAI("chatgpt", "gpt-4"); 87 | 88 | #### `setKey(const String& apiKey, const String& apiName)` 89 | 90 | - **Description**: Sets the API key for a specific AI service. 91 | - **Parameters**: 92 | - `apiKey`: API key for the AI service. 93 | - `apiName` (optional): Name of the AI service (e.g., "chatgpt", "huggingface"). 94 | - **Example**: 95 | ```cpp 96 | chatbot.setKey("YOUR_CHATGPT_API_KEY", "chatgpt"); 97 | 98 | #### `getResponse(const String& message)` 99 | 100 | - **Description**: Sends a message to the selected AI service manually. 101 | - **Parameters**: 102 | - `message`: Message to send to the AI service. 103 | - **Example**: 104 | ```cpp 105 | String response = chatbot.send("Hello, how are you?"); 106 | Serial.println("Response from AI: " + response); 107 | 108 | #### `update()` 109 | 110 | - **Description**: Updates the AI Chatbot instance to handle incoming messages and maintain communication. 111 | - **Example**: 112 | ```cpp 113 | void loop() { 114 | chatbot.update(); 115 | } 116 | 117 | ### `sanitizeInput(const String& input)` 118 | 119 | - **Description**: Sanitizes the input string to prevent issues with special characters. 120 | - **Parameters**: 121 | - `input`:The input string to sanitize. 122 | 123 | 124 | ### 🔧 Internal Functions (Private) 125 | 126 | These functions are used internally by the library and are not intended to be called directly by users. 127 | 128 | `sendToChatGPT(const String& message)` 129 | 130 | - Sends a message to the OpenAI ChatGPT API and returns the response. 131 | 132 | `sendToHuggingFace(const String& message)` 133 | 134 | - Sends a message to the Hugging Face API and returns the response. 135 | 136 | `makeHttpRequest(const String& url, const String& payload, const String& apiKey)` 137 | 138 | -Makes an HTTP POST request to the specified URL with the given payload and API key. 139 | 140 | ### 📚 Header File (AIChatbot.h) 141 | 142 | ```h 143 | #ifndef AI_CHATBOT_H 144 | #define AI_CHATBOT_H 145 | 146 | #include 147 | 148 | #if defined(ESP32) 149 | #include 150 | #include 151 | #include 152 | #define PLATFORM_NAME "ESP32" 153 | #elif defined(ESP8266) 154 | #include 155 | #include 156 | #define PLATFORM_NAME "ESP8266" 157 | #endif 158 | 159 | class AIChatbot { 160 | public: 161 | AIChatbot(); 162 | bool connectWiFi(const char* ssid, const char* password, unsigned long timeoutMs = 10000); 163 | bool validateKeys(); 164 | void begin(long baudRate); 165 | void update(); 166 | void setKey(const String& key, const String& aiName); 167 | void selectAI(const String& aiName, const String& aiVersion = "gpt-3.5-turbo"); 168 | String sanitizeInput(const String& input); 169 | String getResponse(const String& message); 170 | 171 | private: 172 | String chatGPTApiKey; 173 | String huggingFaceApiKey; 174 | String selectedAI; 175 | String selectedAIVersion; 176 | String sendToChatGPT(const String& message); 177 | String sendToHuggingFace(const String& message); 178 | String makeHttpRequest(const String& url, const String& payload, const String& apiKey); 179 | }; 180 | 181 | #endif // AI_CHATBOT_H 182 | ``` 183 | 184 | ### 🔧 Example Sketches 185 | 186 | `AITranslation.ino`: Demonstrates translation capabilities using the library. 187 | 188 | `ChatGPT.ino`: Example of integrating with ChatGPT for general conversation. 189 | 190 | `DataTest.ino`: Verifies communication and tests various AI responses. 191 | 192 | `HuggingFace.ino`: Shows usage with Hugging Face models. 193 | 194 | `QuestionAnswering.ino`: Example for question-answering tasks. 195 | 196 | `TextGeneration.ino`: Demonstrates text generation capabilities. 197 | 198 | `TextSummarization.ino`: Example for summarizing input text. 199 | 200 | ### 📈 Roadmap 201 | 202 | - Add support for more AI services. 203 | 204 | - Improve error handling and debugging tools. 205 | 206 | - Enhance documentation with more detailed examples. 207 | 208 | - Voice & Image Cration. 209 | 210 | ### 🛠️ Support 211 | 212 | For [issues](https://github.com/bayeggex/Arduino-AI-Chat-Library/issues/new), [feature requests](https://github.com/bayeggex/Arduino-AI-Chat-Library/issues/new), or [Contributions](https://github.com/bayeggex/Arduino-AI-Chat-Library/pulls), please visit the [GitHub repository](https://github.com/bayeggex/Arduino-AI-Chat-Library). 213 | 214 | This library is maintained by [BayEggex](https://github.com/bayeggex). Contributions are welcome! 215 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Bay Eggex 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 |
2 | 3 | # AI Chat Library for Arduino
🤖💬 4 | 5 | 6 | ![GitHub](https://img.shields.io/github/license/bayeggex/Arduino-AI-Chat-Library) 7 | ![GitHub release (latest by date including pre-releases)](https://img.shields.io/github/v/release/bayeggex/Arduino-AI-Chat-Library?include_prereleases) 8 | [![PlatformIO Registry](https://badges.registry.platformio.org/packages/bayeggex/library/AIChatBot.svg)](https://registry.platformio.org/libraries/bayeggex/AIChatBot) 9 | [![arduino-library-badge](https://www.ardu-badge.com/badge/AIChatBot.svg?)](https://www.ardu-badge.com/AIChatBot) 10 | ![GitHub last commit](https://img.shields.io/github/last-commit/bayeggex/Arduino-AI-Chat-Library) 11 | ![GitHub issues](https://img.shields.io/github/issues-raw/bayeggex/Arduino-AI-Chat-Library) 12 | 13 |
14 | 15 | ![tenor](https://github.com/bayeggex/Arduino-AI-Chat-Library/assets/79448667/ae4451d4-2c67-43bd-b8c7-e378960c33d1) 16 | 17 | 18 | AIChatbot is a versatile Arduino library for integrating various AI chatbot APIs. It supports connecting to OpenAI's ChatGPT, Hugging Face Api's. 19 | 20 | ## ✨ Features 21 | 22 | - **Versatile AI Integration**: Integrate various AI chatbot APIs seamlessly into your Arduino projects. 23 | - **Supports Multiple APIs**: Connect to OpenAI's ChatGPT, Hugging Face APIs, and more with ease. 24 | - **Easy Setup**: Simple API key configuration and setup for quick deployment. 25 | - **Real-time Interaction**: Handle real-time messages and responses over WiFi. 26 | - **Flexible AI Selection**: Choose between different AI versions such as "gpt-3.5-turbo","gpt-4" (more will be integrated) 27 | - **Community-driven**: Contributions and improvements from the community are welcomed and encouraged. 28 | 29 | ## 🔧Installation 30 | 31 | 1. **Download the Library**: Download or clone this repository. 32 | 33 | 2. **Import into Arduino IDE**: 34 | - Open Arduino IDE. 35 | - Go to **Sketch > Include Library > Add .ZIP Library...** and select the downloaded ZIP file. 36 | 37 | 3. **Dependencies**: 38 | - This library requires the `WiFi` and `HTTPClient` libraries for making HTTP requests. Make sure to install these libraries through the Library Manager in Arduino IDE if not already installed. 39 | 40 | ## 🚀Usage 41 | 42 | ### Setting Up AI Keys 43 | 44 | Before using the AIChatbot library, you need to set your API keys for the respective AI services. You can do this in your sketch code: 45 | 46 | ```cpp 47 | #include 48 | 49 | AIChatbot chatbot; 50 | 51 | void setup() { 52 | chatbot.begin(115200); 53 | 54 | // Set API keys 55 | chatbot.setKey("YOUR_CHATGPT_API_KEY", "chatgpt"); 56 | chatbot.setKey("YOUR_HUGGING_FACE_API_KEY", "huggingface"); 57 | 58 | // Connect to WiFi 59 | if (!chatbot.connectWiFi("SSID", "PASSWORD")) { 60 | Serial.println("Failed to connect to WiFi"); 61 | while (true); // Halt if WiFi connection fails 62 | } 63 | 64 | // Select AI service and optionally specify version 65 | chatbot.selectAI("chatgpt", "gpt-3.5-turbo"); 66 | } 67 | 68 | void loop() { 69 | // Update and handle incoming messages 70 | chatbot.update(); 71 | } 72 | ``` 73 | ## 🤝 Contributing 74 | Contributions are welcome! To contribute to AIChatbot, fork this repository, make improvements, and submit a pull request. For major changes, please open an issue first to discuss what you would like to change. 75 | 76 | Fork the repository. 77 | Create a new branch: git checkout -b feature/amazing-feature 78 | Commit your changes: git commit -m 'Add some amazing feature' 79 | Push to the branch: git push origin feature/amazing-feature 80 | Open a pull request. 81 | 82 | ## 📚 Documentation 83 | 84 | For detailed documentation, please refer to [Docs.md](./Docs.md). 85 | 86 | ## 📄 License 87 | 88 | This project is licensed under the MIT License. See the LICENSE file for more details. 89 | 90 | If you find this project helpful or interesting, don't forget to give it a star! ⭐ 91 | 92 | Express yourself freely and elevate your chat experience with Arduino-AI-Chat-Library! 😊 93 | -------------------------------------------------------------------------------- /examples/AITranslation/AITranslation.ino: -------------------------------------------------------------------------------- 1 | #include "AIChatbot.h" // Include the AIChatbot library 2 | 3 | AIChatbot chatbot; // Create an instance of AIChatbot 4 | 5 | // WiFi and API credentials 6 | const char* ssid = "YOUR_SSID"; 7 | const char* password = "YOUR_PASSWORD"; 8 | const char* apiKey = "YOUR_API_KEY"; 9 | 10 | void setup() { 11 | Serial.begin(115200); // Initialize serial communication at 115200 baud rate 12 | chatbot.begin(115200); // Initialize chatbot communication at 115200 baud rate 13 | 14 | // Connect to WiFi 15 | if (chatbot.connectWiFi(ssid, password)) { 16 | // Set the API key and select the AI model for translation 17 | chatbot.setKey(apiKey, "huggingface"); 18 | chatbot.selectAI("huggingface", "Helsinki-NLP/opus-mt-en-tr"); // English to Turkish translation 19 | Serial.println("WiFi connected. Enter text to translate:"); 20 | } else { 21 | Serial.println("WiFi connection failed."); 22 | } 23 | } 24 | 25 | void loop() { 26 | if (Serial.available() > 0) { 27 | String inputText = Serial.readStringUntil('\n'); 28 | inputText.trim(); 29 | 30 | if (inputText.length() > 0) { 31 | String response = chatbot.getResponse(inputText); 32 | Serial.println("Translated Text: " + response); 33 | } else { 34 | Serial.println("Please enter valid text."); 35 | } 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /examples/ChatGpt/ChatGpt.ino: -------------------------------------------------------------------------------- 1 | #include "AIChatbot.h" // Include the AIChatbot library 2 | 3 | AIChatbot chatbot; // Create an instance of the AIChatbot class 4 | 5 | // WiFi and ChatGPT API credentials 6 | const char* ssid = "YOUR_SSID"; 7 | const char* password = "YOUR_PASSWORD"; 8 | const char* apiKey = "YOUR_CHATGPT_API_KEY"; 9 | 10 | void setup() { 11 | Serial.begin(115200); // Initialize serial communication at 115200 baud rate 12 | chatbot.begin(115200); // Initialize chatbot communication at 115200 baud rate 13 | 14 | // Connect to WiFi 15 | if (chatbot.connectWiFi(ssid, password)) { 16 | // Set the API key and select the AI model 17 | chatbot.setKey(apiKey, "chatgpt"); 18 | chatbot.selectAI("chatgpt", "gpt-3.5-turbo"); 19 | Serial.println("WiFi connected. Enter your question:"); 20 | } else { 21 | Serial.println("WiFi connection failed."); 22 | } 23 | } 24 | 25 | void loop() { 26 | // Check if there is any data available in the serial buffer 27 | if (Serial.available() > 0) { 28 | // Read the input question from the serial monitor 29 | String question = Serial.readStringUntil('\n'); 30 | question.trim(); // Remove any leading or trailing whitespace 31 | 32 | // If the question is not empty, get the response from ChatGPT 33 | if (question.length() > 0) { 34 | String response = chatbot.getResponse(question); 35 | Serial.println("ChatGPT Response: " + response); // Print the response 36 | } else { 37 | Serial.println("Please enter a valid question."); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /examples/Datatest/Datatest.ino: -------------------------------------------------------------------------------- 1 | #include "AIChatbot.h" // Include the AIChatbot library 2 | 3 | AIChatbot chatbot; // Create an instance of the AIChatbot class 4 | 5 | // WiFi credentials and API key 6 | const char* ssid = "YOUR_SSID"; 7 | const char* password = "YOUR_PASSWORD"; 8 | const char* apiKey = "YOUR_API_KEY"; 9 | 10 | void setup() { 11 | Serial.begin(115200); // Initialize serial communication at 115200 baud rate 12 | chatbot.begin(115200); // Initialize chatbot communication at 115200 baud rate 13 | 14 | // Attempt to connect to WiFi 15 | if (chatbot.connectWiFi(ssid, password)) { 16 | chatbot.setKey(apiKey, "chatgpt"); // Set the API key for the chatbot 17 | chatbot.selectAI("chatgpt"); // Select the AI model to use 18 | Serial.println(" test ready. Enter any text:"); // Indicate that the is ready for input 19 | } else { 20 | Serial.println("WiFi connection failed."); // Indicate that the WiFi connection failed 21 | } 22 | } 23 | 24 | void loop() { 25 | // Check if there is any input from the serial monitor 26 | if (Serial.available() > 0) { 27 | String inputText = Serial.readStringUntil('\n'); // Read the input text until a newline character is encountered 28 | inputText.trim(); // Remove any leading or trailing whitespace 29 | 30 | // Check if the input text is not empty 31 | if (inputText.length() > 0) { 32 | String response = chatbot.getResponse(inputText); // Get the response from the chatbot 33 | Serial.println("Response: " + response); // Print the response to the serial monitor 34 | } else { 35 | Serial.println("Please enter valid text."); // Prompt the user to enter valid text 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /examples/HuggingFace/HuggingFace.ino: -------------------------------------------------------------------------------- 1 | #include "AIChatbot.h" // Include the AIChatbot library 2 | 3 | AIChatbot chatbot; // Create an instance of the AIChatbot class 4 | 5 | // WiFi credentials 6 | const char* ssid = "YOUR_SSID"; 7 | const char* password = "YOUR_PASSWORD"; 8 | 9 | // API key for HuggingFace 10 | const char* apiKey = "YOUR_HUGGINGFACE_API_KEY"; 11 | 12 | void setup() { 13 | Serial.begin(115200); // Initialize serial communication at 115200 baud rate 14 | chatbot.begin(115200); // Initialize the chatbot with the same baud rate 15 | 16 | // Attempt to connect to WiFi 17 | if (chatbot.connectWiFi(ssid, password)) { 18 | // Set the API key and select the AI model 19 | chatbot.setKey(apiKey, "huggingface"); 20 | chatbot.selectAI("huggingface", "distilbert-base-uncased"); 21 | Serial.println("WiFi connected. Enter text:"); 22 | } else { 23 | Serial.println("WiFi connection failed."); 24 | } 25 | } 26 | 27 | void loop() { 28 | // Check if there is any input from the serial monitor 29 | if (Serial.available() > 0) { 30 | String inputText = Serial.readStringUntil('\n'); // Read the input text until newline character 31 | inputText.trim(); // Remove any leading or trailing whitespace 32 | 33 | // If the input text is not empty, get the AI response 34 | if (inputText.length() > 0) { 35 | String response = chatbot.getResponse(inputText); 36 | Serial.println("AI Response: " + response); // Print the AI response 37 | } else { 38 | Serial.println("Please enter valid text."); // Prompt user to enter valid text 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /examples/QuestionAnswering/QuestionAnswering.ino: -------------------------------------------------------------------------------- 1 | #include "AIChatbot.h" // Include the AIChatbot library 2 | 3 | AIChatbot chatbot; // Create an instance of the AIChatbot class 4 | 5 | // WiFi credentials 6 | const char* ssid = "YOUR_SSID"; 7 | const char* password = "YOUR_PASSWORD"; 8 | // API key for Hugging Face 9 | const char* apiKey = "YOUR_HUGGINGFACE_API_KEY"; 10 | 11 | void setup() { 12 | Serial.begin(115200); // Initialize serial communication at 115200 baud rate 13 | chatbot.begin(115200); // Initialize chatbot communication at 115200 baud rate 14 | 15 | // Attempt to connect to WiFi 16 | if (chatbot.connectWiFi(ssid, password)) { 17 | // Set the API key and select the AI model 18 | chatbot.setKey(apiKey, "huggingface"); 19 | chatbot.selectAI("huggingface", "deepset/roberta-base-squad2"); 20 | Serial.println("WiFi connected. Enter your question:"); 21 | } else { 22 | Serial.println("WiFi connection failed."); 23 | } 24 | } 25 | 26 | void loop() { 27 | // Check if there is any input from the serial monitor 28 | if (Serial.available() > 0) { 29 | String question = Serial.readStringUntil('\n'); // Read the input question 30 | question.trim(); // Remove any leading or trailing whitespace 31 | 32 | // If the question is not empty, get the response from the chatbot 33 | if (question.length() > 0) { 34 | String response = chatbot.getResponse(question); 35 | Serial.println("Answer: " + response); // Print the response 36 | } else { 37 | Serial.println("Please enter a valid question."); // Prompt for a valid question 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /examples/TextGeneration/TextGeneration.ino: -------------------------------------------------------------------------------- 1 | #include "AIChatbot.h" // Include the AIChatbot library 2 | 3 | AIChatbot chatbot; // Create an instance of the AIChatbot class 4 | 5 | // WiFi credentials 6 | const char* ssid = "YOUR_SSID"; 7 | const char* password = "YOUR_PASSWORD"; 8 | 9 | // API key for Hugging Face 10 | const char* apiKey = "YOUR_HUGGINGFACE_API_KEY"; 11 | 12 | void setup() { 13 | Serial.begin(115200); // Initialize serial communication at 115200 baud rate 14 | chatbot.begin(115200); // Initialize the chatbot with the same baud rate 15 | 16 | // Attempt to connect to WiFi 17 | if (chatbot.connectWiFi(ssid, password)) { 18 | // Set the API key and select the AI model 19 | chatbot.setKey(apiKey, "huggingface"); 20 | chatbot.selectAI("huggingface", "gpt2"); 21 | Serial.println("WiFi connected. Enter a prompt to generate text:"); 22 | } else { 23 | Serial.println("WiFi connection failed."); // Print error message if WiFi connection fails 24 | } 25 | } 26 | 27 | void loop() { 28 | // Check if there is any input from the serial monitor 29 | if (Serial.available() > 0) { 30 | String prompt = Serial.readStringUntil('\n'); // Read the input until a newline character 31 | prompt.trim(); // Remove any leading or trailing whitespace 32 | 33 | // Check if the prompt is not empty 34 | if (prompt.length() > 0) { 35 | String response = chatbot.getResponse(prompt); // Get the response from the chatbot 36 | Serial.println("Generated Text: " + response); // Print the generated text 37 | } else { 38 | Serial.println("Please enter a valid prompt."); // Prompt the user to enter a valid input 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /examples/TextSummarization/TextSummarization.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | AIChatbot chatbot; 4 | 5 | void setup() { 6 | Serial.begin(115200); 7 | chatbot.setKey("YOUR_CHATGPT_API_KEY", "chatgpt"); 8 | chatbot.connectWiFi("YOUR_SSID", "YOUR_PASSWORD"); 9 | chatbot.selectAI("chatgpt", "gpt-3.5-turbo"); 10 | } 11 | 12 | void loop() { 13 | if (Serial.available() > 0) { 14 | String incomingMessage = Serial.readString(); 15 | String message = "Summarize the following text: " + incomingMessage; 16 | String response = chatbot.getResponse(message); 17 | Serial.println("Summary: " + response); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /examples/WebUIInterface/Web_UI_Interface.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | const char* ssid = "YOUR_SSID"; 6 | const char* password = "YOUR_PASSWORD"; 7 | // const char* apiKey = "YOUR_CHATGPT_API_KEY"; //for OPENAI 8 | const char* apiKey = "YOUR_HUGGING_FACE_API_KEY"; //for Hugging face 9 | const char* model = "HuggingFaceH4/zephyr-7b-beta" 10 | 11 | AIChatbot chatbot; 12 | WebServer server(80); 13 | 14 | const char index_html[] PROGMEM = R"rawliteral( 15 | 16 | 17 | 18 | 19 | 20 | ESP32 ChatBot 21 | 98 | 99 | 100 |

Arduino-AI-Chat-Library Interface

101 |
102 | 103 |
104 | 105 | 106 | 107 |
108 | 109 |
110 |

Built with ❤️ by BayEggex | Powered by Your❤️

111 |
112 | 113 | 171 | 172 | 173 | )rawliteral"; 174 | 175 | 176 | void setup() { 177 | Serial.begin(115200); 178 | WiFi.begin(ssid, password); 179 | Serial.print("Connecting to Wi-Fi..."); 180 | while (WiFi.status() != WL_CONNECTED) { 181 | delay(500); 182 | Serial.print("."); 183 | } 184 | Serial.println("\nConnected to Wi-Fi!"); 185 | Serial.print("IP Address: "); 186 | Serial.println(WiFi.localIP()); 187 | 188 | Serial.println("Now, open your browser and type in the " + WiFi.localIP().toString() + " Address shown above."); 189 | 190 | chatbot.setKey(apiKey, "huggingface"); 191 | //tested AI MODEL AND AI 192 | chatbot.selectAI("huggingface", model); 193 | 194 | 195 | server.on("/", HTTP_GET, []() { 196 | server.send_P(200, "text/html", index_html); 197 | }); 198 | 199 | server.on("/chat", HTTP_POST, []() { 200 | if (server.hasArg("message")) { 201 | String message = server.arg("message"); 202 | Serial.println("Received message: " + message); 203 | 204 | if (WiFi.status() == WL_CONNECTED) { 205 | String response = chatbot.getResponse(message); 206 | server.send(200, "text/plain", response); 207 | } else { 208 | server.send(503, "text/plain", "No Wi-Fi connection."); 209 | } 210 | } else { 211 | server.send(400, "text/plain", "Missing parameter: message"); 212 | } 213 | }); 214 | 215 | server.begin(); 216 | Serial.println("Web server started."); 217 | } 218 | 219 | void loop() { 220 | server.handleClient(); 221 | } -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=AIChatBot 2 | version=1.4.0 3 | author=bay_Eggex 4 | maintainer=bay_Eggex 5 | sentence=AI Chat Library for Arduino 6 | paragraph=Arduino library for integrating AI chat like OpenAIs ChatGPT, Hugging Face Transformers, and more. 7 | category=Communication 8 | url=https://github.com/bayeggex/Arduino-AI-Chat-Library 9 | architectures=* 10 | includes=AIChatbot.h 11 | -------------------------------------------------------------------------------- /src/AIChatbot.cpp: -------------------------------------------------------------------------------- 1 | #include "AIChatbot.h" 2 | 3 | AIChatbot::AIChatbot() 4 | : chatGPTApiKey(""), huggingFaceApiKey(""), selectedAI(""), selectedAIVersion("gpt-3.5-turbo") {} 5 | 6 | void AIChatbot::begin(long baudRate) { 7 | Serial.begin(baudRate); 8 | Serial.println(F("Serial communication started.")); 9 | } 10 | 11 | bool AIChatbot::connectWiFi(const char* ssid, const char* password, unsigned long timeoutMs) { 12 | #if defined(ESP8266) 13 | Serial.print("Connecting to WiFi: "); 14 | Serial.println(ssid); 15 | #else // ESP32 16 | Serial.printf(F("Connecting to WiFi: %s\n"), ssid); 17 | #endif 18 | 19 | WiFi.begin(ssid, password); 20 | 21 | unsigned long startAttemptTime = millis(); 22 | while (WiFi.status() != WL_CONNECTED && (millis() - startAttemptTime < timeoutMs)) { 23 | delay(500); 24 | Serial.print("."); 25 | } 26 | 27 | if (WiFi.status() == WL_CONNECTED) { 28 | #if defined(ESP8266) 29 | Serial.println(); 30 | Serial.println("WiFi Connected!"); 31 | Serial.print("IP Address: "); 32 | Serial.println(WiFi.localIP().toString()); 33 | #else // ESP32 34 | Serial.println(F("\nWiFi Connected!")); 35 | Serial.printf(F("IP Address: %s\n"), WiFi.localIP().toString().c_str()); 36 | #endif 37 | return true; 38 | } else { 39 | Serial.println(); 40 | Serial.println(F("WiFi Connection Failed.")); 41 | return false; 42 | } 43 | } 44 | 45 | 46 | bool AIChatbot::validateKeys() { 47 | if (selectedAI == "chatgpt" && chatGPTApiKey.length() == 0) { 48 | Serial.println(F("Error: ChatGPT API key is not set.")); 49 | return false; 50 | } else if (selectedAI == "huggingface" && huggingFaceApiKey.length() == 0) { 51 | Serial.println(F("Error: Hugging Face API key is not set.")); 52 | return false; 53 | } 54 | 55 | if (selectedAI.length() == 0) { 56 | Serial.println(F("Error: No AI selected.")); 57 | return false; 58 | } 59 | 60 | return true; 61 | } 62 | 63 | void AIChatbot::update() { 64 | if (Serial.available() > 0) { 65 | String incomingMessage = Serial.readStringUntil('\n'); 66 | incomingMessage.trim(); 67 | if (incomingMessage.length() > 0) { 68 | Serial.print(F("Received: ")); 69 | Serial.println(incomingMessage); 70 | 71 | String response = getResponse(incomingMessage); 72 | 73 | Serial.print(F("Response: ")); 74 | Serial.println(response); 75 | } 76 | } 77 | } 78 | 79 | void AIChatbot::setKey(const String& key, const String& aiName) { 80 | if (aiName == "chatgpt") { 81 | chatGPTApiKey = key; 82 | } else if (aiName == "huggingface") { 83 | huggingFaceApiKey = key; 84 | } 85 | } 86 | 87 | void AIChatbot::selectAI(const String& aiName, const String& aiVersion) { 88 | selectedAI = aiName; 89 | selectedAIVersion = (aiVersion != "null" && aiVersion != "none") ? aiVersion : "gpt-3.5-turbo"; 90 | 91 | if (selectedAI == "chatgpt" && (selectedAIVersion != "gpt-3.5-turbo" && selectedAIVersion != "gpt-4")) { 92 | Serial.println(F("Warning: Unsupported ChatGPT version. Defaulting to gpt-3.5-turbo.")); 93 | selectedAIVersion = "gpt-3.5-turbo"; 94 | } 95 | if (selectedAI == "huggingface" && selectedAIVersion.length() == 0) { 96 | Serial.println(F("Warning: Hugging Face version not set. Defaulting to HuggingFaceH4/zephyr-7b-beta")); 97 | selectedAIVersion = "HuggingFaceH4/zephyr-7b-beta"; //Tested with this model 2025-2-2 98 | } 99 | } 100 | 101 | String AIChatbot::getResponse(const String& message) { 102 | if (selectedAI == "chatgpt") { 103 | String rawResponse = sendToChatGPT(message); 104 | String cleanedResponse = sanitizeOutput(rawResponse); 105 | return cleanedResponse; 106 | } else if (selectedAI == "huggingface") { 107 | String rawResponse = sendToHuggingFace(message); 108 | String cleanedResponse = sanitizeOutput(rawResponse); 109 | return cleanedResponse; 110 | } else { 111 | return F("AI type not selected."); 112 | } 113 | } 114 | 115 | String AIChatbot::sanitizeInput(const String& input) { 116 | String sanitized = input; 117 | sanitized.replace("\\", "\\\\"); 118 | sanitized.replace("\"", "\\\""); 119 | sanitized.replace("\n", "\\n"); 120 | sanitized.replace("\r", "\\r"); 121 | sanitized.replace("\t", "\\t"); 122 | 123 | for (int i = 0; i < sanitized.length(); i++) { 124 | if (sanitized[i] < 32 && sanitized[i] != '\n' && sanitized[i] != '\r' && sanitized[i] != '\t') { 125 | sanitized.remove(i, 1); 126 | i--; 127 | } 128 | } 129 | 130 | return sanitized; 131 | } 132 | 133 | String AIChatbot::sanitizeOutput(const String& output) { 134 | String sanitized = output; 135 | 136 | sanitized.replace("\\n", "\n"); 137 | sanitized.replace("\\r", "\r"); 138 | sanitized.replace("\\t", "\t"); 139 | sanitized.replace("\\\"", "\""); 140 | sanitized.replace("\\\\", "\\"); 141 | 142 | sanitized.replace("[{", ""); 143 | sanitized.replace("}]", ""); 144 | sanitized.replace("{", ""); 145 | sanitized.replace("}", ""); 146 | sanitized.replace("\"generated_text\":", ""); 147 | sanitized.replace("\"", ""); 148 | 149 | sanitized.trim(); 150 | 151 | if (sanitized.length() > 0) { 152 | char lastChar = sanitized.charAt(sanitized.length() - 1); 153 | if (lastChar != '.' && lastChar != '?' && lastChar != '!') { 154 | sanitized += "."; 155 | } 156 | } 157 | 158 | return sanitized; 159 | } 160 | 161 | 162 | String AIChatbot::sendToChatGPT(const String& message) { 163 | if (chatGPTApiKey.length() == 0) { 164 | return "ChatGPT API key not set."; 165 | } 166 | 167 | String url = "https://api.openai.com/v1/chat/completions"; 168 | String sanitizedMessage = sanitizeInput(message); 169 | String payload = "{\"model\": \"" + selectedAIVersion + "\", \"messages\": [{\"role\": \"user\", \"content\": \"" + sanitizedMessage + "\"}]}"; 170 | 171 | return makeHttpRequest(url, payload, chatGPTApiKey); 172 | } 173 | 174 | String AIChatbot::sendToHuggingFace(const String& message) { 175 | if (huggingFaceApiKey.length() == 0) { 176 | return "Hugging Face API key not set."; 177 | } 178 | 179 | String sanitizedMessage = sanitizeInput(message); 180 | String url = "https://api-inference.huggingface.co/models/" + selectedAIVersion; 181 | String payload = "{\"inputs\": \"" + sanitizedMessage + "\"}"; 182 | 183 | return makeHttpRequest(url, payload, huggingFaceApiKey); 184 | } 185 | 186 | String AIChatbot::makeHttpRequest(const String& url, const String& payload, const String& apiKey) { 187 | HTTPClient http; 188 | WiFiClientSecure client; 189 | client.setInsecure(); 190 | 191 | if (!http.begin(client, url)) { 192 | Serial.println("Error: HTTP begin failed."); 193 | return "HTTP begin failed."; 194 | } 195 | 196 | http.setTimeout(10000); // Timeout = 10 seconds if not probably null response 197 | http.addHeader("Content-Type", "application/json"); 198 | http.addHeader("Accept", "application/json"); 199 | 200 | String authHeader = "Bearer " + apiKey; 201 | Serial.print("Using Authorization header: "); 202 | Serial.println(authHeader); 203 | http.addHeader("Authorization", authHeader); 204 | 205 | Serial.print("POST URL: "); 206 | Serial.println(url); 207 | Serial.print("Payload: "); 208 | Serial.println(payload); 209 | 210 | int retryCount = 0; 211 | int maxRetries = 2; 212 | int httpResponseCode = -1; 213 | String response; 214 | 215 | while (retryCount <= maxRetries) { 216 | httpResponseCode = http.POST(payload); 217 | if (httpResponseCode > 0) { 218 | break; 219 | } else { 220 | Serial.print("HTTP POST failed on try "); 221 | Serial.print(retryCount + 1); 222 | Serial.print(". Error: "); 223 | Serial.println(http.errorToString(httpResponseCode)); 224 | retryCount++; 225 | delay(1000); 226 | } 227 | } 228 | 229 | if (httpResponseCode > 0) { 230 | if (httpResponseCode >= 200 && httpResponseCode < 300) { 231 | response = http.getString(); 232 | Serial.printf("HTTP Response code: %d\nResponse body: %s\n", httpResponseCode, response.c_str()); 233 | } else { 234 | response = "HTTP POST returned code: " + String(httpResponseCode) + ". Response: " + http.getString(); 235 | Serial.println(response); 236 | } 237 | } else { 238 | response = "HTTP POST failed after retries. Error: " + String(http.errorToString(httpResponseCode).c_str()); 239 | Serial.println(response); 240 | } 241 | 242 | http.end(); 243 | return response; 244 | } -------------------------------------------------------------------------------- /src/AIChatbot.h: -------------------------------------------------------------------------------- 1 | #ifndef AI_CHATBOT_H 2 | #define AI_CHATBOT_H 3 | 4 | #include 5 | 6 | #if defined(ESP32) 7 | #include 8 | #include 9 | #include 10 | #define PLATFORM_NAME "ESP32" 11 | #elif defined(ESP8266) 12 | #include 13 | #include 14 | #define PLATFORM_NAME "ESP8266" 15 | #endif 16 | 17 | class AIChatbot { 18 | public: 19 | AIChatbot(); 20 | bool connectWiFi(const char* ssid, const char* password, unsigned long timeoutMs = 10000); 21 | bool validateKeys(); 22 | void begin(long baudRate); 23 | void update(); 24 | void setKey(const String& key, const String& aiName); 25 | void selectAI(const String& aiName, const String& aiVersion = "gpt-3.5-turbo"); 26 | String sanitizeInput(const String& input); 27 | String getResponse(const String& message); 28 | String sanitizeOutput(const String& output); 29 | 30 | private: 31 | String chatGPTApiKey; 32 | String huggingFaceApiKey; 33 | String selectedAI; 34 | String selectedAIVersion; 35 | String sendToChatGPT(const String& message); 36 | String sendToHuggingFace(const String& message); 37 | String makeHttpRequest(const String& url, const String& payload, const String& apiKey); 38 | }; 39 | 40 | #endif // AI_CHATBOT_H --------------------------------------------------------------------------------