Spaces:
Running
Running
File size: 12,099 Bytes
1e6a278 a2f1aa1 1e6a278 a2f1aa1 4bfaa35 1e6a278 a2f1aa1 4365038 a2f1aa1 1e6a278 a2f1aa1 1e6a278 a2f1aa1 f9c615f ed808a2 a2f1aa1 f9c615f a2f1aa1 1e6a278 a2f1aa1 1e6a278 a2f1aa1 1e6a278 a2f1aa1 1e6a278 a2f1aa1 1e6a278 a2f1aa1 1e6a278 a2f1aa1 1e6a278 a2f1aa1 1e6a278 a2f1aa1 1e6a278 a2f1aa1 1e6a278 f54120b a2f1aa1 f54120b a2f1aa1 1e6a278 a2f1aa1 1e6a278 a2f1aa1 f9c615f 1e6a278 a2f1aa1 2537227 a2f1aa1 0b7c833 |
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 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 |
import datetime
import websockets
import asyncio
import sqlite3
import json
import requests
import gradio as gr
import PySimpleGUI as sg
from bs4 import BeautifulSoup
from gradio_client import Client
from websockets.sync.client import connect
modelPath = 'nlp-model.json'
inputs = []
client_ports = []
server_ports = []
layout = [
[sg.Multiline(size=(200, 10), key='-CLIENT-')],
[sg.Multiline(size=(100, 20), key='-INPUT-', auto_refresh=True), sg.Multiline(size=(100, 20), key='-OUTPUT-', auto_refresh=True)],
[sg.Multiline(size=(150, 2), key='-USERINPUT-')],
[sg.Button('Ask the agent')],
[sg.Text('Enter Port:'), sg.InputText(size=(10, 1), key='-PORT-'),
sg.Slider(range=(1000, 9999), orientation='h', size=(20, 20), key='-PORTSLIDER-')],
[sg.Button('Start WebSocket server'), sg.Button('Start WebSocket client')],
[sg.Button('Stop WebSocket server'), sg.Button('Stop WebSocket client')],
[sg.Multiline(size=(20, 4), key='-SERVER_PORTS-')], [sg.Multiline(size=(20, 4), key='-CLIENT_PORTS-')],
[sg.Button('Clear Textboxes')]
]
def get_port(values):
if values['-PORT-']:
return int(values['-PORT-'])
else:
return int(values['-PORTSLIDER-'])
window = sg.Window('WebSocket Client', layout)
# Function to send a question to the chatbot and get the response
async def askQuestion(question):
url = 'https://api.docsbot.ai/teams/ZrbLG98bbxZ9EFqiPvyl/bots/oFFiXuQsakcqyEdpLvCB/chat'
headers = {
'Content-Type': 'application/json'
}
data = {
'question': question,
'full_source': False
}
try:
response = requests.post(url, headers=headers, json=data)
responseText = response.content.decode('utf-8')
return responseText
except requests.exceptions.RequestException as e:
# Handle request exceptions here
print(f"Request failed with exception: {e}")
async def askQuestion2(question):
url = 'https://api.docsbot.ai/teams/ZrbLG98bbxZ9EFqiPvyl/bots/oFFiXuQsakcqyEdpLvCB/chat'
headers = {
'Content-Type': 'application/json'
}
data = {
'question': question,
'full_source': False
}
try:
response = requests.post(url, headers=headers, json=data)
responseText = response.content.decode('utf-8')
return responseText
except requests.exceptions.RequestException as e:
# Handle request exceptions here
print(f"Request failed with exception: {e}")
async def askQuestion3(question):
url = 'https://api.docsbot.ai/teams/ZrbLG98bbxZ9EFqiPvyl/bots/oFFiXuQsakcqyEdpLvCB/chat'
headers = {
'Content-Type': 'application/json'
}
data = {
'question': question,
'full_source': False
}
try:
response = requests.post(url, headers=headers, json=data)
responseText = response.content.decode('utf-8')
return responseText
except requests.exceptions.RequestException as e:
# Handle request exceptions here
print(f"Request failed with exception: {e}")
async def run_agent(question):
os.environ["GOOGLE_CSE_ID"] = GOOGLE_CSE_ID
os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
os.environ["FIREWORKS_API_KEY"] = FIREWORKS_API_KEY
llm = Fireworks(model="accounts/fireworks/models/llama-v2-13b")
tools = load_tools(["google-search", "llm-math"], llm=llm)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, return_intermediate_steps=True)
response = agent({"input": question})
return response["output"], response["intermediate_steps"]
response_content = response.content.decode('utf-8')
return response_content
async def handleWebSocket(ws):
print('New connection')
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."
greetings = {'instructions': instruction}
await ws.send(json.dumps(instruction))
while True:
message = await ws.recv()
print(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 askQuestion(message)
serverResponse = f'server response:{response}'
# Append the server response to the server_responses list
timestamp = datetime.datetime.now().isoformat()
serverSender = 'server'
db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
(serverSender, serverResponse, timestamp))
db.commit()
await ws.send(json.dumps(serverResponse))
return serverResponse
except websockets.exceptions.ConnectionClosedError as e:
print(f"Connection closed: {e}")
except Exception as e:
print(f"Error: {e}")
async def handle_message(message):
print(f'Received message: {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:
userMessage = f'User B:{message}'
response = await askQuestion(userMessage)
serverResponse = f'server response:{response}'
timestamp = datetime.datetime.now().isoformat()
serverSender = 'server'
db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
(serverSender, serverResponse, timestamp))
db.commit()
return serverResponse
except Exception as e:
print(f"Error: {e}")
# Define start_client function with a variable port
async def start_client(clientPort):
uri = f'ws://localhost:{clientPort}'
client_ports.append(clientPort)
window['-CLIENT_PORTS-'].print(str(client_ports) + '\n')
async with websockets.connect(uri, create_protocol=handleClient) as websocket:
print("Connected to server at:", clientPort)
return "Used ports:\n" + '\n'.join(map(str, client_ports))
message = await websocket.recv()
inputMsg = "client: " + handle_message
window['-INPUT-'].print(str(inputMsg) + '\n')
print(message)
return message
async def handleClient(websocket, path):
return client1_msg
async def connect_docsbot(clientPort):
uri = f'ws://localhost:{clientPort}'
async with websockets.connect(uri) as websocket:
print("Connected to server at:", clientPort)
client_ports.append(clientPort)
window['-CLIENT_PORTS-'].print(str(client_ports) + '\n')
return "Used ports:\n" + '\n'.join(map(str, client_ports))
while True:
message = await websocket.recv()
inputMsg = "client: " + handle_message
window['-INPUT-'].print(str(inputMsg) + '\n')
print(message)
return message
async def handleClient2(websocket, path):
return client2_msg
async def connect_agent(clientPort):
uri = f'ws://localhost:{clientPort}'
async with websockets.connect(uri, create_protocol=handleClient3) as websocket:
print("Connected to server at:", clientPort)
client_ports.append(clientPort)
return "Used ports:\n" + '\n'.join(map(str, client_ports))
message = await websocket.recv()
inputMsg = "client: " + handle_message
window['-INPUT-'].print(str(inputMsg) + '\n')
print(message)
return message
async def handleClient3(websocket, path):
return client3_msg
# Function to stop the WebSocket server
def stop_websockets():
global server
if server:
cursor.close()
db.close()
server.close()
print("WebSocket server stopped.")
else:
print("WebSocket server is not running.")
# Start the WebSocket server
async def start_websockets(websocketPort):
uri = f'wss://localhost:{websocketPort}
global server
# Create a WebSocket client that connects to the server
server = await(websockets.serve(handleWebSocket, uri))
server_ports.append(websocketPort)
print(f"Starting WebSocket server on port {websocketPort}...")
return "Used ports:\n" + '\n'.join(map(str, server_ports))
await stop
await server.close()
async def start_client(websocketPort):
uri = f'ws://localhost:{websocketPort}'
while True:
try:
async with websockets.connect(uri) as ws:
print("Connected to server at:", websocketPort)
while True:
message = await ws.recv()
print(message)
response = await askQuestion(message)
print(response)
await ws.send(response)
except websockets.exceptions.ConnectionClosedOK:
print("Connection closed")
continue
async def start_interface():
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Stop WebSocket client'):
break
elif event == 'Start WebSocket server':
websocketPort = get_port(values)
loop = asyncio.get_event_loop()
loop.run_until_complete(start_websockets(websocketPort))
elif event == 'Start WebSocket client':
websocketPort = get_port(values)
loop = asyncio.get_event_loop()
loop.run_until_complete(start_client(websocketPort))
elif event == 'Ask the agent':
question = values['-USERINPUT-']
loop = asyncio.get_event_loop()
loop.run_until_complete(handle_user(question))
elif event == 'Clear Textboxes':
window['-INPUT-'].update('')
window['-OUTPUT-'].update('')
window['-USERINPUT-'].update('')
window.close()
with gr.Blocks() as demo:
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():
userInput = gr.Textbox(label="User Input")
with gr.Row():
Bot = gr.Button("Ask Server")
with gr.Row():
websocketPort = gr.Slider(minimum=1000, maximum=9999, label="Websocket server port", interactive=True, randomize=False)
startServer = gr.Button("Start WebSocket Server")
stopWebsockets = gr.Button("Stop WebSocket Server")
with gr.Row():
port = gr.Textbox()
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()
startServer.click(start_websockets, inputs=websocketPort, outputs=port)
startClient.click(start_client, inputs=clientPort, outputs=[PortInUse, client_msg])
stopWebsockets.click(stop_websockets, inputs=None, outputs=server_msg)
startInterface = gr.Button("Start GUI")
Bot.click(askQuestion, inputs=userInput, outputs=server_msg)
startInterface.click(start_interface, inputs=None, outputs=None)
demo.queue()
demo.launch() |