Skip to content

Commit 2692241

Browse files
committed
Refactor AIChatbot examples and improve error handling in API requests
1 parent 17bc1f9 commit 2692241

File tree

11 files changed

+333
-190
lines changed

11 files changed

+333
-190
lines changed

Docs.md

Lines changed: 128 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,21 +29,19 @@ Before using the AI Chat Library, you need to set your API keys for the respecti
2929
AIChatbot chatbot;
3030

3131
void setup() {
32-
Serial.begin(115200);
32+
chatbot.begin(115200);
3333

3434
// Set API keys
3535
chatbot.setKey("YOUR_CHATGPT_API_KEY", "chatgpt");
3636
chatbot.setKey("YOUR_HUGGING_FACE_API_KEY", "huggingface");
3737

38-
// Begin WiFi connection
39-
WiFi.begin("SSID", "PASSWORD");
40-
while (WiFi.status() != WL_CONNECTED) {
41-
delay(1000);
42-
Serial.println("Connecting to WiFi...");
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
4342
}
44-
Serial.println("Connected to WiFi");
4543

46-
// Select AI and optionally specify version
44+
// Select AI service and optionally specify version
4745
chatbot.selectAI("chatgpt", "gpt-3.5-turbo");
4846
}
4947

@@ -55,6 +53,28 @@ void loop() {
5553

5654
### 📄Functions
5755

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+
5878
#### `selectAI(const String& aiName, const String& aiVersion = "gpt-3.5-turbo")`
5979

6080
- **Description**: Selects the AI service to use.
@@ -75,7 +95,7 @@ void loop() {
7595
```cpp
7696
chatbot.setKey("YOUR_CHATGPT_API_KEY", "chatgpt");
7797

78-
#### `send(const String& message)`
98+
#### `getResponse(const String& message)`
7999

80100
- **Description**: Sends a message to the selected AI service manually.
81101
- **Parameters**:
@@ -93,3 +113,102 @@ void loop() {
93113
void loop() {
94114
chatbot.update();
95115
}
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 <Arduino.h>
147+
148+
#if defined(ESP32)
149+
#include <WiFi.h>
150+
#include <WiFiClientSecure.h>
151+
#include <HTTPClient.h>
152+
#define PLATFORM_NAME "ESP32"
153+
#elif defined(ESP8266)
154+
#include <ESP8266WiFi.h>
155+
#include <ESP8266HTTPClient.h>
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!
Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,38 @@
1-
#include <AIChatbot.h>
1+
#include "AIChatbot.h" // Include the AIChatbot library
22

3-
AIChatbot chatbot;
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";
49

510
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");
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+
}
1023
}
1124

1225
void loop() {
1326
if (Serial.available() > 0) {
14-
String incomingMessage = Serial.readString();
15-
String message = "Translate this text to France: " + incomingMessage;
16-
String response = chatbot.getResponse(message);
17-
Serial.println("Translation: " + response);
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+
}
1836
}
1937
}
38+

examples/Datatest/ChatGpt.ino

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,40 @@
1-
#include <AIChatbot.h>
1+
#include "AIChatbot.h" // Include the AIChatbot library
22

3-
AIChatbot chatbot;
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";
49

510
void setup() {
6-
//changed to ESP32 115200 or ESP8266 9600
7-
Serial.begin(115200);
8-
9-
// Set ChatGPT API key
10-
chatbot.setKey("YOUR_CHATGPT_API_KEY", "chatgpt");
11+
Serial.begin(115200); // Initialize serial communication at 115200 baud rate
12+
chatbot.begin(115200); // Initialize chatbot communication at 115200 baud rate
1113

12-
// Begin WiFi connection
13-
chatbot.connectWiFi("YOUR_SSID", "YOUR_PASSWORD");
14-
15-
// Select AI and specify version
16-
chatbot.selectAI("chatgpt", "gpt-3.5-turbo");
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+
}
1723
}
1824

1925
void loop() {
20-
// Update and handle incoming messages
21-
chatbot.update();
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+
}
2240
}

examples/Datatest/Datatest.ino

Lines changed: 31 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,38 @@
1-
#include <AIChatbot.h>
1+
#include "AIChatbot.h" // Include the AIChatbot library
22

3-
AIChatbot chatbot;
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";
49

510
void setup() {
6-
Serial.begin(115200);
7-
8-
// Set API keys
9-
chatbot.setKey("YOUR_CHATGPT_API_KEY", "chatgpt");
11+
Serial.begin(115200); // Initialize serial communication at 115200 baud rate
12+
chatbot.begin(115200); // Initialize chatbot communication at 115200 baud rate
1013

11-
//Begin WiFi connection
12-
chatbot.connectWiFi("YOUR_SSID", "YOUR_PASSWORD");
13-
14-
// Select AI and optionally specify version
15-
chatbot.selectAI("chatgpt", "gpt-3.5-turbo");
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+
}
1622
}
1723

1824
void loop() {
19-
// Update and handle incoming messages
20-
chatbot.update();
21-
}
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+
}

examples/Datatest/HuggingFace.ino

Lines changed: 34 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,41 @@
1-
#include <AIChatbot.h>
1+
#include "AIChatbot.h" // Include the AIChatbot library
22

3-
AIChatbot chatbot;
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";
411

512
void setup() {
6-
//changed to ESP32 115200 or ESP8266 9600
7-
Serial.begin(115200);
8-
9-
// Set API keys
10-
chatbot.setKey("HUGGING FACE API KEY", "huggingface");
13+
Serial.begin(115200); // Initialize serial communication at 115200 baud rate
14+
chatbot.begin(115200); // Initialize the chatbot with the same baud rate
1115

12-
//Begin WiFi connection
13-
chatbot.connectWiFi("YOUR_SSID", "YOUR_PASSWORD");
14-
15-
// Select AI and optionally specify version
16-
// Tested and used google/flan-t5-small
17-
chatbot.selectAI("huggingface", "google/flan-t5-small");
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+
}
1825
}
1926

2027
void loop() {
21-
// Update and handle incoming messages
22-
chatbot.update();
23-
}
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+
}

0 commit comments

Comments
 (0)