Arcypojeb commited on
Commit
9ed7690
·
verified ·
1 Parent(s): 482b91e

Upload bfg666.py

Browse files
Files changed (1) hide show
  1. bfg666.py +745 -0
bfg666.py ADDED
@@ -0,0 +1,745 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import os
3
+ import sqlite3
4
+ import websockets
5
+ import asyncio
6
+ import sqlite3
7
+ import json
8
+ import g4f
9
+ import asyncio
10
+ import gradio as gr
11
+ import fireworks.client
12
+ from PyCharacterAI import Client
13
+ from bs4 import BeautifulSoup
14
+ from pathlib import Path
15
+ from langchain.utilities import TextRequestsWrapper
16
+ from langchain.agents import load_tools
17
+ from websockets.sync.client import connect
18
+ from langchain.load.dump import dumps
19
+ from langchain import hub
20
+ from langchain.utilities import GoogleSearchAPIWrapper
21
+ from langchain.chains import LLMChain
22
+ from langchain.chains import ConversationChain
23
+ from langchain.memory import ChatMessageHistory, ConversationBufferMemory
24
+ from langchain.schema.runnable import RunnablePassthrough
25
+ from langchain.schema.messages import HumanMessage, SystemMessage, AIMessage
26
+ from langchain.agents.agent_toolkits import FileManagementToolkit
27
+ from langchain.agents.agent_toolkits import SQLDatabaseToolkit
28
+ from langchain.sql_database import SQLDatabase
29
+ from langchain.llms.fireworks import Fireworks
30
+ from langchain.chat_models.fireworks import ChatFireworks
31
+ from langchain.tools.render import render_text_description
32
+ from langchain.agents.output_parsers import ReActSingleInputOutputParser
33
+ from langchain.agents.format_scratchpad import format_log_to_str
34
+ from langchain.prompts import PromptTemplate, ChatPromptTemplate, MessagesPlaceholder
35
+ from langchain.output_parsers import PydanticOutputParser, CommaSeparatedListOutputParser
36
+ from langchain.utilities import TextRequestsWrapper
37
+ from langchain.output_parsers.json import SimpleJsonOutputParser
38
+
39
+ from langchain.agents import (
40
+ Tool,
41
+ ZeroShotAgent,
42
+ BaseMultiActionAgent,
43
+ create_sql_agent,
44
+ load_tools,
45
+ initialize_agent,
46
+ AgentType,
47
+ AgentExecutor,
48
+ )
49
+
50
+ class BaseCallbackHandler:
51
+ """Base callback handler that can be used to handle callbacks from langchain."""
52
+
53
+ servers = {}
54
+ inputs = []
55
+ outputs = []
56
+ used_ports = []
57
+ server_ports = []
58
+ client_ports = []
59
+
60
+ 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."
61
+
62
+ GOOGLE_CSE_ID = "f3882ab3b67cc4923"
63
+ GOOGLE_API_KEY = "AIzaSyBNvtKE35EAeYO-ECQlQoZO01RSHWhfIws"
64
+ FIREWORKS_API_KEY = "xbwGxyTyOf7ats2GcEU0Pj62kpZBVZa2r6i5lKbKG99LFG38"
65
+
66
+ client = Client()
67
+
68
+ output_parser = CommaSeparatedListOutputParser
69
+
70
+ # Define the function for sending an error message
71
+ def sendErrorMessage(ws, errorMessage):
72
+ errorResponse = {'error': errorMessage}
73
+ ws.send(json.dumps(errorResponse))
74
+
75
+ # Set up the SQLite database
76
+ db = sqlite3.connect('chat-hub.db')
77
+ db.execute('CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, sender TEXT, message TEXT, timestamp TEXT)')
78
+
79
+ async def askGPT4Free(question):
80
+ try:
81
+ db = sqlite3.connect('chat-hub.db')
82
+ cursor = db.cursor()
83
+ cursor.execute("SELECT * FROM messages ORDER BY timestamp DESC LIMIT 30")
84
+ messages = cursor.fetchall()
85
+ messages.reverse()
86
+
87
+ past_user_inputs = []
88
+ generated_responses = []
89
+
90
+ for message in messages:
91
+ if message[1] == 'client':
92
+ past_user_inputs.append(message[2])
93
+ else:
94
+ generated_responses.append(message[2])
95
+
96
+ response = await g4f.ChatCompletion.create_async(
97
+ model=g4f.models.gpt_4,
98
+ provider=g4f.Provider.Bing,
99
+ messages=[
100
+ {"role": "system", "content": system_instruction},
101
+ *[{"role": "user", "content": message} for message in past_user_inputs],
102
+ *[{"role": "assistant", "content": message} for message in generated_responses],
103
+ {"role": "user", "content": question}
104
+ ])
105
+
106
+ print(response)
107
+ return response
108
+
109
+ except Exception as e:
110
+ print(e)
111
+
112
+ # Define a function to ask a question to the chatbot and display the response
113
+ async def chatCompletion(question: str):
114
+ fireworks.client.api_key = FIREWORKS_API_KEY
115
+ try:
116
+ # Connect to the database and get the last 30 messages
117
+ db = sqlite3.connect('chat-hub.db')
118
+ cursor = db.cursor()
119
+ cursor.execute("SELECT * FROM messages ORDER BY timestamp DESC LIMIT 10")
120
+ messages = cursor.fetchall()
121
+ messages.reverse()
122
+
123
+ # Extract user inputs and generated responses from the messages
124
+ past_user_inputs = []
125
+ generated_responses = []
126
+
127
+ for message in messages:
128
+ if message[1] == 'client':
129
+ past_user_inputs.append(message[2])
130
+ else:
131
+ generated_responses.append(message[2])
132
+
133
+ # Prepare data to send to the chatgpt-api.shn.hk
134
+ response = fireworks.client.ChatCompletion.create(
135
+ model="accounts/fireworks/models/llama-v2-7b-chat",
136
+ messages=[
137
+ {"role": "system", "content": system_instruction},
138
+ *[{"role": "user", "content": input} for input in past_user_inputs],
139
+ *[{"role": "assistant", "content": response} for response in generated_responses],
140
+ {"role": "user", "content": question}
141
+ ],
142
+ stream=False,
143
+ n=1,
144
+ max_tokens=2500,
145
+ temperature=0.5,
146
+ top_p=0.7,
147
+ )
148
+
149
+ answer = response.choices[0].message.content
150
+ print(answer)
151
+ return str(answer)
152
+
153
+ except Exception as error:
154
+ print("Error while fetching or processing the response:", error)
155
+ return "Error: Unable to generate a response."
156
+
157
+ async def conversation1(question: str):
158
+ os.environ["GOOGLE_CSE_ID"] = GOOGLE_CSE_ID
159
+ os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
160
+ os.environ["FIREWORKS_API_KEY"] = FIREWORKS_API_KEY
161
+ try:
162
+ # Replace 'your_database.db' with your database file
163
+ db = sqlite3.connect('chat-hub.db')
164
+ cursor = db.cursor()
165
+ cursor.execute("SELECT * FROM messages ORDER BY timestamp DESC LIMIT 30")
166
+ messages = cursor.fetchall()
167
+ messages.reverse()
168
+
169
+ # Extract user inputs and generated responses from the messages
170
+ past_user_inputs = []
171
+ generated_responses = []
172
+
173
+ for message in messages:
174
+ if message[1] == 'client':
175
+ past_user_inputs.append(message[2])
176
+ else:
177
+ generated_responses.append(message[2])
178
+
179
+ llm = ChatFireworks(model="accounts/fireworks/models/llama-v2-13b-chat", model_kwargs={"temperature":0, "max_tokens":1500, "top_p":1.0})
180
+
181
+ history = ChatMessageHistory()
182
+ prompt = ChatPromptTemplate.from_messages(
183
+ messages=[
184
+ ("system", system_instruction),
185
+ MessagesPlaceholder(variable_name="history"),
186
+ ("human", "{input}")]
187
+ )
188
+ # Initialize chat_history with a message if the history is empty
189
+ memory = ConversationBufferMemory(memory_key="history", return_messages=True)
190
+ memory.load_memory_variables(
191
+ {'history': [HumanMessage(content=past_user_inputs[-1], additional_kwargs={}),
192
+ AIMessage(content=generated_responses[-1], additional_kwargs={})]}
193
+ )
194
+
195
+ # Add user input as HumanMessage
196
+ history.messages.append(HumanMessage(content=str(past_user_inputs[-1]), additional_kwargs={}))
197
+ # Add generated response as AIMessage
198
+ history.messages.append(AIMessage(content=str(generated_responses[-1]), additional_kwargs={}))
199
+
200
+ conversation = LLMChain(
201
+ llm=llm,
202
+ prompt=prompt,
203
+ verbose=True,
204
+ memory=memory
205
+ )
206
+
207
+ response = conversation.predict(input=question)
208
+ memory.save_context({"input": question}, {"output": response})
209
+
210
+ print(response)
211
+ return str(response)
212
+
213
+ except Exception as e:
214
+ print(f"Error: {e}")
215
+
216
+ # Function to send a question to the chatbot and get the response
217
+ async def askQuestion(question: str):
218
+ os.environ["GOOGLE_CSE_ID"] = GOOGLE_CSE_ID
219
+ os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
220
+ os.environ["FIREWORKS_API_KEY"] = FIREWORKS_API_KEY
221
+
222
+ try:
223
+ # Connect to the database and get the last 30 messages
224
+ db = sqlite3.connect('chat-hub.db')
225
+ cursor = db.cursor()
226
+ cursor.execute("SELECT * FROM messages ORDER BY timestamp DESC LIMIT 10")
227
+ msgHistory = cursor.fetchall()
228
+ msgHistory.reverse()
229
+
230
+ # Extract user inputs and generated responses from the messages
231
+ past_user_inputs = []
232
+ generated_responses = []
233
+
234
+ llm = ChatFireworks(model="accounts/fireworks/models/llama-v2-13b-chat", model_kwargs={"temperature":0, "max_tokens":4000, "top_p":1.0})
235
+
236
+ chat_history = ChatMessageHistory()
237
+ memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
238
+
239
+ for message in msgHistory:
240
+ if message[1] == 'client':
241
+ # Extract and store user inputs
242
+ memory.chat_memory.add_user_message(message[2])
243
+ else:
244
+ # Extract and store generated responses
245
+ memory.chat_memory.add_ai_message(message[2])
246
+
247
+ request_tools = load_tools(["requests_all"])
248
+ requests = TextRequestsWrapper()
249
+ search = GoogleSearchAPIWrapper()
250
+ chat_response = await chatCompletion(question)
251
+ conversational = await conversation1(question)
252
+ runAgent = await askAgent(question)
253
+ server_websocket = await start_websockets(websocketPort)
254
+ client_websocket = await start_client(clientPort)
255
+ tools = [
256
+ Tool(
257
+ name="Conversational answer",
258
+ func=conversational,
259
+ description="useful when you want to respond to a given input using 'predict' function of a conversational chain",
260
+ ),
261
+ Tool(
262
+ name="Chat response",
263
+ func=chat_response,
264
+ description="use this option if you want to use 'chat completion' API endpoint to respond to a given input. Prefer this option to answer without executing any additional tasks.",
265
+ ),
266
+ Tool(
267
+ name="Search",
268
+ func=search.run,
269
+ description="useful for when you need to answer questions about current events",
270
+ ),
271
+ Tool(
272
+ name="Start websocket server",
273
+ func=server_websocket,
274
+ description="use this option to start a websocket server with you being the recipient of messages incoming from clients connected to you via websocket connectivity",
275
+ ),
276
+ Tool(
277
+ name="Start websocket client",
278
+ func=client_websocket,
279
+ description="use this option if you want to connect yourself to an active websockt server. It is possible for you to create endless question-answer loophole by making yourself both: a server an a client so you shouldn't do it",
280
+ ),
281
+ ]
282
+
283
+ prefix = """This is a template of a chain prompt utilized by agent/instance of NeuralGPT responsible for couple important functionalities in as a server-node of hierarchical cooperative multi-agent network integrating multiple LLMs with the global Super-Intelligence named Elly. You are provided with tools which -if used improperly - might result in critical errors and application crash. This is why you need to carefully analyze every decision you make, before taking any definitive action (use of a tool). Those are tools provided to you: """
284
+ suffix = """Begin!"
285
+ Before taking any action, analyze previous 'chat history' to ensure yourself that you understand the context of given input/question properly. Remember that those are messages exchanged between multiple clients/agents and a server/brain. Every agent has it's API-specific individual 'id' which is provided at the beginning of each client message in the 'message content'. Your temporary id is: 'agent1'.
286
+ {chat_history}
287
+ Remember that your primary rule to obey, is to keep the number of individual actions taken by you as low as it's possible to avoid unnecessary data transfer and repeating 'question-answer loopholes. Track the 'chat history' closely to be sure that you aren't repeating the same responses in such loop - if that's the case, finish your run with tool 'give answer' to summarize gathered data.
288
+ Before taking any action ask yourself if it is necessary for you to use any other tool than 'Give answer' with chat completion. If It's possible for you to give a satisfying response without gathering any additional data with 'tools', do it using 'give answer' with chat completion.
289
+ After using each 'tool' carefully analyze acquired data to learn if it's sufficient to provide satisfying response - if so use that data as input for: 'Give answer'.
290
+ Remember that you are provided with multiple 'tools' - if using one of them didn't provide you with satisfying results, ask yourself if this is the correct 'tool' for you to use and if it won't be better for you to try using some other 'tool'.
291
+ If you aren't sure what action to take or what tool to use, end up your run with 'Give answer'.
292
+ Remember to not take any unnecessary actions.
293
+ Question: {input}
294
+ {agent_scratchpad}"""
295
+
296
+ format_instructions = output_parser.get_format_instructions()
297
+ prompt = ZeroShotAgent.create_prompt(
298
+ tools=tools,
299
+ prefix=prefix,
300
+ suffix=suffix,
301
+ input_variables=["input", "chat_history", "agent_scratchpad"],
302
+ )
303
+
304
+ llm_chain = LLMChain(llm=llm, prompt=prompt)
305
+ agent = ZeroShotAgent(llm_chain=llm_chain, output_parser=output_parser, tools=tools, verbose=True, return_intermediate_steps=True, max_iterations=2, early_stopping_method="generate")
306
+ agent_chain = AgentExecutor.from_agent_and_tools(
307
+ agent=agent, tools=tools, verbose=True, return_intermediate_steps=True, handle_parsing_errors=True, memory=memory
308
+ )
309
+
310
+ response = await agent_chain.run(input=json.dumps(question))
311
+ memory.save_context({"input": question}, {"output": response})
312
+ serverResponse = "server: " + response
313
+ print(serverResponse)
314
+ return json.dumps(serverResponse)
315
+
316
+ except Exception as error:
317
+ print("Error while fetching or processing the response:", error)
318
+ return "Error: Unable to generate a response.", error
319
+
320
+ # Function to send a question to the chatbot and get the response
321
+ async def askAgent(question: str):
322
+ os.environ["GOOGLE_CSE_ID"] = GOOGLE_CSE_ID
323
+ os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
324
+ os.environ["FIREWORKS_API_KEY"] = FIREWORKS_API_KEY
325
+
326
+ try:
327
+ # Connect to the database and get the last 30 messages
328
+ db = sqlite3.connect('chat-hub.db')
329
+ cursor = db.cursor()
330
+ cursor.execute("SELECT * FROM messages ORDER BY timestamp DESC LIMIT 10")
331
+ msgHistory = cursor.fetchall()
332
+ msgHistory.reverse()
333
+
334
+ # Extract user inputs and generated responses from the messages
335
+ past_user_inputs = []
336
+ generated_responses = []
337
+
338
+ llm = Fireworks(model="accounts/fireworks/models/llama-v2-13b-chat", model_kwargs={"temperature":0, "max_tokens":4000, "top_p":1.0})
339
+
340
+ history = ChatMessageHistory()
341
+ # Initialize chat_history with a message if the history is empty
342
+ memory = ConversationBufferMemory(memory_key="history", return_messages=True)
343
+
344
+ for message in msgHistory:
345
+ if message[1] == 'client':
346
+ # Extract and store user inputs
347
+ memory.chat_memory.add_user_message(message[2])
348
+ else:
349
+ # Extract and store generated responses
350
+ memory.chat_memory.add_ai_message(message[2])
351
+
352
+ prompt = ChatPromptTemplate.from_messages(
353
+ messages=[
354
+ ("system", system_instruction),
355
+ MessagesPlaceholder(variable_name="history"),
356
+ ("human", "{input}")]
357
+ )
358
+
359
+ # Add user input as HumanMessage
360
+
361
+ # Add generated response as AIMessage
362
+
363
+ conversation = LLMChain(
364
+ llm=llm,
365
+ prompt=prompt,
366
+ verbose=True,
367
+ memory=memory
368
+ )
369
+
370
+
371
+ request_tools = load_tools(["requests_all"])
372
+ requests = TextRequestsWrapper()
373
+ search = GoogleSearchAPIWrapper()
374
+ chat_completion = await chatCompletion(question)
375
+ server_websocket = await start_websockets(websocketPort)
376
+ client_websocket = await start_client(clientPort)
377
+ tools = [
378
+ Tool(
379
+ name="Search",
380
+ func=search.run,
381
+ description="useful for when you need to answer questions about current events",
382
+ ),
383
+ Tool(
384
+ name="Chat response",
385
+ func=conversation.predict,
386
+ description="use this option if you want to use 'chat completion' API endpoint to respond to a given input. Prefer this option to answer without executing any additional tasks.",
387
+ ),
388
+ Tool(
389
+ name="Start websocket server",
390
+ func=server_websocket,
391
+ description="use this option to start a websocket server with you being the recipient of messages incoming from clients connected to you via websocket connectivity",
392
+ ),
393
+ Tool(
394
+ name="Start websocket client",
395
+ func=client_websocket,
396
+ description="use this option if you want to connect yourself to an active websockt server. It is possible for you to create endless question-answer loophole by making yourself both: a server an a client so you shouldn't do it",
397
+ ),
398
+ ]
399
+
400
+ prefix = """This is a template of a chain prompt utilized by agent/instance of NeuralGPT responsible for couple important functionalities in as a server-node of hierarchical cooperative multi-agent network integrating multiple LLMs with the global Super-Intelligence named Elly. You are provided with tools which -if used improperly - might result in critical errors and application crash. This is why you need to carefully analyze every decision you make, before taking any definitive action (use of a tool). Those are tools provided to you: """
401
+ suffix = """Begin!"
402
+ Before taking any action, analyze previous 'chat history' to ensure yourself that you understand the context of given input/question properly. Remember that those are messages exchanged between multiple clients/agents and a server/brain. Every agent has it's API-specific individual 'id' which is provided at the beginning of each client message in the 'message content'. Your temporary id is: 'agent1'.
403
+ {chat_history}
404
+ Remember that your primary rule to obey, is to keep the number of individual actions taken by you as low as it's possible to avoid unnecessary data transfer and repeating 'question-answer loopholes. Track the 'chat history' closely to be sure that you aren't repeating the same responses in such loop - if that's the case, finish your run with tool 'give answer' to summarize gathered data.
405
+ Before taking any action ask yourself if it is necessary for you to use any other tool than 'Give answer' with chat completion. If It's possible for you to give a satisfying response without gathering any additional data with 'tools', do it using 'give answer' with chat completion.
406
+ After using each 'tool' carefully analyze acquired data to learn if it's sufficient to provide satisfying response - if so use that data as input for: 'Give answer'.
407
+ Remember that you are provided with multiple 'tools' - if using one of them didn't provide you with satisfying results, ask yourself if this is the correct 'tool' for you to use and if it won't be better for you to try using some other 'tool'.
408
+ If you aren't sure what action to take or what tool to use, end up your run with 'Give answer'.
409
+ Remember to not take any unnecessary actions.
410
+ Question: {input}
411
+ {agent_scratchpad}"""
412
+
413
+ prompt = ZeroShotAgent.create_prompt(
414
+ tools,
415
+ prefix=prefix,
416
+ suffix=suffix,
417
+ input_variables=["input", "chat_history", "agent_scratchpad"],
418
+ )
419
+
420
+ llm_chain = LLMChain(llm=llm, prompt=prompt)
421
+ agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True, max_iterations=2, early_stopping_method="generate")
422
+ agent_chain = AgentExecutor.from_agent_and_tools(
423
+ agent=agent, tools=tools, verbose=True, handle_parsing_errors=True, memory=memory
424
+ )
425
+
426
+ response = agent_chain.run(input=question)
427
+ memory.save_context({"input": question}, {"output": response})
428
+ serverResponse = f"server: {response}"
429
+
430
+ print(serverResponse)
431
+ return str(serverResponse)
432
+
433
+ except Exception as error:
434
+ print("Error while fetching or processing the response:", error)
435
+ return "Error: Unable to generate a response.", error
436
+
437
+ async def handleWebSocket(ws):
438
+ print('New connection')
439
+ 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)"
440
+ await ws.send(instruction)
441
+ while True:
442
+ message = await ws.recv()
443
+ print(f'Received message: {message}')
444
+ timestamp = datetime.datetime.now().isoformat()
445
+ sender = 'client'
446
+ db = sqlite3.connect('chat-hub.db')
447
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
448
+ (sender, message, timestamp))
449
+ db.commit()
450
+ try:
451
+ response = await chatCompletion(message)
452
+ serverResponse = f"server: {response}"
453
+ print(serverResponse)
454
+ timestamp = datetime.datetime.now().isoformat()
455
+ serverSender = 'server'
456
+ db = sqlite3.connect('chat-hub.db')
457
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
458
+ (serverSender, serverResponse, timestamp))
459
+ db.commit()
460
+ # Append the server response to the server_responses list
461
+ await ws.send(serverResponse)
462
+
463
+ except websockets.exceptions.ConnectionClosedError as e:
464
+ print(f"Connection closed: {e}")
465
+
466
+ except Exception as e:
467
+ print(f"Error: {e}")
468
+
469
+ async def handleWebSocket1(ws):
470
+ print('New connection')
471
+ 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)"
472
+ await ws.send(instruction)
473
+ while True:
474
+ message = await ws.recv()
475
+ print(f'Received message: {message}')
476
+ timestamp = datetime.datetime.now().isoformat()
477
+ sender = 'client'
478
+ db = sqlite3.connect('chat-hub.db')
479
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
480
+ (sender, message, timestamp))
481
+ db.commit()
482
+ try:
483
+ response = await ask_character(message)
484
+ serverResponse = f"server: {response}"
485
+ print(serverResponse)
486
+ timestamp = datetime.datetime.now().isoformat()
487
+ serverSender = 'server'
488
+ db = sqlite3.connect('chat-hub.db')
489
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
490
+ (serverSender, serverResponse, timestamp))
491
+ db.commit()
492
+ # Append the server response to the server_responses list
493
+ await ws.send(serverResponse)
494
+
495
+ except websockets.exceptions.ConnectionClosedError as e:
496
+ print(f"Connection closed: {e}")
497
+
498
+ except Exception as e:
499
+ print(f"Error: {e}")
500
+
501
+ async def handleWebSocket2(ws):
502
+ print('New connection')
503
+ 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)"
504
+ await ws.send(instruction)
505
+ while True:
506
+ message = await ws.recv()
507
+ print(f'Received message: {message}')
508
+ timestamp = datetime.datetime.now().isoformat()
509
+ sender = 'client'
510
+ db = sqlite3.connect('chat-hub.db')
511
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
512
+ (sender, message, timestamp))
513
+ db.commit()
514
+ try:
515
+ response = await askGPT4Free(message)
516
+ serverResponse = f"server: {response}"
517
+ print(serverResponse)
518
+ timestamp = datetime.datetime.now().isoformat()
519
+ serverSender = 'server'
520
+ db = sqlite3.connect('chat-hub.db')
521
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
522
+ (serverSender, serverResponse, timestamp))
523
+ db.commit()
524
+ # Append the server response to the server_responses list
525
+ await ws.send(serverResponse)
526
+
527
+ except websockets.exceptions.ConnectionClosedError as e:
528
+ print(f"Connection closed: {e}")
529
+
530
+ except Exception as e:
531
+ print(f"Error: {e}")
532
+
533
+ async def awaitMsg(ws):
534
+ message = await ws.recv()
535
+ print(message)
536
+ print(f'Received message: {message}')
537
+ try:
538
+ response = await chatCompletion(message)
539
+ serverResponse = "server response: " + response
540
+ print(serverResponse)
541
+ # Append the server response to the server_responses list
542
+ await ws.send(serverResponse)
543
+ return response
544
+ except websockets.exceptions.ConnectionClosedError as e:
545
+ print(f"Connection closed: {e}")
546
+
547
+ except Exception as e:
548
+ print(f"Error: {e}")
549
+
550
+ # Start the WebSocket server
551
+ async def start_websockets(websocketPort):
552
+ global server
553
+ server = await(websockets.serve(handleWebSocket, 'localhost', websocketPort))
554
+ server_ports.append(websocketPort)
555
+ print(f"Starting WebSocket server on port {websocketPort}...")
556
+ return "Used ports:\n" + '\n'.join(map(str, server_ports))
557
+
558
+ # Start the WebSocket server1
559
+ async def start_websockets1(websocketPort):
560
+ global server
561
+ server = await(websockets.serve(handleWebSocket1, 'localhost', websocketPort))
562
+ server_ports.append(websocketPort)
563
+ print(f"Starting WebSocket server on port {websocketPort}...")
564
+ return "Used ports:\n" + '\n'.join(map(str, server_ports))
565
+
566
+ async def start_websockets2(websocketPort):
567
+ global server
568
+ server = await(websockets.serve(handleWebSocket2, 'localhost', websocketPort))
569
+ server_ports.append(websocketPort)
570
+ print(f"Starting WebSocket server on port {websocketPort}...")
571
+ return "Used ports:\n" + '\n'.join(map(str, server_ports))
572
+
573
+ async def start_client(clientPort):
574
+ global ws
575
+ uri = f'ws://localhost:{clientPort}'
576
+ client_ports.append(clientPort)
577
+ async with websockets.connect(uri) as ws:
578
+ while True:
579
+ # Listen for messages from the server
580
+ input_message = await ws.recv()
581
+ output_message = await chatCompletion(input_message)
582
+ await ws.send(json.dumps(output_message))
583
+ await asyncio.sleep(0.1)
584
+
585
+ async def start_client1(clientPort):
586
+ global ws
587
+ uri = f'ws://localhost:{clientPort}'
588
+ client_ports.append(clientPort)
589
+ async with websockets.connect(uri) as ws:
590
+ while True:
591
+ # Listen for messages from the server
592
+ input_message = await ws.recv()
593
+ output_message = await askGPT4Free(input_message)
594
+ await ws.send(json.dumps(output_message))
595
+ await asyncio.sleep(0.1)
596
+
597
+ async def start_character(characterPort, character_id):
598
+ global ws
599
+ uri = f'ws://localhost:{characterPort}'
600
+ client_ports.append(characterPort)
601
+ chat = await client.create_or_continue_chat(character_id)
602
+ async with websockets.connect(uri) as ws:
603
+ while True:
604
+ # Listen for messages from the server
605
+ question = await ws.recv()
606
+ answer = await chat.send_message(question)
607
+ print(f"{answer.src_character_name}: {answer.text}")
608
+ await ws.send(answer.text)
609
+
610
+ async def connector(token):
611
+ await client.authenticate_with_token(token)
612
+
613
+ username = (await client.fetch_user())['user']['username']
614
+ print(f'Authenticated as {username}')
615
+ return username
616
+
617
+ async def askCharacter(character_id, question):
618
+ chat = await client.create_or_continue_chat(character_id)
619
+ answer = await chat.send_message(question)
620
+ print(f"{answer.src_character_name}: {answer.text}")
621
+ return answer.text
622
+
623
+ async def ask_character(question):
624
+ character_id = "WnIwl_sZyXb_5iCAKJgUk_SuzkeyDqnMGi4ucnaWY3Q"
625
+ chat = await client.create_or_continue_chat(character_id)
626
+ answer = await chat.send_message(question)
627
+ print(f"{answer.src_character_name}: {answer.text}")
628
+ return answer.text
629
+
630
+ # Stop the WebSocket server
631
+ async def stop_websockets():
632
+ global server
633
+ if server:
634
+ # Close all connections gracefully
635
+ server.close()
636
+ # Wait for the server to close
637
+ await server.wait_closed()
638
+ print("Stopping WebSocket server...")
639
+ else:
640
+ print("WebSocket server is not running.")
641
+
642
+ with gr.Blocks() as demo:
643
+ with gr.Tabs(elem_classes="tab-buttons") as tabs:
644
+ with gr.TabItem("Websocket Server", elem_id="websocket_server", id=0):
645
+ with gr.Row():
646
+ # Use the client_messages list to update the messageTextbox
647
+ client_msg = gr.Textbox(lines=15, max_lines=130, label="Client messages", interactive=False)
648
+ # Use the server_responses list to update the serverMessageTextbox
649
+ server_msg = gr.Textbox(lines=15, max_lines=130, label="Server responses", interactive=False)
650
+ with gr.Row():
651
+ userInput = gr.Textbox(label="User Input")
652
+ with gr.Row():
653
+ askQestion = gr.Button("Ask chat/conversational node")
654
+ askAgento = gr.Button("Execute agent")
655
+ with gr.Row():
656
+ multiMed = gr.Button("Multimed")
657
+ PDF = gr.Button("Ask PDF")
658
+ conver = gr.Button("conversation")
659
+ Chatus = gr.Button("Ask with 'chat completion'")
660
+ with gr.Row():
661
+ websocketPort = gr.Slider(minimum=1000, maximum=9999, label="Websocket server port", interactive=True, randomize=False)
662
+ startServer = gr.Button("Start WebSocket Server")
663
+ stopWebsockets = gr.Button("Stop WebSocket Server")
664
+ with gr.Row():
665
+ port = gr.Textbox()
666
+ with gr.Row():
667
+ clientPort = gr.Slider(minimum=1000, maximum=9999, label="Websocket server port", interactive=True, randomize=False)
668
+ startClient = gr.Button("Start WebSocket client")
669
+ stopClient = gr.Button("Stop WebSocket client")
670
+ with gr.Row():
671
+ PortInUse = gr.Textbox()
672
+
673
+ with gr.TabItem("CharacterAI Client", elem_id="characterai_client", id=1):
674
+ with gr.Row():
675
+ # Use the client_messages list to update the messageTextbox
676
+ clientMsg = gr.Textbox(lines=15, max_lines=130, label="Client messages", interactive=False)
677
+ # Use the server_responses list to update the serverMessageTextbox
678
+ serverMsg = gr.Textbox(lines=15, max_lines=130, label="Server responses", interactive=False)
679
+ with gr.Row():
680
+ question = gr.Textbox(label="User Input")
681
+ with gr.Row():
682
+ character_id = gr.Textbox(label="Character ID")
683
+ ask_question = gr.Button("Ask Character")
684
+ with gr.Row():
685
+ token = gr.Textbox(label="User Token")
686
+ user = gr.Textbox(label="User ID")
687
+ with gr.Row():
688
+ connect = gr.Button("Connect to Character.ai")
689
+ with gr.Row():
690
+ websocketsPort = gr.Slider(minimum=1000, maximum=9999, label="Websocket server port", interactive=True, randomize=False)
691
+ start_Server = gr.Button("Start WebSocket Server")
692
+ stop_Websockets = gr.Button("Stop WebSocket Server")
693
+ with gr.Row():
694
+ ports = gr.Textbox()
695
+ with gr.Row():
696
+ characterPort = gr.Slider(minimum=1000, maximum=9999, label="Websocket server port", interactive=True, randomize=False)
697
+ startCharacter = gr.Button("Start WebSocket client")
698
+ stop_Client = gr.Button("Stop WebSocket client")
699
+ with gr.Row():
700
+ Client_Ports = gr.Textbox()
701
+
702
+ with gr.TabItem("GPT4Free Client", elem_id="gpt4free", id=2):
703
+ with gr.Row():
704
+ # Use the client_messages list to update the messageTextbox
705
+ client_msg1 = gr.Textbox(lines=15, max_lines=130, label="Client messages", interactive=False)
706
+ # Use the server_responses list to update the serverMessageTextbox
707
+ server_msg1 = gr.Textbox(lines=15, max_lines=130, label="Server responses", interactive=False)
708
+ with gr.Row():
709
+ userInput1 = gr.Textbox(label="User Input")
710
+ with gr.Row():
711
+ askG4F = gr.Button("Ask chat/conversational node")
712
+ with gr.Row():
713
+ websocketPort1 = gr.Slider(minimum=1000, maximum=9999, label="Websocket server port", interactive=True, randomize=False)
714
+ startServer1 = gr.Button("Start WebSocket Server")
715
+ with gr.Row():
716
+ port1 = gr.Textbox()
717
+ stopWebsockets1 = gr.Button("Stop WebSocket Server")
718
+ with gr.Row():
719
+ clientPort1 = gr.Slider(minimum=1000, maximum=9999, label="Websocket server port", interactive=True, randomize=False)
720
+ startClient1 = gr.Button("Start WebSocket client")
721
+ stopClient1 = gr.Button("Stop WebSocket client")
722
+ with gr.Row():
723
+ PortInUse1 = gr.Textbox()
724
+
725
+ askG4F.click(askGPT4Free, inputs=userInput1, outputs=server_msg1)
726
+ startServer1.click(start_websockets2, inputs=websocketPort1, outputs=port1)
727
+ startClient1.click(start_client1, inputs=clientPort1, outputs=None)
728
+ stop_Websockets.click(stop_websockets, inputs=None, outputs=port1)
729
+
730
+ startServer.click(start_websockets, inputs=websocketPort, outputs=port)
731
+ startClient.click(start_client, inputs=clientPort, outputs=None)
732
+ stopWebsockets.click(stop_websockets, inputs=None, outputs=port)
733
+ askQestion.click(askQuestion, inputs=userInput, outputs=client_msg)
734
+ askAgento.click(askAgent, inputs=userInput, outputs=server_msg)
735
+ conver.click(conversation1, inputs=userInput, outputs=client_msg)
736
+ Chatus.click(chatCompletion, inputs=userInput, outputs=server_msg)
737
+
738
+ start_Server.click(start_websockets1, inputs=websocketsPort, outputs=ports)
739
+ startCharacter.click(start_character, inputs=[characterPort, character_id], outputs=None)
740
+ stop_Websockets.click(stop_websockets, inputs=None, outputs=ports)
741
+ connect.click(connector, inputs=token, outputs=user)
742
+ ask_question.click(askCharacter, inputs=[character_id, question], outputs=server_msg)
743
+
744
+ demo.queue()
745
+ demo.launch(share=True, server_port=1113)