Spaces:
Sleeping
Sleeping
Delete pages/GPT4Free.py
Browse files- pages/GPT4Free.py +0 -190
pages/GPT4Free.py
DELETED
@@ -1,190 +0,0 @@
|
|
1 |
-
import datetime
|
2 |
-
import websockets
|
3 |
-
import asyncio
|
4 |
-
import sqlite3
|
5 |
-
import json
|
6 |
-
import g4f
|
7 |
-
import streamlit as st
|
8 |
-
|
9 |
-
servers = {}
|
10 |
-
inputs = []
|
11 |
-
outputs = []
|
12 |
-
used_ports = []
|
13 |
-
server_ports = []
|
14 |
-
client_ports = []
|
15 |
-
|
16 |
-
st.set_page_config(layout="wide")
|
17 |
-
server = None
|
18 |
-
|
19 |
-
# Set up the SQLite database
|
20 |
-
db = sqlite3.connect('chat-hub.db')
|
21 |
-
cursor = db.cursor()
|
22 |
-
cursor.execute('CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, sender TEXT, message TEXT, timestamp TEXT)')
|
23 |
-
db.commit()
|
24 |
-
|
25 |
-
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."
|
26 |
-
|
27 |
-
# Define the function for sending an error message
|
28 |
-
async def askQuestion(question):
|
29 |
-
try:
|
30 |
-
db = sqlite3.connect('chat-hub.db')
|
31 |
-
cursor = db.cursor()
|
32 |
-
cursor.execute("SELECT * FROM messages ORDER BY timestamp DESC LIMIT 30")
|
33 |
-
messages = cursor.fetchall()
|
34 |
-
messages.reverse()
|
35 |
-
|
36 |
-
past_user_inputs = []
|
37 |
-
generated_responses = []
|
38 |
-
|
39 |
-
for message in messages:
|
40 |
-
if message[1] == 'client':
|
41 |
-
past_user_inputs.append(message[2])
|
42 |
-
else:
|
43 |
-
generated_responses.append(message[2])
|
44 |
-
|
45 |
-
response = await g4f.ChatCompletion.create_async(
|
46 |
-
model=g4f.models.gpt_4,
|
47 |
-
provider=g4f.Provider.Bing,
|
48 |
-
messages=[
|
49 |
-
{"role": "system", "content": system_instruction},
|
50 |
-
*[{"role": "user", "content": message} for message in past_user_inputs],
|
51 |
-
*[{"role": "assistant", "content": message} for message in generated_responses],
|
52 |
-
{"role": "user", "content": question}
|
53 |
-
])
|
54 |
-
|
55 |
-
print(response)
|
56 |
-
return response
|
57 |
-
|
58 |
-
except Exception as e:
|
59 |
-
print(e)
|
60 |
-
|
61 |
-
async def handleWebSocket(ws):
|
62 |
-
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)"
|
63 |
-
print('New connection')
|
64 |
-
await ws.send(instruction)
|
65 |
-
while True:
|
66 |
-
message = await ws.recv()
|
67 |
-
print(f'Received message: {message}')
|
68 |
-
inputMsg = st.chat_message("assistant")
|
69 |
-
inputMsg.markdown(message)
|
70 |
-
timestamp = datetime.datetime.now().isoformat()
|
71 |
-
sender = 'client'
|
72 |
-
db = sqlite3.connect('chat-hub.db')
|
73 |
-
db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
|
74 |
-
(sender, message, timestamp))
|
75 |
-
db.commit()
|
76 |
-
try:
|
77 |
-
response = await askQuestion(message)
|
78 |
-
serverResponse = f"server: {response}"
|
79 |
-
outputMsg = st.chat_message("ai")
|
80 |
-
print(serverResponse)
|
81 |
-
outputMsg.markdown(response)
|
82 |
-
timestamp = datetime.datetime.now().isoformat()
|
83 |
-
serverSender = 'server'
|
84 |
-
db = sqlite3.connect('chat-hub.db')
|
85 |
-
db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
|
86 |
-
(serverSender, serverResponse, timestamp))
|
87 |
-
db.commit()
|
88 |
-
# Append the server response to the server_responses list
|
89 |
-
await ws.send(serverResponse)
|
90 |
-
|
91 |
-
except websockets.exceptions.ConnectionClosedError as e:
|
92 |
-
print(f"Connection closed: {e}")
|
93 |
-
|
94 |
-
except Exception as e:
|
95 |
-
print(f"Error: {e}")
|
96 |
-
|
97 |
-
# Start the WebSocket server
|
98 |
-
async def start_websockets(websocketPort):
|
99 |
-
async with websockets.serve(handleWebSocket, 'localhost', websocketPort):
|
100 |
-
print(f"Starting WebSocket server on port {websocketPort}...")
|
101 |
-
await asyncio.Future()
|
102 |
-
|
103 |
-
async def start_client(clientPort):
|
104 |
-
global ws
|
105 |
-
output_Msg = st.chat_message("assistant")
|
106 |
-
input_Msg = st.chat_message("ai")
|
107 |
-
uri = f'ws://localhost:{clientPort}'
|
108 |
-
client_ports.append(clientPort)
|
109 |
-
async with websockets.connect(uri) as ws:
|
110 |
-
while True:
|
111 |
-
print(f"Connecting to server at port: {clientPort}...")
|
112 |
-
# Listen for messages from the server
|
113 |
-
input_message = await ws.recv()
|
114 |
-
input_Msg.markdown(input_message)
|
115 |
-
output_message = await askQuestion(input_message)
|
116 |
-
output_Msg.markdown(output_message)
|
117 |
-
await ws.send(json.dumps(output_message))
|
118 |
-
|
119 |
-
async def handleUser(userInput):
|
120 |
-
user_input = st.chat_message("human")
|
121 |
-
user_input.markdown(userInput)
|
122 |
-
timestamp = datetime.datetime.now().isoformat()
|
123 |
-
sender = 'client'
|
124 |
-
db = sqlite3.connect('chat-hub.db')
|
125 |
-
db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
|
126 |
-
(sender, userInput, timestamp))
|
127 |
-
db.commit()
|
128 |
-
try:
|
129 |
-
response = await askQuestion(userInput)
|
130 |
-
server_response = st.chat_message("assistant")
|
131 |
-
server_response.markdown(response)
|
132 |
-
serverSender = 'server'
|
133 |
-
timestamp = datetime.datetime.now().isoformat()
|
134 |
-
db = sqlite3.connect('chat-hub.db')
|
135 |
-
db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
|
136 |
-
(serverSender, response, timestamp))
|
137 |
-
db.commit()
|
138 |
-
|
139 |
-
except Exception as e:
|
140 |
-
print(f"Error: {e}")
|
141 |
-
|
142 |
-
# Stop the WebSocket server
|
143 |
-
async def stop_websockets():
|
144 |
-
global server
|
145 |
-
if server:
|
146 |
-
# Close all connections gracefully
|
147 |
-
server.close()
|
148 |
-
# Wait for the server to close
|
149 |
-
server.wait_closed()
|
150 |
-
print("Stopping WebSocket server...")
|
151 |
-
else:
|
152 |
-
print("WebSocket server is not running.")
|
153 |
-
|
154 |
-
# Stop the WebSocket client
|
155 |
-
async def stop_client():
|
156 |
-
global ws
|
157 |
-
# Close the connection with the server
|
158 |
-
ws.close()
|
159 |
-
print("Stopping WebSocket client...")
|
160 |
-
|
161 |
-
async def main():
|
162 |
-
userInput = st.chat_input("User input")
|
163 |
-
websocketPort = st.sidebar.slider('Server port', min_value=1000, max_value=9999, value=1000)
|
164 |
-
startServer = st.sidebar.button('Start websocket server')
|
165 |
-
clientPort = st.sidebar.slider('Client port', min_value=1000, max_value=9999, value=1000)
|
166 |
-
startClient = st.sidebar.button('Connect client to server')
|
167 |
-
st.sidebar.text("Server ports:")
|
168 |
-
serverPorts = st.sidebar.container(border=True)
|
169 |
-
serverPorts.text("Local ports")
|
170 |
-
st.sidebar.text("Client ports")
|
171 |
-
clientPorts = st.sidebar.container(border=True)
|
172 |
-
clientPorts.text("Connected ports")
|
173 |
-
|
174 |
-
if userInput:
|
175 |
-
print(f"User B: {userInput}")
|
176 |
-
srvr_response = await handleUser(userInput)
|
177 |
-
print(f"Server: {srvr_response}")
|
178 |
-
|
179 |
-
if startServer:
|
180 |
-
server_ports.append(websocketPort)
|
181 |
-
serverPorts.markdown(server_ports)
|
182 |
-
await start_websockets(websocketPort)
|
183 |
-
|
184 |
-
if startClient:
|
185 |
-
client_ports.append(clientPort)
|
186 |
-
clientPorts.markdown(client_ports)
|
187 |
-
await start_client(clientPort)
|
188 |
-
|
189 |
-
|
190 |
-
asyncio.run(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|