Arcypojeb commited on
Commit
f0a2d7a
1 Parent(s): 4ee5651

Upload Fireworks.py

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