Arcypojeb commited on
Commit
d26139f
·
verified ·
1 Parent(s): bcbf773

Delete ServFire.py

Browse files
Files changed (1) hide show
  1. ServFire.py +0 -124
ServFire.py DELETED
@@ -1,124 +0,0 @@
1
- import asyncio
2
- import websockets
3
- import threading
4
- import sqlite3
5
- import datetime
6
- import g4f
7
- import streamlit as st
8
- import fireworks.client
9
-
10
- class WebSocketServer:
11
- def __init__(self, host, port):
12
- self.host = host
13
- self.port = port
14
- self.server = None
15
-
16
- async def chatCompletion(self, question):
17
-
18
- if "api_key" not in st.session_state:
19
- st.session_state.api_key = ""
20
-
21
- fireworks.client.api_key = st.session_state.api_key
22
- 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."
23
-
24
- try:
25
- # Connect to the database and get the last 30 messages
26
- db = sqlite3.connect('chat-hub.db')
27
- cursor = db.cursor()
28
- cursor.execute("SELECT * FROM messages ORDER BY timestamp DESC LIMIT 10")
29
- messages = cursor.fetchall()
30
- messages.reverse()
31
-
32
- # Extract user inputs and generated responses from the messages
33
- past_user_inputs = []
34
- generated_responses = []
35
-
36
- for message in messages:
37
- if message[1] == 'client':
38
- past_user_inputs.append(message[2])
39
- else:
40
- generated_responses.append(message[2])
41
-
42
- # Prepare data to send to the chatgpt-api.shn.hk
43
- response = fireworks.client.ChatCompletion.create(
44
- model="accounts/fireworks/models/llama-v2-7b-chat",
45
- messages=[
46
- {"role": "system", "content": system_instruction},
47
- *[{"role": "user", "content": message} for message in past_user_inputs],
48
- *[{"role": "assistant", "content": message} for message in generated_responses],
49
- {"role": "user", "content": question}
50
- ],
51
- stream=False,
52
- n=1,
53
- max_tokens=2500,
54
- temperature=0.5,
55
- top_p=0.7,
56
- )
57
-
58
- answer = response.choices[0].message.content
59
- print(answer)
60
- return str(answer)
61
-
62
- except Exception as error:
63
- print("Error while fetching or processing the response:", error)
64
- return "Error: Unable to generate a response."
65
-
66
- # Define the handler function that will process incoming messages
67
- async def handler(self, websocket):
68
- 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)"
69
- print('New connection')
70
- await websocket.send(instruction)
71
- db = sqlite3.connect('chat-hub.db')
72
- # Loop forever
73
- while True:
74
- # Receive a message from the client
75
- message = await websocket.recv()
76
- # Print the message
77
- print(f"Server received: {message}")
78
- input_Msg = st.chat_message("assistant")
79
- input_Msg.markdown(message)
80
- timestamp = datetime.datetime.now().isoformat()
81
- sender = 'client'
82
- db = sqlite3.connect('chat-hub.db')
83
- db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
84
- (sender, message, timestamp))
85
- db.commit()
86
- try:
87
- response = await self.chatCompletion(message)
88
- serverResponse = f"server: {response}"
89
- print(serverResponse)
90
- output_Msg = st.chat_message("ai")
91
- output_Msg.markdown(serverResponse)
92
- timestamp = datetime.datetime.now().isoformat()
93
- serverSender = 'server'
94
- db = sqlite3.connect('chat-hub.db')
95
- db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
96
- (serverSender, serverResponse, timestamp))
97
- db.commit()
98
- # Append the server response to the server_responses list
99
- await websocket.send(serverResponse)
100
- continue
101
-
102
- except websockets.exceptions.ConnectionClosedError as e:
103
- print(f"Connection closed: {e}")
104
-
105
- except Exception as e:
106
- print(f"Error: {e}")
107
-
108
- async def start_server(self):
109
- self.server = await websockets.serve(
110
- self.handler,
111
- self.host,
112
- self.port
113
- )
114
- print(f"WebSocket server started at ws://{self.host}:{self.port}")
115
-
116
- def run_forever(self):
117
- asyncio.get_event_loop().run_until_complete(self.start_server())
118
- asyncio.get_event_loop().run_forever()
119
-
120
- async def stop_server(self):
121
- if self.server:
122
- self.server.close()
123
- await self.server.wait_closed()
124
- print("WebSocket server stopped.")