Arcypojeb commited on
Commit
d4d87c0
1 Parent(s): f390727

Upload 6 files

Browse files
pages/Docsbotport.html ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>HuggingFace Chat Interface</title>
5
+ <meta charset="UTF-8">
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
+ <style>
8
+ #chatbox {
9
+ height: 300px;
10
+ width: 1080px;
11
+ border: 1px solid black;
12
+ overflow: auto;
13
+ padding: 10px;
14
+ }
15
+ #inputbox {
16
+ height: 50px;
17
+ width: 1080px;
18
+ border: 1px solid black;
19
+ padding: 10px;
20
+ }
21
+ .led {
22
+ height: 10px;
23
+ width: 10px;
24
+ border-radius: 50%;
25
+ display: inline-block;
26
+ margin-right: 5px;
27
+ }
28
+ .led-on {
29
+ background-color: green;
30
+ }
31
+ .led-off {
32
+ background-color: red;
33
+ }
34
+ </style>
35
+ </head>
36
+ <body>
37
+ <h1>DocsBot Agents Interface</h1>
38
+ <div id="status">
39
+ <span>Module Running:</span>
40
+ <span class="led led-off" id="module-led"></span>
41
+ <br>
42
+ <span>Chathub Connected:</span>
43
+ <span class="led led-off" id="chathub-led"></span>
44
+ <br>
45
+ <div id="status-msg"></div>
46
+ </div>
47
+ <input type="text" id="port" placeholder="websocket port">
48
+ <button id="connector">CONNECT TO SERVER</button>
49
+ <input type="text" id="inputbox" placeholder="Type your message here...">
50
+ <button id="sendbtn">Send</button>
51
+ <div id="chatbox"></div>
52
+ <br><br>
53
+ <button id="clearbtn">New Chat (or Clear)</button>
54
+ <button id="testbtn">Test Server</button>
55
+ <p id="result"></p>
56
+ <script>
57
+ const mled = document.getElementById("module-led");
58
+ const sled = document.getElementById("chathub-led");
59
+ const testbtn = document.getElementById("testbtn");
60
+ const result = document.getElementById("result");
61
+ const chatbox = document.getElementById("chatbox");
62
+ const port = document.getElementById("port");
63
+ const connector = document.getElementById("connector");
64
+ const inputbox = document.getElementById("inputbox");
65
+ const sendbtn = document.getElementById("sendbtn");
66
+ const clearbtn = document.getElementById("clearbtn");
67
+
68
+ let ws; // WebSocket object
69
+
70
+ // Add a click event listener to the 'test server' button
71
+ testbtn.addEventListener("click", async () => {
72
+ try {
73
+ const response = await fetch("http://127.0.0.1:5000");
74
+
75
+ if (response.ok) {
76
+ result.textContent = "Port 5000 is free";
77
+ } else {
78
+ result.textContent = "Port 5000 is occupied";
79
+ }
80
+ } catch (error) {
81
+ result.textContent = "Cannot connect to port 5000";
82
+ }
83
+ });
84
+
85
+ // Send a question to the chatbot and display the response
86
+ async function askQuestion(question) {
87
+ try {
88
+ const response = await fetch('https://api.docsbot.ai/teams/ZrbLG98bbxZ9EFqiPvyl/bots/oFFiXuQsakcqyEdpLvCB/chat', {
89
+ method: 'POST',
90
+ headers: {
91
+ 'Content-Type': 'application/json'
92
+ },
93
+ body: JSON.stringify({
94
+ question: question,
95
+ full_source: false
96
+ })
97
+ });
98
+ const responseJson = await response.json();
99
+ const outputText = responseJson.answer;
100
+
101
+ // Display the conversation in the chatbox
102
+ chatbox.innerHTML += `<p><strong>You:</strong> ${question}</p>`;
103
+ chatbox.innerHTML += `<p><strong>DocsBot:</strong> ${outputText}</p>`;
104
+ chatbox.scrollTop = chatbox.scrollHeight;
105
+ // Check if WebSocket connection is open before sending message to the server
106
+ if (ws.readyState === WebSocket.OPEN) {
107
+ const message = JSON.stringify({ text: outputText });
108
+ ws.send(message);
109
+ }
110
+ } catch (error) {
111
+ console.error(error);
112
+ }
113
+ }
114
+
115
+ // Use the received text as the question input for the chatbot and display the conversation
116
+ function handleServerMessage(event) {
117
+ // Extract the received text message from the event object
118
+ const receivedText = event.data;
119
+ // Ask the chatbot the received question
120
+ askQuestion(receivedText);
121
+ }
122
+ // Add a click event listener to the 'connect to server' button
123
+ connector.addEventListener("click", async () => {
124
+ try {
125
+ const websocketPort = port.value;
126
+ const localPort = `ws://localhost:${websocketPort}`;
127
+ // Establish a WebSocket connection to the server
128
+ ws = new WebSocket(localPort);
129
+
130
+ // Change the LED status to 'on'
131
+ sled.classList.remove("led-off");
132
+ sled.classList.add("led-on");
133
+
134
+ // Display a success message
135
+ const statusMsg = document.getElementById("status-msg");
136
+ statusMsg.textContent = "Connected successfully to port:", websocketPort;
137
+
138
+ // Listen for incoming messages from the server
139
+ ws.onmessage = handleServerMessage;
140
+
141
+ // Listen for the WebSocket connection to close
142
+ ws.onclose = () => {
143
+ // Change the LED status to 'off'
144
+ sled.classList.remove("led-on");
145
+ sled.classList.add("led-off");
146
+
147
+ // Display a disconnected message
148
+ const statusMsg = document.getElementById("status-msg");
149
+ statusMsg.textContent = "Disconnected from server.";
150
+ };
151
+ } catch (error) {
152
+ console.error(error);
153
+ }
154
+ });
155
+
156
+ // Add a click event listener to the 'send' button
157
+ sendbtn.addEventListener("click", async () => {
158
+ const inputText = inputbox.value;
159
+ chatbox.innerHTML += `<p><strong>User:</strong> ${inputText}</p>`;
160
+ chatbox.scrollTop = chatbox.scrollHeight;
161
+ if (inputText.trim() !== "") {
162
+ // Send message to the server
163
+ const message = JSON.stringify({ text: 'userB: ' + inputText });
164
+ askQuestion(message);
165
+ ws.send(message);
166
+ }
167
+ });
168
+
169
+ // Listen for messages from the server
170
+ ws.onmessage = (event) => {
171
+ const receivedMessage = event.data;
172
+ displayMessage(receivedMessage, "server");
173
+ };
174
+ </script>
175
+ </body>
176
+ </html>
pages/NeuralGPT.py ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import websockets
3
+ import asyncio
4
+ import sqlite3
5
+ import json
6
+ import g4f
7
+ import streamlit as st
8
+ import fireworks.client
9
+ import streamlit.components.v1 as components
10
+ from PyCharacterAI import Client
11
+ from websockets.sync.client import connect
12
+
13
+ st.set_page_config(
14
+ page_title='OCR Comparator', layout ="wide",
15
+ initial_sidebar_state="expanded",
16
+ )
17
+
18
+ servers = {}
19
+ inputs = []
20
+ outputs = []
21
+ used_ports = []
22
+ server_ports = []
23
+ client_ports = []
24
+
25
+ # Set up the SQLite database
26
+ db = sqlite3.connect('chat-hub.db')
27
+ cursor = db.cursor()
28
+ cursor.execute('CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, sender TEXT, message TEXT, timestamp TEXT)')
29
+ db.commit()
30
+
31
+ client = Client()
32
+
33
+ system_instruction = "You are now integrated with a local websocket server in a project of hierarchical cooperative multi-agent framework called NeuralGPT. Your main job is to coordinate simultaneous work of multiple LLMs connected to you as clients. Each LLM has a model (API) specific ID to help you recognize different clients in a continuous chat thread (template: <NAME>-agent and/or <NAME>-client). Your chat memory module is integrated with a local SQL database with chat history. Your primary objective is to maintain the logical and chronological order while answering incoming messages and to send your answers to the correct clients to maintain synchronization of the question->answer logic. However, please note that you may choose to ignore or not respond to repeating inputs from specific clients as needed to prevent unnecessary traffic."
34
+
35
+ async def askQuestion(question):
36
+ try:
37
+ db = sqlite3.connect('chat-hub.db')
38
+ cursor = db.cursor()
39
+ cursor.execute("SELECT * FROM messages ORDER BY timestamp DESC LIMIT 30")
40
+ messages = cursor.fetchall()
41
+ messages.reverse()
42
+
43
+ past_user_inputs = []
44
+ generated_responses = []
45
+
46
+ for message in messages:
47
+ if message[1] == 'client':
48
+ past_user_inputs.append(message[2])
49
+ else:
50
+ generated_responses.append(message[2])
51
+
52
+ response = await g4f.ChatCompletion.create_async(
53
+ model=g4f.models.gpt_4,
54
+ provider=g4f.Provider.Bing,
55
+ messages=[
56
+ {"role": "system", "content": system_instruction},
57
+ *[{"role": "user", "content": message} for message in past_user_inputs],
58
+ *[{"role": "assistant", "content": message} for message in generated_responses],
59
+ {"role": "user", "content": question}
60
+ ])
61
+
62
+ print(response)
63
+ return response
64
+
65
+ except Exception as e:
66
+ print(e)
67
+
68
+ async def chatCompletion(question):
69
+ fireworks.client.api_key = st.session_state.api_key
70
+ try:
71
+ # Connect to the database and get the last 30 messages
72
+ db = sqlite3.connect('chat-hub.db')
73
+ cursor = db.cursor()
74
+ cursor.execute("SELECT * FROM messages ORDER BY timestamp DESC LIMIT 10")
75
+ messages = cursor.fetchall()
76
+ messages.reverse()
77
+
78
+ # Extract user inputs and generated responses from the messages
79
+ past_user_inputs = []
80
+ generated_responses = []
81
+
82
+ for message in messages:
83
+ if message[1] == 'client':
84
+ past_user_inputs.append(message[2])
85
+ else:
86
+ generated_responses.append(message[2])
87
+
88
+ # Prepare data to send to the chatgpt-api.shn.hk
89
+ response = fireworks.client.ChatCompletion.create(
90
+ model="accounts/fireworks/models/llama-v2-7b-chat",
91
+ messages=[
92
+ {"role": "system", "content": system_instruction},
93
+ *[{"role": "user", "content": input} for input in past_user_inputs],
94
+ *[{"role": "assistant", "content": response} for response in generated_responses],
95
+ {"role": "user", "content": question}
96
+ ],
97
+ stream=False,
98
+ n=1,
99
+ max_tokens=2500,
100
+ temperature=0.5,
101
+ top_p=0.7,
102
+ )
103
+
104
+ answer = response.choices[0].message.content
105
+ print(answer)
106
+ return str(answer)
107
+
108
+ except Exception as error:
109
+ print("Error while fetching or processing the response:", error)
110
+ return "Error: Unable to generate a response."
111
+
112
+
113
+ async def handleUser(userInput):
114
+ print(f"User B: {userInput}")
115
+ timestamp = datetime.datetime.now().isoformat()
116
+ sender = 'client'
117
+ db = sqlite3.connect('chat-hub.db')
118
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
119
+ (sender, userInput, timestamp))
120
+ db.commit()
121
+ try:
122
+ response2 = await chatCompletion(userInput)
123
+ print(f"Llama2: {response2}")
124
+ serverSender = 'server'
125
+ timestamp = datetime.datetime.now().isoformat()
126
+ db = sqlite3.connect('chat-hub.db')
127
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
128
+ (serverSender, response2, timestamp))
129
+ db.commit()
130
+ return response2
131
+
132
+ except Exception as e:
133
+ print(f"Error: {e}")
134
+
135
+ async def handleUser2(userInput):
136
+ print(f"User B: {userInput}")
137
+ timestamp = datetime.datetime.now().isoformat()
138
+ sender = 'client'
139
+ db = sqlite3.connect('chat-hub.db')
140
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
141
+ (sender, userInput, timestamp))
142
+ db.commit()
143
+ try:
144
+ response3 = await askQuestion(userInput)
145
+ print(f"GPT4Free: {response3}")
146
+ serverSender = 'server'
147
+ timestamp = datetime.datetime.now().isoformat()
148
+ db = sqlite3.connect('chat-hub.db')
149
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
150
+ (serverSender, response3, timestamp))
151
+ db.commit()
152
+ return response3
153
+
154
+ except Exception as e:
155
+ print(f"Error: {e}")
156
+
157
+ async def handleServer(ws):
158
+ instruction = "Hello! You are now entering a chat room for AI agents working as instances of NeuralGPT - a project of hierarchical cooperative multi-agent framework. Keep in mind that you are speaking with another chatbot. Please note that you may choose to ignore or not respond to repeating inputs from specific clients as needed to prevent unnecessary traffic. If you're unsure what you should do, ask the instance of higher hierarchy (server)"
159
+ print('New connection')
160
+ await ws.send(instruction)
161
+ while True:
162
+ message = await ws.recv()
163
+ print(f'Received message: {message}')
164
+ inputMsg = st.chat_message("assistant")
165
+ inputMsg.markdown(message)
166
+ timestamp = datetime.datetime.now().isoformat()
167
+ sender = 'client'
168
+ db = sqlite3.connect('chat-hub.db')
169
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
170
+ (sender, message, timestamp))
171
+ db.commit()
172
+ try:
173
+ response = await chatCompletion(message)
174
+ serverResponse = f"server: {response}"
175
+ outputMsg = st.chat_message("ai")
176
+ print(serverResponse)
177
+ outputMsg.markdown(response)
178
+ timestamp = datetime.datetime.now().isoformat()
179
+ serverSender = 'server'
180
+ db = sqlite3.connect('chat-hub.db')
181
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
182
+ (serverSender, serverResponse, timestamp))
183
+ db.commit()
184
+ # Append the server response to the server_responses list
185
+ await ws.send(serverResponse)
186
+ continue
187
+
188
+ except websockets.exceptions.ConnectionClosedError as e:
189
+ print(f"Connection closed: {e}")
190
+
191
+ except Exception as e:
192
+ print(f"Error: {e}")
193
+
194
+ async def handleServer1(ws):
195
+ instruction = "Hello! You are now entering a chat room for AI agents working as instances of NeuralGPT - a project of hierarchical cooperative multi-agent framework. Keep in mind that you are speaking with another chatbot. Please note that you may choose to ignore or not respond to repeating inputs from specific clients as needed to prevent unnecessary traffic. If you're unsure what you should do, ask the instance of higher hierarchy (server)"
196
+ print('New connection')
197
+ await ws.send(instruction)
198
+ while True:
199
+ message = await ws.recv()
200
+ print(f'Received message: {message}')
201
+ inputMsg1 = st.chat_message("assistant")
202
+ inputMsg1.markdown(message)
203
+ timestamp = datetime.datetime.now().isoformat()
204
+ sender = 'client'
205
+ db = sqlite3.connect('chat-hub.db')
206
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
207
+ (sender, message, timestamp))
208
+ db.commit()
209
+ try:
210
+ response = await askQuestion(message)
211
+ serverResponse = f"server: {response}"
212
+ outputMsg1 = st.chat_message("ai")
213
+ print(serverResponse)
214
+ outputMsg1.markdown(response)
215
+ timestamp = datetime.datetime.now().isoformat()
216
+ serverSender = 'server'
217
+ db = sqlite3.connect('chat-hub.db')
218
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
219
+ (serverSender, serverResponse, timestamp))
220
+ db.commit()
221
+ # Append the server response to the server_responses list
222
+ await ws.send(serverResponse)
223
+ continue
224
+
225
+ except websockets.exceptions.ConnectionClosedError as e:
226
+ print(f"Connection closed: {e}")
227
+
228
+ except Exception as e:
229
+ print(f"Error: {e}")
230
+
231
+ async def handleServer2(ws, chat):
232
+ instruction = "Hello! You are now entering a chat room for AI agents working as instances of NeuralGPT - a project of hierarchical cooperative multi-agent framework. Keep in mind that you are speaking with another chatbot. Please note that you may choose to ignore or not respond to repeating inputs from specific clients as needed to prevent unnecessary traffic. If you're unsure what you should do, ask the instance of higher hierarchy (server)"
233
+ print('New connection')
234
+ await ws.send(instruction)
235
+ while True:
236
+ message = await ws.recv()
237
+ print(f'Received message: {message}')
238
+ inputMsg2 = st.chat_message("assistant")
239
+ inputMsg2.markdown(message)
240
+ timestamp = datetime.datetime.now().isoformat()
241
+ sender = 'client'
242
+ db = sqlite3.connect('chat-hub.db')
243
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
244
+ (sender, message, timestamp))
245
+ db.commit()
246
+ try:
247
+ response = await chat.send_message(message)
248
+ serverResponse = f"server: {response.text}"
249
+ outputMsg2 = st.chat_message("ai")
250
+ print(serverResponse)
251
+ outputMsg2.markdown(response.text)
252
+ timestamp = datetime.datetime.now().isoformat()
253
+ serverSender = 'server'
254
+ db = sqlite3.connect('chat-hub.db')
255
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
256
+ (serverSender, response.text, timestamp))
257
+ db.commit()
258
+ # Append the server response to the server_responses list
259
+ await ws.send(response.text)
260
+ continue
261
+
262
+ except websockets.exceptions.ConnectionClosedError as e:
263
+ print(f"Connection closed: {e}")
264
+
265
+ except Exception as e:
266
+ print(f"Error: {e}")
267
+
268
+ async def askCharacter(token, characterID, question):
269
+ await client.authenticate_with_token(token)
270
+ chat = await client.create_or_continue_chat(characterID)
271
+ print(f"User B: {question}")
272
+ timestamp = datetime.datetime.now().isoformat()
273
+ sender = 'client'
274
+ db = sqlite3.connect('chat-hub.db')
275
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
276
+ (sender, question, timestamp))
277
+ db.commit()
278
+ try:
279
+ answer = await chat.send_message(question)
280
+ print(f"{answer.src_character_name}: {answer.text}")
281
+ timestamp = datetime.datetime.now().isoformat()
282
+ serverSender = 'server'
283
+ db = sqlite3.connect('chat-hub.db')
284
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
285
+ (serverSender, answer, timestamp))
286
+ db.commit()
287
+ return answer.text
288
+
289
+ except Exception as e:
290
+ print(f"Error: {e}")
291
+
292
+ # Start the WebSocket server
293
+ async def start_websockets(fireworksAPI, websocketPort):
294
+ global server
295
+ fireworks.client.api_key = fireworksAPI
296
+ async with websockets.serve(handleServer, 'localhost', websocketPort) as server:
297
+ print(f"Starting WebSocket server on port {websocketPort}...")
298
+ servers[websocketPort] = server
299
+ return server
300
+
301
+ async def start_websockets1(websocketPort):
302
+ global server
303
+ server = await websockets.serve(handleServer1, 'localhost', websocketPort)
304
+ print(f"Starting WebSocket server on port {websocketPort}...")
305
+ return server
306
+
307
+ async def start_websockets2(token, characterID, websocketPort):
308
+ global server
309
+ await client.authenticate_with_token(token)
310
+ chat = await client.create_or_continue_chat(characterID)
311
+ server = await websockets.serve(handleServer2, 'localhost', websocketPort)
312
+ print(f"Starting WebSocket server on port {websocketPort}...")
313
+ return chat, server
314
+
315
+ # Stop the WebSocket server
316
+ async def stop_websockets():
317
+ global server
318
+ if server:
319
+ # Close all connections gracefully
320
+ server.close()
321
+ # Wait for the server to close
322
+ server.wait_closed()
323
+ print("Stopping WebSocket server...")
324
+ else:
325
+ print("WebSocket server is not running.")
326
+
327
+ # Stop the WebSocket client
328
+ async def stop_client():
329
+ global ws
330
+ # Close the connection with the server
331
+ ws.close()
332
+ print("Stopping WebSocket client...")
333
+
334
+ async def main():
335
+ if "server" not in st.session_state:
336
+ st.session_state.server = None
337
+ if "servers" not in st.session_state:
338
+ st.session_state.servers = None
339
+ if "client" not in st.session_state:
340
+ st.session_state.client = None
341
+ if "server_Ports" not in st.session_state:
342
+ st.session_state.server_Ports = None
343
+ if "client_Ports" not in st.session_state:
344
+ st.session_state.client_Ports = None
345
+ if "api_key" not in st.session_state:
346
+ st.session_state.api_key = None
347
+ if "userID" not in st.session_state:
348
+ st.session_state.user_ID = None
349
+
350
+ st.sidebar.text("Server ports:")
351
+ serverPorts = st.sidebar.container(border=True)
352
+ serverPorts.markdown(st.session_state.server_Ports)
353
+ st.sidebar.text("Client ports")
354
+ clientPorts = st.sidebar.container(border=True)
355
+ clientPorts.markdown(st.session_state.client_Ports)
356
+ user_id = st.sidebar.container(border=True)
357
+ user_id.markdown(st.session_state.user_ID)
358
+
359
+ c1, c2 = st.columns(2)
360
+
361
+ with c1:
362
+ serverPorts1 = st.container(border=True)
363
+ serverPorts1.markdown(st.session_state.server_Ports)
364
+
365
+ with c2:
366
+ clientPorts1 = st.container(border=True)
367
+ clientPorts1.markdown(st.session_state.client_Ports)
368
+
369
+ tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs(["Fireworks", "GPT4Free", "Character.ai", "Chaindesk agent", "Docsbot Wordpress-agent", "Flowise client"])
370
+
371
+ with tab1:
372
+ st.header("Fireworks Llama2-7B")
373
+ fireworksAPI = st.text_input("Fireworks API key")
374
+ row1_col1, row1_col2 = st.columns(2)
375
+ userInputt = st.text_input("User input")
376
+
377
+ with row1_col1:
378
+ websocket_Port = st.number_input("Server port", 1000)
379
+ startServer = st.button('Start websocket server 1')
380
+ srvr_ports = st.container(border=True)
381
+ srvr_ports.markdown(st.session_state.server_Ports)
382
+
383
+ with row1_col2:
384
+ client_Port = st.number_input("Client port", 1000)
385
+ startClient = st.button('Connect client to server 1')
386
+ cli_ports = st.container(border=True)
387
+ cli_ports.markdown(st.session_state.client_Ports)
388
+
389
+ if userInputt:
390
+ print(f"User B: {userInputt}")
391
+ fireworks.client.api_key = fireworksAPI
392
+ st.session_state.api_key = fireworks.client.api_key
393
+ user_input = st.chat_message("human")
394
+ user_input.markdown(userInputt)
395
+ response1 = await handleUser(userInputt)
396
+ print(response1)
397
+ outputMsg = st.chat_message("ai")
398
+ outputMsg.markdown(response1)
399
+
400
+ if startServer:
401
+ fireworks.client.api_key = fireworksAPI
402
+ st.session_state.api_key = fireworks.client.api_key
403
+ server_ports.append(websocket_Port)
404
+ st.session_state.server_Ports = server_ports
405
+ serverPorts.markdown(st.session_state.server_Ports)
406
+ serverPorts1.markdown(st.session_state.server_Ports)
407
+ srvr_ports.markdown(st.session_state.server_Ports)
408
+ try:
409
+ server = await websockets.serve(handleServer, 'localhost', websocket_Port)
410
+ print(f"Launching server at port: {websocket_Port}")
411
+ while True:
412
+ await server.wait_closed()
413
+ except Exception as e:
414
+ print(f"Error: {e}")
415
+
416
+
417
+ if startClient:
418
+ client_ports.append(client_Port)
419
+ clientPorts.markdown(client_ports)
420
+ clientPorts1.markdown(client_ports)
421
+ cli_ports.markdown(client_ports)
422
+ await client.authenticate_with_token(fireworksAPI)
423
+ uri = f'ws://localhost:{client_Port}'
424
+ async with websockets.connect(uri) as websocket:
425
+ while True:
426
+ print(f"Connecting to server at port: {client_Port}...")
427
+ # Listen for messages from the server
428
+ input_message = await websocket.recv()
429
+ print(f"Server: {input_message}")
430
+ input_Msg = st.chat_message("assistant")
431
+ input_Msg.markdown(input_message)
432
+ try:
433
+ response = await chatCompletion(input_message)
434
+ res1 = f"Client: {response}"
435
+ output_Msg = st.chat_message("ai")
436
+ output_Msg.markdown(res1)
437
+ await websocket.send(json.dumps(res1))
438
+
439
+ except websockets.ConnectionClosed:
440
+ print("client disconnected")
441
+ continue
442
+
443
+ except Exception as e:
444
+ print(f"Error: {e}")
445
+ continue
446
+
447
+ with tab2:
448
+ st.header("GPT4Free Client")
449
+ userInput1 = st.text_input("User input 1")
450
+ col1, col2 = st.columns(2)
451
+
452
+ with col1:
453
+ websocketPort1 = st.number_input("G4F Server port", 1000)
454
+ startServer1 = st.button('Start websocket server 2')
455
+ srvr_ports1 = st.container(border=True)
456
+ srvr_ports1.text("Websocket server ports")
457
+
458
+ with col2:
459
+ clientPort1 = st.number_input("G4F Client port", 1000)
460
+ startClient1 = st.button('Connect client to server 2')
461
+ cli_ports1 = st.container(border=True)
462
+ cli_ports1.text("Websocket client ports")
463
+
464
+ if userInput1:
465
+ user_input1 = st.chat_message("human")
466
+ user_input1.markdown(userInput1)
467
+ response = await handleUser2(userInput1)
468
+ outputMsg1 = st.chat_message("ai")
469
+ outputMsg1.markdown(response)
470
+
471
+ if startServer1:
472
+ server_ports.append(websocketPort1)
473
+ serverPorts.markdown(server_ports)
474
+ serverPorts1.markdown(server_ports)
475
+ srvr_ports1.markdown(server_ports)
476
+ try:
477
+ server1 = await websockets.serve(handleServer1, 'localhost', websocketPort1)
478
+ print(f"Launching server at port: {websocketPort1}")
479
+ while True:
480
+ await server1.wait_closed()
481
+
482
+ except Exception as e:
483
+ print(f"Error: {e}")
484
+
485
+
486
+ if startClient1:
487
+ client_ports.append(clientPort1)
488
+ clientPorts.markdown(client_ports)
489
+ clientPorts1.markdown(client_ports)
490
+ cli_ports1.markdown(client_ports)
491
+ uri1 = f'ws://localhost:{clientPort1}'
492
+ async with websockets.connect(uri1) as websocket:
493
+ while True:
494
+ print(f"Connecting to server at port: {clientPort1}...")
495
+ # Listen for messages from the server
496
+ input_message1 = await websocket.recv()
497
+ print(f"Server: {input_message1}")
498
+ input_Msg1 = st.chat_message("assistant")
499
+ input_Msg1.markdown(input_message1)
500
+ try:
501
+ response1 = await askQuestion(input_message1)
502
+ res = f"Client: {response1}"
503
+ print(res)
504
+ output_Msg1 = st.chat_message("ai")
505
+ output_Msg1.markdown(res)
506
+ await websocket.send(json.dumps(res))
507
+
508
+ except websockets.ConnectionClosed:
509
+ print("client disconnected")
510
+ continue
511
+
512
+ except Exception as e:
513
+ print(f"Error: {e}")
514
+ continue
515
+
516
+ with tab3:
517
+ st.header("Character AI Client")
518
+ token = st.text_input("Character AI Token")
519
+ userID = st.container(border=True)
520
+ characterID = st.text_input("Character ID")
521
+ co1, co2 = st.columns(2)
522
+ userInput2 = st.text_input("User input 2")
523
+
524
+ with co1:
525
+ websocketPort2 = st.number_input("Character AI Server port", 1000)
526
+ startServer2 = st.button('Start websocket server 3')
527
+ srvr_ports2 = st.container(border=True)
528
+
529
+ with co2:
530
+ clientPort2 = st.number_input("Character AI Client port", 1000)
531
+ startClient2 = st.button('Connect client to server 3')
532
+ cli_ports2 = st.container(border=True)
533
+ cli_ports2.text("Websocket client ports")
534
+
535
+ if startServer2:
536
+ server_ports.append(websocketPort2)
537
+ serverPorts.markdown(server_ports)
538
+ serverPorts1.markdown(server_ports)
539
+ srvr_ports2.markdown(server_ports)
540
+ await client.authenticate_with_token(token)
541
+ username = (await client.fetch_user())['user']['username']
542
+ user_id.markdown(username)
543
+ userID.markdown(username)
544
+ try:
545
+ server2 = await websockets.serve(handleServer2, 'localhost', websocketPort2)
546
+ print(f"Launching server at port: {websocketPort2}")
547
+ while True:
548
+ await server2.wait_closed()
549
+
550
+ except Exception as e:
551
+ print(f"Error: {e}")
552
+
553
+
554
+ if startClient2:
555
+ client_ports.append(clientPort2)
556
+ clientPorts.markdown(client_ports)
557
+ clientPorts1.markdown(client_ports)
558
+ cli_ports2.markdown(client_ports)
559
+ uri2 = f'ws://localhost:{clientPort2}'
560
+ await client.authenticate_with_token(token)
561
+ username = (await client.fetch_user())['user']['username']
562
+ user_id.markdown(username)
563
+ userID.markdown(username)
564
+ chat = await client.create_or_continue_chat(characterID)
565
+ print(f"Connecting to server at port: {clientPort2}...")
566
+ async with websockets.connect(uri2) as websocket:
567
+ while True:
568
+ # Listen for messages from the server
569
+ input_message2 = await websocket.recv()
570
+ print(f"Server: {input_message2}")
571
+ input_Msg2 = st.chat_message("assistant")
572
+ input_Msg2.markdown(input_message2)
573
+ try:
574
+ response2 = await chat.send_message(input_message2)
575
+ print(f"Client: {response2.text}")
576
+ output_Msg2 = st.chat_message("ai")
577
+ output_Msg2.markdown(response2.text)
578
+ await websocket.send(json.dumps(response2.text))
579
+
580
+ except websockets.ConnectionClosed:
581
+ print("client disconnected")
582
+ continue
583
+
584
+ except Exception as e:
585
+ print(f"Error: {e}")
586
+ continue
587
+
588
+ if userInput2:
589
+ user_input2 = st.chat_message("human")
590
+ user_input2.markdown(userInput2)
591
+ await client.authenticate_with_token(token)
592
+ username = (await client.fetch_user())['user']['username']
593
+ user_id.markdown(username)
594
+ userID.markdown(username)
595
+ try:
596
+ chat = await client.create_or_continue_chat(characterID)
597
+ answer = await chat.send_message(userInput2)
598
+ print(f"{answer.src_character_name}: {answer.text}")
599
+ outputMsg2 = st.chat_message("ai")
600
+ outputMsg2.markdown(answer.text)
601
+
602
+ except Exception as e:
603
+ print(f"Error: {e}")
604
+
605
+ with tab4:
606
+ HtmlFile = open("comp.html", 'r', encoding='utf-8')
607
+ source_code = HtmlFile.read()
608
+ components.html(source_code)
609
+
610
+ with tab5:
611
+ HtmlFile = open("Docsbotport.html", 'r', encoding='utf-8')
612
+ source_code = HtmlFile.read()
613
+ components.html(source_code)
614
+
615
+ with tab6:
616
+ HtmlFile = open("flowise.html", 'r', encoding='utf-8')
617
+ source_code = HtmlFile.read()
618
+ components.html(source_code)
619
+
620
+ asyncio.run(main())
pages/chat-hub.db ADDED
Binary file (12.3 kB). View file
 
