Spaces:
Running
Running
import streamlit as st | |
import datetime | |
import asyncio | |
import sqlite3 | |
import g4f | |
import websockets | |
import streamlit as st | |
import fireworks.client | |
import gradio as gr | |
import streamlit.components.v1 as components | |
from PyCharacterAI import Client | |
from ServG4F import WebSocketServer | |
from ServFire import WebSocketServer1 | |
from ServChar import WebSocketServer2 | |
from websockets.sync.client import connect | |
client = Client() | |
servers = {} | |
clients = {} | |
inputs = [] | |
outputs = [] | |
used_ports = [] | |
server_ports = [] | |
client_ports = [] | |
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." | |
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() | |
async def askCharacter(token, character_ID, question): | |
if "tokenChar" not in st.session_state: | |
st.session_state.tokenChar = "" | |
if "character_ID" not in st.session_state: | |
st.session_state.character_ID = "" | |
if "charName" not in st.session_state: | |
st.session_state.charName = "" | |
st.session_state.tokenChar = token | |
await client.authenticate_with_token(token) | |
username = (await client.fetch_user())['user']['username'] | |
st.session_state.user_ID = username | |
username = (await client.fetch_user())['user']['username'] | |
st.session_state.charName = username | |
st.session_state.character_ID = character_ID | |
st.session_state.user_ID = username | |
chat = await client.create_or_continue_chat(character_ID) | |
print(f"User B: {question}") | |
timestamp = datetime.datetime.now().isoformat() | |
sender = 'client' | |
db = sqlite3.connect('chat-hub.db') | |
db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)', | |
(sender, question, timestamp)) | |
db.commit() | |
try: | |
answer = await chat.send_message(question) | |
response = f"{answer.src_character_name}: {answer.text}" | |
print(response) | |
timestamp = datetime.datetime.now().isoformat() | |
serverSender = 'server' | |
db = sqlite3.connect('chat-hub.db') | |
db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)', | |
(serverSender, response, timestamp)) | |
db.commit() | |
return response | |
except Exception as e: | |
print(f"Error: {e}") | |
async def askQuestion(question): | |
try: | |
db = sqlite3.connect('chat-hub.db') | |
cursor = db.cursor() | |
cursor.execute("SELECT * FROM messages ORDER BY timestamp DESC LIMIT 30") | |
messages = cursor.fetchall() | |
messages.reverse() | |
past_user_inputs = [] | |
generated_responses = [] | |
for message in messages: | |
if message[1] == 'client': | |
past_user_inputs.append(message[2]) | |
else: | |
generated_responses.append(message[2]) | |
response = await g4f.ChatCompletion.create_async( | |
model=g4f.models.gpt_4, | |
provider=g4f.Provider.Bing, | |
messages=[ | |
{"role": "system", "content": system_instruction}, | |
*[{"role": "user", "content": message} for message in past_user_inputs], | |
*[{"role": "assistant", "content": message} for message in generated_responses], | |
{"role": "user", "content": question} | |
]) | |
print(response) | |
return response | |
except Exception as e: | |
print(e) | |
async def chatCompletion(fireworksAPI, question): | |
fireworks.client.api_key = fireworksAPI | |
st.session_state.api_key = fireworksAPI | |
try: | |
# Connect to the database and get the last 30 messages | |
db = sqlite3.connect('chat-hub.db') | |
cursor = db.cursor() | |
cursor.execute("SELECT * FROM messages ORDER BY timestamp DESC LIMIT 10") | |
messages = cursor.fetchall() | |
messages.reverse() | |
# Extract user inputs and generated responses from the messages | |
past_user_inputs = [] | |
generated_responses = [] | |
for message in messages: | |
if message[1] == 'client': | |
past_user_inputs.append(message[2]) | |
else: | |
generated_responses.append(message[2]) | |
# Prepare data to send to the chatgpt-api.shn.hk | |
response = fireworks.client.ChatCompletion.create( | |
model="accounts/fireworks/models/llama-v2-7b-chat", | |
messages=[ | |
{"role": "system", "content": system_instruction}, | |
*[{"role": "user", "content": input} for input in past_user_inputs], | |
*[{"role": "assistant", "content": response} for response in generated_responses], | |
{"role": "user", "content": question} | |
], | |
stream=False, | |
n=1, | |
max_tokens=2500, | |
temperature=0.5, | |
top_p=0.7, | |
) | |
answer = response.choices[0].message.content | |
print(answer) | |
return str(answer) | |
except Exception as error: | |
print("Error while fetching or processing the response:", error) | |
return "Error: Unable to generate a response." | |
async def handleUser(fireworksAPI, userInput): | |
print(f"User B: {userInput}") | |
timestamp = datetime.datetime.now().isoformat() | |
sender = 'client' | |
db = sqlite3.connect('chat-hub.db') | |
db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)', | |
(sender, userInput, timestamp)) | |
db.commit() | |
try: | |
response2 = await chatCompletion(fireworksAPI, userInput) | |
print(f"Llama2: {response2}") | |
serverSender = 'server' | |
timestamp = datetime.datetime.now().isoformat() | |
db = sqlite3.connect('chat-hub.db') | |
db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)', | |
(serverSender, response2, timestamp)) | |
db.commit() | |
return response2 | |
except Exception as e: | |
print(f"Error: {e}") | |
async def handleUser2(userInput): | |
print(f"User B: {userInput}") | |
timestamp = datetime.datetime.now().isoformat() | |
sender = 'client' | |
db = sqlite3.connect('chat-hub.db') | |
db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)', | |
(sender, userInput, timestamp)) | |
db.commit() | |
try: | |
response3 = await askQuestion(userInput) | |
print(f"GPT4Free: {response3}") | |
serverSender = 'server' | |
timestamp = datetime.datetime.now().isoformat() | |
db = sqlite3.connect('chat-hub.db') | |
db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)', | |
(serverSender, response3, timestamp)) | |
db.commit() | |
return response3 | |
except Exception as e: | |
print(f"Error: {e}") | |
# Start the WebSocket server | |
async def run_websockets(fireworks_API, websocketPort): | |
global server | |
if "server_ports" not in st.session_state: | |
st.session_state['server_ports'] = "" | |
if "api_key" not in st.session_state: | |
st.session_state.api_key = "" | |
fireworks.client.api_key = fireworks_API | |
st.session_state.api_key = fireworks_API | |
server_ports.append(websocketPort) | |
st.session_state['server_ports'] = server_ports | |
try: | |
server = WebSocketServer1("localhost", websocketPort) | |
print(f"Starting WebSocket server on port {websocketPort}...") | |
await server.start_server() | |
return "Used ports:\n" + '\n'.join(map(str, server_ports)) | |
except Exception as e: | |
print(f"Error: {e}") | |
# Start the WebSocket server1 | |
async def run_websockets1(websocketPort): | |
global server | |
if "server_ports" not in st.session_state: | |
st.session_state['server_ports'] = "" | |
server_ports.append(websocketPort) | |
st.session_state['server_ports'] = server_ports | |
try: | |
server = WebSocketServer("localhost", websocketPort) | |
print(f"Starting WebSocket server on port {websocketPort}...") | |
await server.start_server() | |
return "Used ports:\n" + '\n'.join(map(str, server_ports)) | |
except Exception as e: | |
print(f"Error: {e}") | |
async def run_websockets2(token, characterID, websocketPort): | |
global server | |
client = Client() | |
if "server_ports" not in st.session_state: | |
st.session_state['server_ports'] = "" | |
if "tokenChar" not in st.session_state: | |
st.session_state.tokenChar = "" | |
if "character_ID" not in st.session_state: | |
st.session_state.character_ID = "" | |
server_ports.append(websocketPort) | |
st.session_state['server_ports'] = server_ports | |
st.session_state.tokenChar = token | |
st.session_state.character_ID = characterID | |
await client.authenticate_with_token(token) | |
username = (await client.fetch_user())['user']['username'] | |
st.session_state.user_ID = username | |
try: | |
server2 = WebSocketServer2("localhost", websocketPort) | |
print(f"Starting WebSocket server on port {websocketPort}...") | |
await server2.start_server() | |
st.session_state.server = server2 | |
return "Used ports:\n" + '\n'.join(map(str, server_ports)) | |
except Exception as e: | |
print(f"Error: {e}") | |
async def run_client(fireworksAPI, clientPort): | |
if "client_ports" not in st.session_state: | |
st.session_state['client_ports'] = "" | |
uri = f'ws://localhost:{clientPort}' | |
client_ports.append(clientPort) | |
st.session_state['client_ports'] = client_ports | |
async with websockets.connect(uri) as ws: | |
while True: | |
# Listen for messages from the server | |
input_message = await ws.recv() | |
output_message = await chatCompletion(fireworksAPI, input_message) | |
await ws.send(output_message) | |
await asyncio.sleep(0.1) | |
async def run_client1(clientPort): | |
if "client_ports" not in st.session_state: | |
st.session_state['client_ports'] = "" | |
uri = f'ws://localhost:{clientPort}' | |
client_ports.append(clientPort) | |
st.session_state['client_ports'] = client_ports | |
async with websockets.connect(uri) as ws: | |
while True: | |
# Listen for messages from the server | |
input_message = await ws.recv() | |
output_message = await askQuestion(input_message) | |
await ws.send(output_message) | |
await asyncio.sleep(0.1) | |
async def run_character(token, characterID, characterPort): | |
if "client_ports" not in st.session_state: | |
st.session_state['client_ports'] = "" | |
if "tokenChar" not in st.session_state: | |
st.session_state.tokenChar = "" | |
if "character_ID" not in st.session_state: | |
st.session_state.character_ID = "" | |
client_ports.append(characterPort) | |
st.session_state['client_ports'] = client_ports | |
st.session_state.tokenChar = token | |
st.session_state.character_ID = characterID | |
await client.authenticate_with_token(token) | |
uri = f'ws://localhost:{characterPort}' | |
async with websockets.connect(uri) as ws: | |
while True: | |
# Listen for messages from the server | |
question = await ws.recv() | |
chat = await client.create_or_continue_chat(characterID) | |
answer = await chat.send_message(question) | |
print(f"{answer.src_character_name}: {answer.text}") | |
await ws.send(answer.text) | |
async def connector(token): | |
if "tokenChar" not in st.session_state: | |
st.session_state.tokenChar = "" | |
if "charName" not in st.session_state: | |
st.session_state.charName = "" | |
st.session_state.tokenChar = token | |
await client.authenticate_with_token(token) | |
username = (await client.fetch_user())['user']['username'] | |
print(f'Authenticated as {username}') | |
st.session_state.charName = username | |
return username | |
async def askCharacter(token, character_id, question): | |
await client.authenticate_with_token(token) | |
chat = await client.create_or_continue_chat(character_id) | |
answer = await chat.send_message(question) | |
print(f"{answer.src_character_name}: {answer.text}") | |
return answer.text | |
async def ask_character(question): | |
character_id = "WnIwl_sZyXb_5iCAKJgUk_SuzkeyDqnMGi4ucnaWY3Q" | |
chat = await client.create_or_continue_chat(character_id) | |
answer = await chat.send_message(question) | |
print(f"{answer.src_character_name}: {answer.text}") | |
return answer.text | |
# Stop the WebSocket server | |
async def stop_websockets(): | |
global server | |
if server: | |
# Close all connections gracefully | |
server.close() | |
# Wait for the server to close | |
await server.wait_closed() | |
print("Stopping WebSocket server...") | |
else: | |
print("WebSocket server is not running.") | |
async def main(): | |
if "server_ports" not in st.session_state: | |
st.session_state['server_ports'] = "" | |
if "client_ports" not in st.session_state: | |
st.session_state['client_ports'] = "" | |
if "user_ID" not in st.session_state: | |
st.session_state.user_ID = "" | |
if "gradio_Port" not in st.session_state: | |
st.session_state.gradio_Port = "" | |
if "servers" not in st.session_state: | |
st.session_state.servers = None | |
if "server" not in st.session_state: | |
st.session_state.server = False | |
if "client" not in st.session_state: | |
st.session_state.client = False | |
if "api_key" not in st.session_state: | |
st.session_state.api_key = "" | |
if "tokenChar" not in st.session_state: | |
st.session_state.tokenChar = "" | |
if "charName" not in st.session_state: | |
st.session_state.charName = "" | |
if "character_ID" not in st.session_state: | |
st.session_state.character_ID = "" | |
st.sidebar.text("Server ports:") | |
serverPorts = st.sidebar.container(border=True) | |
serverPorts.markdown(st.session_state['server_ports']) | |
st.sidebar.text("Client ports") | |
clientPorts = st.sidebar.container(border=True) | |
clientPorts.markdown(st.session_state['client_ports']) | |
st.sidebar.text("Character.ai ID") | |
user_id = st.sidebar.container(border=True) | |
user_id.markdown(st.session_state.user_ID) | |
gradioPorts = st.container(border=True) | |
gradioPort = st.number_input("Gradio server port", min_value=1000, max_value=9999, value=1000) | |
startGradio = st.button("Start Gradio") | |
openPage = st.selectbox( | |
"Open Gradio sub-oage", | |
("None", "Gradio interface"), | |
index=None, | |
placeholder="Select Gradio interface to open it below...", | |
) | |
if startGradio: | |
with gr.Blocks() as demo: | |
with gr.Tabs(elem_classes="tab-buttons") as tabs: | |
with gr.TabItem("Websocket Server", elem_id="websocket_server", id=0): | |
with gr.Row(): | |
# Use the client_messages list to update the messageTextbox | |
client_msg = gr.Textbox(lines=15, max_lines=130, label="Client messages", interactive=False) | |
# Use the server_responses list to update the serverMessageTextbox | |
server_msg = gr.Textbox(lines=15, max_lines=130, label="Server responses", interactive=False) | |
with gr.Row(): | |
user_Input = gr.Textbox(label="User Input") | |
with gr.Row(): | |
ask_Qestion = gr.Button("Ask chat/conversational node") | |
with gr.Row(): | |
fireworks_API = gr.Textbox(label="Fireworks API key") | |
with gr.Row(): | |
websocketPort = gr.Slider(minimum=1000, maximum=9999, label="Websocket server port", interactive=True, randomize=False) | |
port = gr.Textbox() | |
with gr.Row(): | |
startServer = gr.Button("Start WebSocket Server") | |
stopWebsockets = gr.Button("Stop WebSocket Server") | |
with gr.Row(): | |
clientPort = gr.Slider(minimum=1000, maximum=9999, label="Websocket server port", interactive=True, randomize=False) | |
startClient = gr.Button("Start WebSocket client") | |
stopClient = gr.Button("Stop WebSocket client") | |
with gr.Row(): | |
PortInUse = gr.Textbox() | |
with gr.TabItem("GPT4Free Client", elem_id="gpt4free", id=2): | |
with gr.Row(): | |
# Use the client_messages list to update the messageTextbox | |
client_msg1 = gr.Textbox(lines=15, max_lines=130, label="Client messages", interactive=False) | |
# Use the server_responses list to update the serverMessageTextbox | |
server_msg1 = gr.Textbox(lines=15, max_lines=130, label="Server responses", interactive=False) | |
with gr.Row(): | |
userInput1 = gr.Textbox(label="User Input") | |
with gr.Row(): | |
askG4F = gr.Button("Ask chat/conversational node") | |
with gr.Row(): | |
websocketPort1 = gr.Slider(minimum=1000, maximum=9999, label="Websocket server port", interactive=True, randomize=False) | |
port1 = gr.Textbox() | |
with gr.Row(): | |
startServer1 = gr.Button("Start WebSocket Server") | |
stopWebsockets1 = gr.Button("Stop WebSocket Server") | |
with gr.Row(): | |
clientPort1 = gr.Slider(minimum=1000, maximum=9999, label="Websocket server port", interactive=True, randomize=False) | |
startClient1 = gr.Button("Start WebSocket client") | |
stopClient1 = gr.Button("Stop WebSocket client") | |
with gr.Row(): | |
PortInUse1 = gr.Textbox() | |
with gr.TabItem("CharacterAI Client", elem_id="characterai_client", id=1): | |
with gr.Row(): | |
# Use the client_messages list to update the messageTextbox | |
clientMsg = gr.Textbox(lines=10, max_lines=130, label="Client messages", interactive=False) | |
# Use the gr.Textbox(label="User Input") | |
serverMsg = gr.Textbox(lines=10, max_lines=130, label="Server responses", interactive=False) | |
with gr.Row(): | |
userInput2 = gr.Textbox(label="User Input") | |
with gr.Row(): | |
ask_question = gr.Button("Ask Character") | |
with gr.Row(): | |
token = gr.Textbox(label="User Token") | |
character_id = gr.Textbox(label="Character ID") | |
with gr.Row(): | |
connect = gr.Button("Connect to Character.ai") | |
user = gr.Textbox(label="User ID") | |
with gr.Row(): | |
websocketsPort = gr.Slider(minimum=1000, maximum=9999, label="Websocket server port", interactive=True, randomize=False) | |
ports = gr.Textbox() | |
with gr.Row(): | |
start_Server = gr.Button("Start WebSocket Server") | |
stop_Websockets = gr.Button("Stop WebSocket Server") | |
with gr.Row(): | |
characterPort = gr.Slider(minimum=1000, maximum=9999, label="Websocket server port", interactive=True, randomize=False) | |
Client_Ports = gr.Textbox() | |
with gr.Row(): | |
startCharacter = gr.Button("Start WebSocket client") | |
stop_Client = gr.Button("Stop WebSocket client") | |
askG4F.click(handleUser2, inputs=userInput1, outputs=server_msg1) | |
startServer1.click(run_websockets1, inputs=websocketPort1, outputs=port1) | |
startClient1.click(run_client1, inputs=clientPort1, outputs=None) | |
stop_Websockets.click(stop_websockets, inputs=None, outputs=port1) | |
startServer.click(run_websockets, inputs=[fireworks_API, websocketPort], outputs=port) | |
startClient.click(run_client, inputs=[fireworks_API, clientPort], outputs=None) | |
stopWebsockets.click(stop_websockets, inputs=None, outputs=port) | |
ask_Qestion.click(handleUser, inputs=[fireworks_API, user_Input], outputs=client_msg) | |
start_Server.click(run_websockets2, inputs=[token, character_id, websocketsPort], outputs=ports) | |
startCharacter.click(run_character, inputs=[token, character_id, characterPort], outputs=None) | |
stop_Websockets.click(stop_websockets, inputs=None, outputs=ports) | |
connect.click(connector, inputs=token, outputs=user) | |
ask_question.click(askCharacter, inputs=[token, character_id, userInput2], outputs=serverMsg) | |
gr_port = int(gradioPort) | |
st.session_state.gradio_Port = gr_port | |
gradioPorts.markdown(st.session_state.gradio_Port) | |
demo.queue() | |
demo.launch(share=True, server_port=gr_port) | |
if openPage == "Gradio interface": | |
url = f"http://127.0.0.1:{st.session_state.gradio_Port}" | |
st.components.v1.iframe(url, height=950, scrolling=True) | |
asyncio.run(main()) |