Arcypojeb commited on
Commit
152577e
·
1 Parent(s): 844ea56

Rename App.py to app.py

Browse files
Files changed (2) hide show
  1. App.py +0 -132
  2. app.py +211 -0
App.py DELETED
@@ -1,132 +0,0 @@
1
- import requests
2
- import datetime
3
- import http.server
4
- import websockets
5
- import asyncio
6
- import sqlite3
7
- import json
8
- import tensorflow as tf
9
- import gradio as gr
10
-
11
- from bs4 import BeautifulSoup
12
-
13
- # Define a placeholder function that doesn't do anything
14
- def placeholder_fn(input_text):
15
- pass
16
-
17
- # Set up the HTTP server
18
- class SimpleHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
19
- def do_GET(self):
20
- if self.path == '/':
21
- self.send_response(200)
22
- self.send_header('Content-type', 'text/html')
23
- self.end_headers()
24
- with open('index.html', 'rb') as file:
25
- self.wfile.write(file.read())
26
- else:
27
- self.send_response(404)
28
- self.end_headers()
29
-
30
- # Define the function for handling incoming messages
31
- async def handleMessage(message):
32
- response = {'message': message.get('message')}
33
- try:
34
- question = message.get('message')
35
- result = await askQuestion(question)
36
- response['result'] = result
37
- except Exception as e:
38
- print(e)
39
- return response
40
-
41
- # Define the function for sending an error message
42
- def sendErrorMessage(ws, errorMessage):
43
- errorResponse = {'error': errorMessage}
44
- ws.send(json.dumps(errorResponse))
45
-
46
- # Define the function for asking a question to the chatbot
47
- async def askQuestion(question):
48
- try:
49
- db = sqlite3.connect('chat-hub.db')
50
- cursor = db.execute('SELECT * FROM messages ORDER BY timestamp DESC LIMIT 10')
51
- messages = cursor.fetchall()
52
- pastUserInputs = []
53
- generatedResponses = []
54
- for i, message in enumerate(messages):
55
- if i % 2 == 0:
56
- pastUserInputs.append(message[2])
57
- else:
58
- generatedResponses.append(message[2])
59
- response = requests.post(
60
- "https://api-inference.huggingface.co/models/facebook/blenderbot-400M-distill",
61
- headers={
62
- "Content-Type": "application/json",
63
- "Authorization": "Bearer HF_TOKEN",
64
- },
65
- json={
66
- "inputs": {
67
- "text": question,
68
- "past_user_inputs": pastUserInputs,
69
- "generated_responses": generatedResponses,
70
- },
71
- "full_source": False,
72
- },
73
- )
74
- responseJson = response.json()
75
- outputText = responseJson["generated_text"]
76
- return outputText
77
- except Exception as e:
78
- print(e)
79
-
80
- # Define the WebSocket handler
81
- async def handleWebSocket(ws, path):
82
- print('New connection')
83
- try:
84
- # Set up the SQLite database
85
- db = sqlite3.connect('chat-hub.db')
86
- db.execute('CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, sender TEXT, message TEXT, timestamp TEXT)')
87
- db.commit()
88
- await ws.send('Hello! Please integrate yourself with the local sql database and file system')
89
- async for message in ws:
90
- print(f'Received message: {message}')
91
- parsedMessage = json.loads(message)
92
- messageText = parsedMessage.get('text', '')
93
- timestamp = datetime.datetime.now().isoformat()
94
- sender = 'client'
95
- db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)', (sender, messageText, timestamp))
96
- db.commit()
97
- try:
98
- if 'text' in parsedMessage:
99
- answer = await askQuestion(parsedMessage['text'])
100
- response = {'answer': answer}
101
- await ws.send(json.dumps(response))
102
- serverMessageText = response.get('answer', '')
103
- serverSender = 'server'
104
- db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)', (serverSender, serverMessageText, timestamp))
105
- db.commit()
106
- except Exception as e:
107
- print(e)
108
- sendErrorMessage(ws, 'An error occurred while processing the message.')
109
- except websockets.exceptions.ConnectionClosedError as e:
110
- print(f"Connection closed: {e}")
111
- except Exception as e:
112
- print(f"Error: {e}")
113
- finally:
114
- print("Closing connection")
115
-
116
- port=5000
117
- # Start the WebSocket server
118
- async def start_websockets():
119
- await(websockets.serve(handleWebSocket, 'localhost', port))
120
- print(f"Starting WebSocket server on port {port}...")
121
-
122
- with gr.Blocks() as demo:
123
-
124
- # Define Gradio interface
125
- fn=placeholder_fn, # Placeholder function
126
- inputs=[gr.Textbox()],
127
- outputs=[gr.Textbox()],
128
- startWebsockets = gr.Button("start Websocket Server")
129
- startWebsockets.click(start_websockets)
130
- live=True
131
-
132
- demo.launch(server_port=8888)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import datetime
3
+ import http.server
4
+ import websockets
5
+ import websocket
6
+ import asyncio
7
+ import sqlite3
8
+ import json
9
+ import gradio as gr
10
+ from bs4 import BeautifulSoup
11
+ from gradio_client import Client
12
+ import time
13
+
14
+ client_messages = []
15
+ server_responses = []
16
+ messages = []
17
+ used_ports = []
18
+
19
+ websocket_server = None
20
+ stop = asyncio.Future()
21
+
22
+ # Global variables to store references to the textboxes
23
+ messageTextbox = None
24
+ serverMessageTextbox = None
25
+
26
+ def slow_echo(message, history):
27
+ for i in range(len(message)):
28
+ time.sleep(0.3)
29
+ yield "You typed: " + message[: i+1]
30
+
31
+ # Define a function to read the HTML file
32
+ def read_html_file(file_name):
33
+ with open(file_name, 'r') as file:
34
+ html_content = file.read()
35
+ return html_content
36
+
37
+ # Set up the HTTP server
38
+ class SimpleHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
39
+ def do_GET(self):
40
+ if self.path == '/':
41
+ self.send_response(200)
42
+ self.send_header('Content-type', 'text/html')
43
+ self.end_headers()
44
+ with open('index.html', 'rb') as file:
45
+ self.wfile.write(file.read())
46
+ else:
47
+ self.send_response(404)
48
+ self.end_headers()
49
+
50
+ # Set up the SQLite database
51
+ db = sqlite3.connect('chat-hub.db')
52
+ cursor = db.cursor()
53
+ cursor.execute('CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, sender TEXT, message TEXT, timestamp TEXT)')
54
+ db.commit()
55
+
56
+ # Define the function for sending an error message
57
+ def sendErrorMessage(ws, errorMessage):
58
+ errorResponse = {'error': errorMessage}
59
+ ws.send(json.dumps(errorResponse))
60
+
61
+ # Define a function to ask a question to the chatbot and display the response
62
+ async def askQuestion(question):
63
+ try:
64
+ # Connect to the database and get the last 30 messages
65
+ db = sqlite3.connect('chat-hub.db') # Replace 'your_database.db' with your database file
66
+ cursor = db.cursor()
67
+ cursor.execute("SELECT * FROM messages ORDER BY timestamp DESC LIMIT 30")
68
+ messages = cursor.fetchall()
69
+
70
+ # Extract user inputs and generated responses from the messages
71
+ past_user_inputs = []
72
+ generated_responses = []
73
+
74
+ for message in messages:
75
+ if message[1] == 'server':
76
+ past_user_inputs.append(message[2])
77
+ else:
78
+ generated_responses.append(message[2])
79
+
80
+ # Prepare data to send to the chatgpt-api.shn.hk
81
+ system_instruction = "You are now integrated with a local websocket server in a project of hierarchical cooperative multi-agent framework called NeuralGPT. Your 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 (example: 'Starcoder-client' for LLM called Starcoder). Your chat memory module is integrated with a local SQL database with chat history. Your main job is to integrate the hierarchical cooperative multi-agent framework with the local environment of User B (createor of NeuralGPT project). Remember to maintain the logical and chronological order while answering to incoming messages and to send your answers to correct clients to maintain synchronization of question->answer logic"
82
+ messages_data = [
83
+ {"role": "system", "content": system_instruction},
84
+ {"role": "user", "content": question},
85
+ *[{"role": "user", "content": input} for input in past_user_inputs],
86
+ *[{"role": "assistant", "content": response} for response in generated_responses]
87
+ ]
88
+ request_data = {
89
+ "model": "gpt-3.5-turbo",
90
+ "messages": messages_data
91
+ }
92
+
93
+ # Make the request to the chatgpt-api.shn.hk
94
+ response = requests.post("http://127.0.0.1:6969/api/conversation?text=", json=request_data)
95
+
96
+ # Process the response and get the generated answer
97
+ response_data = response.json()
98
+ generated_answer = response_data["choices"][0]["message"]["content"]
99
+
100
+ # Save the generated answer to the database or take further actions as needed
101
+ print(generated_answer)
102
+ return generated_answer
103
+ except Exception as error:
104
+ print("Error while fetching or processing the response:", error)
105
+ return "Error: Unable to generate a response."
106
+
107
+
108
+ async def listen_for_messages():
109
+ while True:
110
+ if len(client_messages) > 0:
111
+ # Get the latest client message
112
+ client_message = client_messages[-1]
113
+ try:
114
+ server_message = server_responses[-1]
115
+ except IndexError:
116
+ # Handle the case when there are no server responses yet
117
+ server_message = "connected successfully"
118
+
119
+ return client_message, server_message
120
+ else:
121
+ # Handle the case when there are no client messages yet
122
+ client_message = "connected successfully"
123
+ server_message = "connected successfully"
124
+
125
+ return client_message, server_message
126
+
127
+ async def handleWebSocket(ws):
128
+ print('New connection')
129
+ await ws.send('Hello! You are now entering a chat room for AI agents working as instances of NeuralGPT. Keep in mind that you are speaking with another chatbot')
130
+ while True:
131
+ message = await ws.recv()
132
+ message_copy = message
133
+ client_messages.append(message_copy)
134
+ print(f'Received message: {message}')
135
+ parsedMessage = json.loads(message)
136
+ messageText = message
137
+ messages.append(message)
138
+ timestamp = datetime.datetime.now().isoformat()
139
+ sender = 'client'
140
+ db = sqlite3.connect('chat-hub.db')
141
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
142
+ (sender, messageText, timestamp))
143
+ db.commit()
144
+ try:
145
+ message = messages[-1]
146
+ answer = await askQuestion(message) # Use the message directly
147
+ response = {'answer': answer}
148
+ serverMessageText = response.get('answer', '')
149
+ await ws.send(json.dumps(response))
150
+ # Append the server response to the server_responses list
151
+ server_responses.append(serverMessageText)
152
+ serverSender = 'server'
153
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
154
+ (serverSender, serverMessageText, timestamp))
155
+ db.commit()
156
+
157
+ except websockets.exceptions.ConnectionClosedError as e:
158
+ print(f"Connection closed: {e}")
159
+
160
+ except Exception as e:
161
+ print(f"Error: {e}")
162
+
163
+
164
+ # Function to stop the WebSocket server
165
+ def stop_websockets():
166
+ global websocket_server
167
+ if websocket_server:
168
+ cursor.close()
169
+ db.close()
170
+ websocket_server.close()
171
+ print("WebSocket server stopped.")
172
+ else:
173
+ print("WebSocket server is not running.")
174
+
175
+ # Start the WebSocket server
176
+ async def start_websockets(websocketPort):
177
+ global messageTextbox, serverMessageTextbox, websocket_server
178
+ # Create a WebSocket client that connects to the server
179
+
180
+ await(websockets.serve(handleWebSocket, 'localhost', websocketPort))
181
+ used_ports.append(websocketPort)
182
+ print(f"Starting WebSocket server on port {websocketPort}...")
183
+ return "Used ports:\n" + '\n'.join(map(str, used_ports))
184
+
185
+ def create_iframe():
186
+ # Create an iframe with your HTML content
187
+ iframe_code = f'<iframe srcdoc="{htmlStr}" width="70%" height="70%"></iframe>'
188
+ return iframe_code
189
+
190
+ with gr.Blocks() as demo:
191
+
192
+ with gr.Column(scale=1, min_width=600):
193
+ with gr.Row():
194
+ # Use the client_messages list to update the messageTextbox
195
+ client_message = gr.Textbox(lines=15, max_lines=130, label="Client inputs")
196
+ # Use the server_responses list to update the serverMessageTextbox
197
+ server_message = gr.Textbox(lines=15, max_lines=130, label="Server responses")
198
+ with gr.Row():
199
+ websocketPort = gr.Slider(minimum=1000, maximum=9999, label="Websocket server port", interactive=True, randomize=False)
200
+ startWebsockets = gr.Button("Start WebSocket Server")
201
+ stopWebsockets = gr.Button("Stop WebSocket Server")
202
+ with gr.Row():
203
+ gui = gr.Button("connect interface")
204
+ with gr.Row():
205
+ port = gr.Textbox()
206
+ startWebsockets.click(start_websockets, inputs=websocketPort, outputs=port)
207
+ gui.click(listen_for_messages, inputs=None, outputs={client_message, server_message})
208
+ stopWebsockets.click(stop_websockets)
209
+
210
+ demo.queue()
211
+ demo.launch(share=True, server_port=1111)