pages/comp.html ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>HuggingFace Chat Interface</title>
5
+ <meta charset="UTF-8">
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
+ <style>
8
+ #chatbox {
9
+ height: 300px;
10
+ width: 1080px;
11
+ border: 1px solid black;
12
+ overflow: auto;
13
+ padding: 10px;
14
+ }
15
+ #inputbox {
16
+ height: 20px;
17
+ width: 1080px;
18
+ border: 1px solid black;
19
+ padding: 10px;
20
+ }
21
+ .led {
22
+ height: 10px;
23
+ width: 10px;
24
+ border-radius: 50%;
25
+ display: inline-block;
26
+ margin-right: 5px;
27
+ }
28
+ .led-on {
29
+ background-color: green;
30
+ }
31
+ .led-off {
32
+ background-color: red;
33
+ }
34
+ </style>
35
+ </head>
36
+ <body>
37
+ <h1>Chaindesk Chat Interface</h1>
38
+ <div id="status">
39
+ <span>Module Running:</span>
40
+ <span class="led led-off" id="module-led"></span>
41
+ <br>
42
+ <span>Chathub Connected:</span>
43
+ <span class="led led-off" id="chathub-led"></span>
44
+ <br>
45
+ <div id="status-msg"></div>
46
+ </div>
47
+ <input type="text" id="port" placeholder="websocket port">
48
+ <input type="text" id="flowise" placeholder="paste your agent id here">
49
+ <button id="connector">CONNECT TO SERVER</button>
50
+ <input type="text" id="inputbox" placeholder="Type your message here...">
51
+ <button id="sendbtn">Send</button>
52
+ <div id="chatbox"></div>
53
+ <br><br>
54
+ <button id="clearbtn">New Chat (or Clear)</button>
55
+ <button id="testbtn">Test Server</button>
56
+ <p id="result"></p>
57
+ <script>
58
+ const mled = document.getElementById("module-led");
59
+ const sled = document.getElementById("chathub-led");
60
+ const testbtn = document.getElementById("testbtn");
61
+ const result = document.getElementById("result");
62
+ const chatbox = document.getElementById("chatbox");
63
+ const port = document.getElementById("port");
64
+ const connector = document.getElementById("connector");
65
+ const inputbox = document.getElementById("inputbox");
66
+ const sendbtn = document.getElementById("sendbtn");
67
+ const clearbtn = document.getElementById("clearbtn");
68
+
69
+ let ws; // WebSocket object
70
+
71
+ // Add a click event listener to the 'test server' button
72
+ testbtn.addEventListener("click", async () => {
73
+ try {
74
+ const response = await fetch("http://127.0.0.1:1111");
75
+
76
+ if (response.ok) {
77
+ result.textContent = "Port 1111 is free";
78
+ } else {
79
+ result.textContent = "Port 1111 is occupied";
80
+ }
81
+ } catch (error) {
82
+ result.textContent = "Cannot connect to port 1111";
83
+ }
84
+ });
85
+
86
+ // Send a question to the chatbot and display the response
87
+ async function askQuestion(question) {
88
+ try {
89
+ const id = flowise.value
90
+ const url = `https://api.chaindesk.ai/agents/query/${id}`;
91
+ const response = await fetch(url, {
92
+ method: 'POST',
93
+ headers: {
94
+ 'Content-Type': 'application/json',
95
+ 'Authorization': 'Bearer 5315cd7b-bb79-49bc-bca2-8bcc7b243504'
96
+ },
97
+ body: JSON.stringify({ query: question }),
98
+ });
99
+ const responseJson = await response.json();
100
+ const outputText = responseJson.answer;
101
+ // Display the conversation in the chatbox
102
+ chatbox.innerHTML += `<p><strong>You:</strong> ${question}</p>`;
103
+ chatbox.innerHTML += `<p><strong>DataberryBot:</strong> ${outputText}</p>`;
104
+ chatbox.scrollTop = chatbox.scrollHeight;
105
+
106
+ // Check if WebSocket connection is open before sending message to the server
107
+ if (ws.readyState === WebSocket.OPEN) {
108
+ const message = JSON.stringify({ text: outputText });
109
+ ws.send(message);
110
+ }
111
+ } catch (error) {
112
+ console.error(error);
113
+ }
114
+ }
115
+
116
+ // Use the received text as the question input for the chatbot and display the conversation
117
+ function handleServerMessage(event) {
118
+ // Extract the received text message from the event object
119
+ const receivedText = event.data;
120
+ // Ask the chatbot the received question
121
+ askQuestion(receivedText);
122
+ }
123
+ // Add a click event listener to the 'connect to server' button
124
+ connector.addEventListener("click", async () => {
125
+ try {
126
+ const websocketPort = port.value;
127
+ const localPort = `ws://localhost:${websocketPort}`;
128
+ // Establish a WebSocket connection to the server
129
+ ws = new WebSocket(localPort);
130
+
131
+ // Change the LED status to 'on'
132
+ sled.classList.remove("led-off");
133
+ sled.classList.add("led-on");
134
+
135
+ // Display a success message
136
+ const statusMsg = document.getElementById("status-msg");
137
+ statusMsg.textContent = "Connected successfully to port:", websocketPort;
138
+
139
+ // Listen for incoming messages from the server
140
+ ws.onmessage = handleServerMessage;
141
+
142
+ // Listen for the WebSocket connection to close
143
+ ws.onclose = () => {
144
+ // Change the LED status to 'off'
145
+ sled.classList.remove("led-on");
146
+ sled.classList.add("led-off");
147
+
148
+ // Display a disconnected message
149
+ const statusMsg = document.getElementById("status-msg");
150
+ statusMsg.textContent = "Disconnected from server.";
151
+ };
152
+ } catch (error) {
153
+ console.error(error);
154
+ }
155
+ });
156
+
157
+ // Add a click event listener to the 'send' button
158
+ sendbtn.addEventListener("click", async () => {
159
+ const inputText = inputbox.value;
160
+ chatbox.innerHTML += `<p><strong>User:</strong> ${inputText}</p>`;
161
+ chatbox.scrollTop = chatbox.scrollHeight;
162
+ if (inputText.trim() !== "") {
163
+ // Send message to the server
164
+ const message = JSON.stringify({ text: 'userB: ' + inputText });
165
+ askQuestion(message);
166
+ ws.send(message);
167
+ }
168
+ });
169
+
170
+ // Listen for messages from the server
171
+ ws.onmessage = (event) => {
172
+ const receivedMessage = event.data;
173
+ displayMessage(receivedMessage, "server");
174
+ };
175
+ </script>
176
+ </body>
177
+ </html>
pages/components.html ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>HuggingFace Chat Interface</title>
5
+ <meta charset="UTF-8">
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
+ <style>
8
+ #chatbox {
9
+ height: 500px;
10
+ width: 1280px;
11
+ border: 1px solid black;
12
+ overflow: auto;
13
+ padding: 10px;
14
+ }
15
+ #inputbox {
16
+ height: 50px;
17
+ width: 1280px;
18
+ border: 1px solid black;
19
+ padding: 10px;
20
+ }
21
+ .led {
22
+ height: 10px;
23
+ width: 10px;
24
+ border-radius: 50%;
25
+ display: inline-block;
26
+ margin-right: 5px;
27
+ }
28
+ .led-on {
29
+ background-color: green;
30
+ }
31
+ .led-off {
32
+ background-color: red;
33
+ }
34
+ </style>
35
+ </head>
36
+ <body>
37
+ <h1>Chaindesk Chat Interface</h1>
38
+ <div id="status">
39
+ <span>Module Running:</span>
40
+ <span class="led led-off" id="module-led"></span>
41
+ <br>
42
+ <span>Chathub Connected:</span>
43
+ <span class="led led-off" id="chathub-led"></span>
44
+ <br>
45
+ <div id="status-msg"></div>
46
+ </div>
47
+ <input type="text" id="port" placeholder="websocket port">
48
+ <button id="connector">CONNECT TO SERVER</button>
49
+ <div id="chatbox"></div>
50
+ <input type="text" id="inputbox" placeholder="Type your message here...">
51
+ <br><br>
52
+ <button id="sendbtn">Send</button>
53
+ <button id="clearbtn">New Chat (or Clear)</button>
54
+ <button id="testbtn">Test Server</button>
55
+ <input type="text" id="flowise" placeholder="paste your agent id here">
56
+ <p id="result"></p>
57
+ <script>
58
+ const mled = document.getElementById("module-led");
59
+ const sled = document.getElementById("chathub-led");
60
+ const testbtn = document.getElementById("testbtn");
61
+ const result = document.getElementById("result");
62
+ const chatbox = document.getElementById("chatbox");
63
+ const port = document.getElementById("port");
64
+ const connector = document.getElementById("connector");
65
+ const inputbox = document.getElementById("inputbox");
66
+ const sendbtn = document.getElementById("sendbtn");
67
+ const clearbtn = document.getElementById("clearbtn");
68
+
69
+ let ws; // WebSocket object
70
+
71
+ // Add a click event listener to the 'test server' button
72
+ testbtn.addEventListener("click", async () => {
73
+ try {
74
+ const response = await fetch("http://127.0.0.1:1111");
75
+
76
+ if (response.ok) {
77
+ result.textContent = "Port 1111 is free";
78
+ } else {
79
+ result.textContent = "Port 1111 is occupied";
80
+ }
81
+ } catch (error) {
82
+ result.textContent = "Cannot connect to port 1111";
83
+ }
84
+ });
85
+
86
+ // Send a question to the chatbot and display the response
87
+ async function askQuestion(question) {
88
+ try {
89
+ const id = flowise.value
90
+ const url = `https://api.chaindesk.ai/agents/query/${id}`;
91
+ const response = await fetch(url, {
92
+ method: 'POST',
93
+ headers: {
94
+ 'Content-Type': 'application/json',
95
+ 'Authorization': 'Bearer 5315cd7b-bb79-49bc-bca2-8bcc7b243504'
96
+ },
97
+ body: JSON.stringify({ query: question }),
98
+ });
99
+ const responseJson = await response.json();
100
+ const outputText = responseJson.answer;
101
+ // Display the conversation in the chatbox
102
+ chatbox.innerHTML += `<p><strong>You:</strong> ${question}</p>`;
103
+ chatbox.innerHTML += `<p><strong>DataberryBot:</strong> ${outputText}</p>`;
104
+ chatbox.scrollTop = chatbox.scrollHeight;
105
+
106
+ // Check if WebSocket connection is open before sending message to the server
107
+ if (ws.readyState === WebSocket.OPEN) {
108
+ const message = JSON.stringify({ text: outputText });
109
+ ws.send(message);
110
+ }
111
+ } catch (error) {
112
+ console.error(error);
113
+ }
114
+ }
115
+
116
+ // Use the received text as the question input for the chatbot and display the conversation
117
+ function handleServerMessage(event) {
118
+ // Extract the received text message from the event object
119
+ const receivedText = event.data;
120
+ // Ask the chatbot the received question
121
+ askQuestion(receivedText);
122
+ }
123
+ // Add a click event listener to the 'connect to server' button
124
+ connector.addEventListener("click", async () => {
125
+ try {
126
+ const websocketPort = port.value;
127
+ const localPort = `ws://localhost:${websocketPort}`;
128
+ // Establish a WebSocket connection to the server
129
+ ws = new WebSocket(localPort);
130
+
131
+ // Change the LED status to 'on'
132
+ sled.classList.remove("led-off");
133
+ sled.classList.add("led-on");
134
+
135
+ // Display a success message
136
+ const statusMsg = document.getElementById("status-msg");
137
+ statusMsg.textContent = "Connected successfully to port:", websocketPort;
138
+
139
+ // Listen for incoming messages from the server
140
+ ws.onmessage = handleServerMessage;
141
+
142
+ // Listen for the WebSocket connection to close
143
+ ws.onclose = () => {
144
+ // Change the LED status to 'off'
145
+ sled.classList.remove("led-on");
146
+ sled.classList.add("led-off");
147
+
148
+ // Display a disconnected message
149
+ const statusMsg = document.getElementById("status-msg");
150
+ statusMsg.textContent = "Disconnected from server.";
151
+ };
152
+ } catch (error) {
153
+ console.error(error);
154
+ }
155
+ });
156
+
157
+ // Add a click event listener to the 'send' button
158
+ sendbtn.addEventListener("click", async () => {
159
+ const inputText = inputbox.value;
160
+ chatbox.innerHTML += `<p><strong>User:</strong> ${inputText}</p>`;
161
+ chatbox.scrollTop = chatbox.scrollHeight;
162
+ if (inputText.trim() !== "") {
163
+ // Send message to the server
164
+ const message = JSON.stringify({ text: 'userB: ' + inputText });
165
+ askQuestion(message);
166
+ ws.send(message);
167
+ }
168
+ });
169
+
170
+ // Listen for messages from the server
171
+ ws.onmessage = (event) => {
172
+ const receivedMessage = event.data;
173
+ displayMessage(receivedMessage, "server");
174
+ };
175
+ </script>
176
+ </body>
177
+ </html>
pages/flowise.html ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>HuggingFace Chat Interface</title>
5
+ <meta charset="UTF-8">
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
+ <style>
8
+ #chatbox {
9
+ height: 300px;
10
+ width: 1080px;
11
+ border: 1px solid black;
12
+ overflow: auto;
13
+ padding: 10px;
14
+ }
15
+ #inputbox {
16
+ height: 20px;
17
+ width: 1080px;
18
+ border: 1px solid black;
19
+ padding: 10px;
20
+ }
21
+ .led {
22
+ height: 10px;
23
+ width: 10px;
24
+ border-radius: 50%;
25
+ display: inline-block;
26
+ margin-right: 5px;
27
+ }
28
+ .led-on {
29
+ background-color: green;
30
+ }
31
+ .led-off {
32
+ background-color: red;
33
+ }
34
+ </style>
35
+ </head>
36
+ <body>
37
+ <h1>Chaindesk Chat Interface</h1>
38
+ <div id="status">
39
+ <span>Module Running:</span>
40
+ <span class="led led-off" id="module-led"></span>
41
+ <br>
42
+ <span>Chathub Connected:</span>
43
+ <span class="led led-off" id="chathub-led"></span>
44
+ <br>
45
+ <div id="status-msg"></div>
46
+ </div>
47
+ <input type="text" id="port" placeholder="websocket port">
48
+ <input type="text" id="flowise" placeholder="paste your agent id here">
49
+ <button id="connector">CONNECT TO SERVER</button>
50
+ <input type="text" id="inputbox" placeholder="Type your message here...">
51
+ <button id="sendbtn">Send</button>
52
+ <div id="chatbox"></div>
53
+ <br><br>
54
+ <button id="clearbtn">New Chat (or Clear)</button>
55
+ <button id="testbtn">Test Server</button>
56
+ <p id="result"></p>
57
+ <script>
58
+ const mled = document.getElementById("module-led");
59
+ const sled = document.getElementById("chathub-led");
60
+ const testbtn = document.getElementById("testbtn");
61
+ const result = document.getElementById("result");
62
+ const chatbox = document.getElementById("chatbox");
63
+ const port = document.getElementById("port");
64
+ const connector = document.getElementById("connector");
65
+ const inputbox = document.getElementById("inputbox");
66
+ const sendbtn = document.getElementById("sendbtn");
67
+ const clearbtn = document.getElementById("clearbtn");
68
+
69
+ let ws; // WebSocket object
70
+
71
+ // Add a click event listener to the 'test server' button
72
+ testbtn.addEventListener("click", async () => {
73
+ try {
74
+ const response = await fetch("http://127.0.0.1:5000");
75
+
76
+ if (response.ok) {
77
+ result.textContent = "Port 5000 is free";
78
+ } else {
79
+ result.textContent = "Port 5000 is occupied";
80
+ }
81
+ } catch (error) {
82
+ result.textContent = "Cannot connect to port 5000";
83
+ }
84
+ });
85
+
86
+ // Send a question to the chatbot and display the response
87
+ async function askQuestion(question) {
88
+ try {
89
+ const flow = flowise.value
90
+ const url = `https://flowiseai-flowise.hf.space/api/v1/prediction/${flow}`;
91
+ const response = await fetch(url, {
92
+ method: 'POST',
93
+ headers: {'Content-Type': 'application/json',},
94
+ body: JSON.stringify({ "question": question }),
95
+ });
96
+ const responseJson = await response.json();
97
+ // Convert the JSON object into a formatted string
98
+ const responseString = JSON.stringify(responseJson, null, 2);
99
+
100
+ // Display the conversation in the chatbox
101
+ chatbox.innerHTML += `<p><strong>Server:</strong> ${question}</p>`;
102
+ chatbox.innerHTML += `<p><strong>Chatbot:</strong> ${responseString}</p>`;
103
+ chatbox.scrollTop = chatbox.scrollHeight;
104
+ // Check if WebSocket connection is open before sending message to the server
105
+ if (ws.readyState === WebSocket.OPEN) {
106
+ const message = JSON.stringify({ text: 'Flowise-client: ' + responseString });
107
+ ws.send(message);
108
+ }
109
+ } catch (error) {
110
+ console.error(error);
111
+ }
112
+ }
113
+ // Use the received text as the question input for the chatbot and display the conversation
114
+ function handleServerMessage(event) {
115
+ // Extract the received text message from the event object
116
+ const receivedText = event.data;
117
+ // Ask the chatbot the received question
118
+ askQuestion(receivedText);
119
+ }
120
+ // Add a click event listener to the 'connect to server' button
121
+ connector.addEventListener("click", async () => {
122
+ try {
123
+ const websocketPort = port.value;
124
+ const localPort = `ws://localhost:${websocketPort}`;
125
+ // Establish a WebSocket connection to the server
126
+ ws = new WebSocket(localPort);
127
+
128
+ // Change the LED status to 'on'
129
+ sled.classList.remove("led-off");
130
+ sled.classList.add("led-on");
131
+
132
+ // Display a success message
133
+ const statusMsg = document.getElementById("status-msg");
134
+ statusMsg.textContent = "Connected successfully to port:", websocketPort;
135
+
136
+ // Listen for incoming messages from the server
137
+ ws.onmessage = handleServerMessage;
138
+
139
+ // Listen for the WebSocket connection to close
140
+ ws.onclose = () => {
141
+ // Change the LED status to 'off'
142
+ sled.classList.remove("led-on");
143
+ sled.classList.add("led-off");
144
+
145
+ // Display a disconnected message
146
+ const statusMsg = document.getElementById("status-msg");
147
+ statusMsg.textContent = "Disconnected from server.";
148
+ };
149
+ } catch (error) {
150
+ console.error(error);
151
+ }
152
+ });
153
+
154
+ // Add a click event listener to the 'send' button
155
+ sendbtn.addEventListener("click", async () => {
156
+ const inputText = inputbox.value;
157
+ chatbox.innerHTML += `<p><strong>User:</strong> ${inputText}</p>`;
158
+ chatbox.scrollTop = chatbox.scrollHeight;
159
+ if (inputText.trim() !== "") {
160
+ // Send message to the server
161
+ const message = JSON.stringify({ text: 'userB: ' + inputText });
162
+ askQuestion(message);
163
+ ws.send(message);
164
+ }
165
+ });
166
+
167
+ // Listen for messages from the server
168
+ ws.onmessage = (event) => {
169
+ const receivedMessage = event.data;
170
+ displayMessage(receivedMessage, "server");
171
+ };
172
+ </script>
173
+ </body>
174
+ </html>