File size: 6,560 Bytes
155b034
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import datetime
import websockets
import asyncio
import sqlite3
import json
import g4f
import streamlit as st
import fireworks.client

import streamlit as st
from multipage import MultiPage

app = MultiPage()
st.set_page_config(
    page_title='OCR Comparator', layout ="wide",
    initial_sidebar_state="expanded",
)

# Add all your application here
app.add_page("Home", "house", home.app)
app.add_page("About", "info-circle", about.app)
app.add_page("App", "cast", ocr_comparator.app)

# The main app
app.run()

servers = {}
inputs = []
outputs = []
used_ports = []
server_ports = []
client_ports = []

st.set_page_config(layout="wide")
websocket_server = None

GOOGLE_CSE_ID = "f3882ab3b67cc4923"
GOOGLE_API_KEY = "AIzaSyBNvtKE35EAeYO-ECQlQoZO01RSHWhfIws"
FIREWORKS_API_KEY = "xbwGxyTyOf7ats2GcEU0Pj62kpZBVZa2r6i5lKbKG99LFG38"

# Set up the SQLite database
db = sqlite3.connect('chat-hub.db')
cursor = db.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, sender TEXT, message TEXT, timestamp TEXT)')    
db.commit()

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."

st.set_page_config(layout="wide")
# Start the WebSocket server 
async def start_websockets(websocketPort):
    async with websockets.serve(handleWebSocket, 'localhost', websocketPort):    
        print(f"Starting WebSocket server on port {websocketPort}...")        
        await asyncio.Future()

async def handleServer(ws):              
    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)" 
    print('New connection')
    await ws.send(instruction)
    while True:
        message = await ws.recv()        
        print(f'Received message: {message}')
        inputMsg = st.chat_message("assistant")
        inputMsg.markdown(message)
        timestamp = datetime.datetime.now().isoformat()
        sender = 'client'
        db = sqlite3.connect('chat-hub.db')
        db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
                    (sender, message, timestamp))
        db.commit()   
        try:
            response = await chatCompletion(message)
            serverResponse = f"server: {response}"
            outputMsg = st.chat_message("ai") 
            print(serverResponse)
            outputMsg.markdown(response)
            timestamp = datetime.datetime.now().isoformat()
            serverSender = 'server'
            db = sqlite3.connect('chat-hub.db')
            db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
                        (serverSender, serverResponse, timestamp))
            db.commit()   
            # Append the server response to the server_responses list
            await ws.send(serverResponse)
                   
        except websockets.exceptions.ConnectionClosedError as e:
            print(f"Connection closed: {e}")

        except Exception as e:
            print(f"Error: {e}")

async def start_client(clientPort):
    global ws    
    input_Msg = st.chat_message("ai")    
    uri = f'ws://localhost:{clientPort}'
    client_ports.append(clientPort)
    async with websockets.connect(uri) as ws:
        while True:
            print(f"Connecting to server at port: {clientPort}...")
            # Listen for messages from the server            
            input_message = await ws.recv()
            output_Msg = st.chat_message("assistant")
            input_Msg.markdown(input_message)
            output_message = await chatCompletion(input_message)
            output_Msg.markdown(output_message)
            await ws.send(json.dumps(output_message))            

# Stop the WebSocket server
async def stop_websockets():    
    global server
    if server:
        # Close all connections gracefully
        server.close()
        # Wait for the server to close
        server.wait_closed()
        print("Stopping WebSocket server...")
    else:
        print("WebSocket server is not running.")

# Stop the WebSocket client
async def stop_client():
    global ws
    # Close the connection with the server
    ws.close()
    print("Stopping WebSocket client...")

st.sidebar.text("Server ports:")
serverPorts = st.sidebar.container(border=True)
serverPorts.text("Local ports")
st.sidebar.text("Client ports")
clientPorts = st.sidebar.container(border=True)
clientPorts.text("Connected ports")

async def main():
    tab1, tab2, tab3 = st.tabs(["Fireworks", "GPT4Free", "Character.ai"])

    with tab1:
        st.header("Fireworks Llama2-7B")
        userInput1 = st.chat_input("User input")
        col1, col2 = st.columns([4, 1])
        with col1:
            serverPorts = st.sidebar.container(border=True)
            serverPorts.text("Local ports")
            clientPorts = st.sidebar.container(border=True)
            clientPorts.text("Connected ports")

        with col2:
            server_Port = st.number_input("Port", 1000)
            client_Port = st.number_input("Port",1000)

            if userInput1:        
                print(f"User B: {userInput1}")
                await handleUser(userInput1)               

    with tab2:
        st.header("A dog")
        st.image("https://static.streamlit.io/examples/dog.jpg", width=200)

    with tab3:
        st.header("An owl")
        st.image("https://static.streamlit.io/examples/owl.jpg", width=200)

asyncio.run(main())