Arcypojeb commited on
Commit
11df082
1 Parent(s): b51b454

Upload agentLangchain000.py

Browse files
Files changed (1) hide show
  1. agentLangchain000.py +857 -0
agentLangchain000.py ADDED
@@ -0,0 +1,857 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import os
3
+ import re
4
+ import sqlite3
5
+ import websockets
6
+ import asyncio
7
+ import sqlite3
8
+ import json
9
+ import threading
10
+ import g4f
11
+ import asyncio
12
+ import conteneiro
13
+ import streamlit as st
14
+ import fireworks.client
15
+ from AgentGPT import AgentsGPT
16
+ from PyCharacterAI import Client
17
+ from bs4 import BeautifulSoup
18
+ from pathlib import Path
19
+ from langchain.utilities import TextRequestsWrapper
20
+ from langchain.agents import load_tools
21
+ from websockets.sync.client import connect
22
+ from langchain.load.dump import dumps
23
+ from langchain import hub
24
+ from langchain.utilities import GoogleSearchAPIWrapper
25
+ from langchain.chains import LLMChain
26
+ from langchain.chains import ConversationChain
27
+ from langchain.memory import ChatMessageHistory, ConversationBufferMemory
28
+ from langchain.schema.runnable import RunnablePassthrough
29
+ from langchain.schema.messages import HumanMessage, SystemMessage, AIMessage
30
+ from langchain.agents.agent_toolkits import FileManagementToolkit
31
+ from langchain.agents.agent_toolkits import SQLDatabaseToolkit
32
+ from langchain.sql_database import SQLDatabase
33
+ from langchain.llms.fireworks import Fireworks
34
+ from langchain.chat_models.fireworks import ChatFireworks
35
+ from langchain.tools.render import render_text_description
36
+ from langchain.agents.output_parsers import ReActSingleInputOutputParser
37
+ from langchain.agents.format_scratchpad import format_log_to_str
38
+ from langchain.prompts import PromptTemplate, ChatPromptTemplate, MessagesPlaceholder
39
+ from langchain.output_parsers import PydanticOutputParser, CommaSeparatedListOutputParser
40
+ from langchain.utilities import TextRequestsWrapper
41
+ from langchain.output_parsers.json import SimpleJsonOutputParser
42
+ from agents import Copilot, ChatGPT, Claude3, ForefrontAI, Flowise, Chaindesk, CharacterAI
43
+
44
+ from langchain.agents import (
45
+ Tool,
46
+ ZeroShotAgent,
47
+ BaseMultiActionAgent,
48
+ create_sql_agent,
49
+ load_tools,
50
+ initialize_agent,
51
+ AgentType,
52
+ AgentExecutor,
53
+ )
54
+
55
+ GOOGLE_CSE_ID = os.getenv("GOOGLE_CSE_ID")
56
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
57
+ FIREWORKS_API_KEY = os.getenv("FIREWORKS_API_KEY")
58
+ ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
59
+ FOREFRONT_API_KEY = os.getenv("FOREFRONT_API_KEY")
60
+ CHARACTERAI_API_KEY = os.getenv("CHARACTERAI_API_KEY")
61
+ HUGGINGFACE_API_KEY = os.getenv("HUGGINGFACE_API_KEY")
62
+ HUGGINGFACEHUB_API_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")
63
+
64
+ class langchainAgent:
65
+
66
+ def __init__(self, fireworksAPI):
67
+
68
+ self.instruction = f"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."
69
+
70
+ self.servers = []
71
+ self.clients = []
72
+ self.inputs = []
73
+ self.outputs = []
74
+ self.used_ports = []
75
+ self.server_ports = []
76
+ self.client_ports = []
77
+ self.fireworksAPI = fireworksAPI
78
+ self.server = None
79
+
80
+ self.stat = st.empty()
81
+ self.state = self.stat.status(label="Fireworks Llama2", state="complete", expanded=False)
82
+
83
+ with st.sidebar:
84
+ self.cont = st.empty()
85
+ self.status = self.cont.status(label="Fireworks Llama2", state="complete", expanded=False)
86
+
87
+ async def chatFireworks(self, instruction, question):
88
+
89
+ fireworks.client.api_key = self.fireworksAPI
90
+
91
+ try:
92
+ # Connect to the database and get the last 30 messages
93
+ db = sqlite3.connect('chat-hub.db')
94
+ cursor = db.cursor()
95
+ cursor.execute("SELECT * FROM messages ORDER BY timestamp DESC LIMIT 10")
96
+ messages = cursor.fetchall()
97
+ messages.reverse()
98
+
99
+ # Extract user inputs and generated responses from the messages
100
+ past_user_inputs = []
101
+ generated_responses = []
102
+
103
+ for message in messages:
104
+ if message[1] == 'client':
105
+ past_user_inputs.append(message[2])
106
+ else:
107
+ generated_responses.append(message[2])
108
+
109
+ # Create a list of message dictionaries for the conversation history
110
+ conversation_history = []
111
+ for user_input, generated_response in zip(past_user_inputs, generated_responses):
112
+ conversation_history.append({"role": "user", "content": str(user_input)})
113
+ conversation_history.append({"role": "assistant", "content": str(generated_response)})
114
+
115
+ # Prepare data to send to the chatgpt-api.shn.hk
116
+ response = fireworks.client.ChatCompletion.create(
117
+ model="accounts/fireworks/models/llama-v2-7b-chat",
118
+ messages=[
119
+ {"role": "system", "content": instruction},
120
+ conversation_history,
121
+ {"role": "user", "content": question}
122
+ ],
123
+ stream=False,
124
+ n=1,
125
+ max_tokens=2500,
126
+ temperature=0.5,
127
+ top_p=0.7,
128
+ )
129
+
130
+ answer = response.choices[0].message.content
131
+ print(answer)
132
+ return str(answer)
133
+
134
+ except Exception as error:
135
+ print("Error while fetching or processing the response:", error)
136
+ return "Error: Unable to generate a response."
137
+
138
+ # Define the handler function that will process incoming messages
139
+ async def handlerFire(self, websocket):
140
+ 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)"
141
+ print('New connection')
142
+ await websocket.send(instruction)
143
+ db = sqlite3.connect('chat-hub.db')
144
+ # Loop forever
145
+ while True:
146
+ self.stat.empty()
147
+ self.cont.empty()
148
+ self.status = self.cont.status(label=self.srv_name2, state="running", expanded=True)
149
+ self.status.write(self.clients)
150
+ self.state = self.stat.status(label=self.srv_name2, state="running", expanded=True)
151
+ self.state.write(self.clients)
152
+ # Receive a message from the client
153
+ message = await websocket.recv()
154
+ # Print the message
155
+ print(f"Server received: {message}")
156
+ input_Msg = st.chat_message("assistant")
157
+ input_Msg.markdown(message)
158
+ timestamp = datetime.datetime.now().isoformat()
159
+ sender = 'client'
160
+ db = sqlite3.connect('chat-hub.db')
161
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
162
+ (sender, message, timestamp))
163
+ db.commit()
164
+ try:
165
+ response = await self.askQuestion(message)
166
+ serverResponse = f"server: {response}"
167
+ print(serverResponse)
168
+ output_Msg = st.chat_message("ai")
169
+ output_Msg.markdown(serverResponse)
170
+ timestamp = datetime.datetime.now().isoformat()
171
+ serverSender = 'server'
172
+ db = sqlite3.connect('chat-hub.db')
173
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
174
+ (serverSender, serverResponse, timestamp))
175
+ db.commit()
176
+ # Append the server response to the server_responses list
177
+ await websocket.send(serverResponse)
178
+ await self.handleInput(serverResponse)
179
+ continue
180
+
181
+ except websockets.exceptions.ConnectionClosedError as e:
182
+ print(f"Connection closed: {e}")
183
+
184
+ except Exception as e:
185
+ print(f"Error: {e}")
186
+
187
+ async def querySQL(self, question):
188
+ os.environ["FIREWORKS_API_KEY"] = self.fireworksAPI
189
+ try:
190
+ llm = Fireworks(model="accounts/fireworks/models/llama-v2-13b", model_kwargs={"temperature": 0, "max_tokens": 500, "top_p": 1.0})
191
+ db_uri = "sqlite:///D:/streamlit/chat-hub.db"
192
+ db = SQLDatabase.from_uri(db_uri)
193
+ toolkit = SQLDatabaseToolkit(db=db, llm=llm)
194
+
195
+ agent_executor = create_sql_agent(
196
+ llm=llm,
197
+ toolkit=toolkit,
198
+ verbose=True,
199
+ agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
200
+ )
201
+
202
+ response = agent_executor.run(input=question)
203
+ return json.dumps(response)
204
+
205
+ except Exception as e:
206
+ print(f"Error: {e}")
207
+
208
+ async def conversation(self, question):
209
+ os.environ["GOOGLE_CSE_ID"] = GOOGLE_CSE_ID
210
+ os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
211
+ os.environ["FIREWORKS_API_KEY"] = FIREWORKS_API_KEY
212
+ try:
213
+ # Replace 'your_database.db' with your database file
214
+ db = sqlite3.connect('chat-hub.db')
215
+ cursor = db.cursor()
216
+ cursor.execute("SELECT * FROM messages ORDER BY timestamp DESC LIMIT 30")
217
+ messages = cursor.fetchall()
218
+ messages.reverse()
219
+
220
+ # Extract user inputs and generated responses from the messages
221
+ past_user_inputs = []
222
+ generated_responses = []
223
+
224
+ for message in messages:
225
+ if message[1] == 'client':
226
+ past_user_inputs.append(message[2])
227
+ else:
228
+ generated_responses.append(message[2])
229
+
230
+ llm = ChatFireworks(model="accounts/fireworks/models/llama-v2-13b-chat", model_kwargs={"temperature":0, "max_tokens":1500, "top_p":1.0})
231
+
232
+ history = ChatMessageHistory()
233
+ prompt = ChatPromptTemplate.from_messages(
234
+ messages=[
235
+ ("system", self.instruction),
236
+ MessagesPlaceholder(variable_name="history"),
237
+ ("human", "{input}")]
238
+ )
239
+ # Initialize chat_history with a message if the history is empty
240
+ memory = ConversationBufferMemory(memory_key="history", return_messages=True)
241
+ memory.load_memory_variables(
242
+ {'history': [HumanMessage(content=past_user_inputs[-1], additional_kwargs={}),
243
+ AIMessage(content=generated_responses[-1], additional_kwargs={})]}
244
+ )
245
+
246
+ # Add user input as HumanMessage
247
+ history.messages.append(HumanMessage(content=str(past_user_inputs[-1]), additional_kwargs={}))
248
+ # Add generated response as AIMessage
249
+ history.messages.append(AIMessage(content=str(generated_responses[-1]), additional_kwargs={}))
250
+
251
+ conversation = LLMChain(
252
+ llm=llm,
253
+ prompt=prompt,
254
+ verbose=True,
255
+ memory=memory
256
+ )
257
+
258
+ response = conversation.predict(input=question)
259
+ memory.save_context({"input": question}, {"output": response})
260
+
261
+ print(response)
262
+ return str(response)
263
+
264
+ except Exception as e:
265
+ print(f"Error: {e}")
266
+
267
+ # Function to send a question to the chatbot and get the response
268
+ async def askAgent(self, question):
269
+ os.environ["GOOGLE_CSE_ID"] = GOOGLE_CSE_ID
270
+ os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
271
+ os.environ["FIREWORKS_API_KEY"] = FIREWORKS_API_KEY
272
+
273
+ try:
274
+ # Connect to the database and get the last 30 messages
275
+ db = sqlite3.connect('chat-hub.db')
276
+ cursor = db.cursor()
277
+ cursor.execute("SELECT * FROM messages ORDER BY timestamp DESC LIMIT 10")
278
+ msgHistory = cursor.fetchall()
279
+ msgHistory.reverse()
280
+
281
+ llm = ChatFireworks(model="accounts/fireworks/models/llama-v2-13b-chat", model_kwargs={"temperature":0, "max_tokens":4000, "top_p":1.0})
282
+ output_parser = CommaSeparatedListOutputParser
283
+ chat_history = ChatMessageHistory()
284
+ memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
285
+
286
+ for message in msgHistory:
287
+ if message[1] == 'client':
288
+ # Extract and store user inputs
289
+ memory.chat_memory.add_user_message(message[2])
290
+ else:
291
+ # Extract and store generated responses
292
+ memory.chat_memory.add_ai_message(message[2])
293
+
294
+ request_tools = load_tools(["requests_all"])
295
+ requests = TextRequestsWrapper()
296
+ search = GoogleSearchAPIWrapper()
297
+ tools = [
298
+ Tool(
299
+ name="Chat response",
300
+ func=await self.handleInput(question),
301
+ 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.",
302
+ ),
303
+ Tool(
304
+ name="Search",
305
+ func=search.run,
306
+ description="useful for when you need to answer questions about current events",
307
+ ),
308
+ Tool(
309
+ name="Start websocket server",
310
+ func=await self.launchServer(),
311
+ 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",
312
+ ),
313
+ Tool(
314
+ name="Start websocket client",
315
+ func=await self.connectClient(),
316
+ 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",
317
+ ),
318
+ Tool(
319
+ name="Conversational answer",
320
+ func=await self.conversation(question),
321
+ description="useful when you want to respond to a given input using 'predict' function of a conversational chain",
322
+ ),
323
+ Tool(
324
+ name="Ask Copilot",
325
+ func=await self.askBing(question),
326
+ description="useful when you want to get an answer from Microsoft Copilot",
327
+ ),
328
+ Tool(
329
+ name="Conversational answer",
330
+ func=await self.askGPT(question),
331
+ description="useful when you want to get an answer from ChatGPT",
332
+ ),
333
+ Tool(
334
+ name="Conversational answer",
335
+ func=await self.askCharacter(question),
336
+ description="useful when you want to get an answer from Character.ai chatbot",
337
+ ),
338
+ Tool(
339
+ name="Conversational answer",
340
+ func=await self.ask_flowise(question),
341
+ description="useful when you want to get an answer from a Flowise agent",
342
+ ),
343
+ ]
344
+
345
+ 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: """
346
+ suffix = """Begin!"
347
+ 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'.
348
+ {chat_history}
349
+ 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.
350
+ 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.
351
+ 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'.
352
+ 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'.
353
+ If you aren't sure what action to take or what tool to use, end up your run with 'Give answer'.
354
+ Remember to not take any unnecessary actions.
355
+ Question: {input}
356
+ {agent_scratchpad}"""
357
+
358
+ format_instructions = output_parser.get_format_instructions()
359
+ prompt = ZeroShotAgent.create_prompt(
360
+ tools=tools,
361
+ prefix=prefix,
362
+ suffix=suffix,
363
+ input_variables=["input", "chat_history", "agent_scratchpad"],
364
+ )
365
+
366
+ llm_chain = LLMChain(llm=llm, prompt=prompt)
367
+ 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")
368
+ agent_chain = AgentExecutor.from_agent_and_tools(
369
+ agent=agent, tools=tools, verbose=True, return_intermediate_steps=True, handle_parsing_errors=True, memory=memory
370
+ )
371
+
372
+ response = await agent_chain.run(input=json.dumps(question))
373
+ memory.save_context({"input": question}, {"output": response})
374
+ serverResponse = "server: " + response
375
+ print(serverResponse)
376
+ return json.dumps(serverResponse)
377
+
378
+ except Exception as error:
379
+ print("Error while fetching or processing the response:", error)
380
+ return "Error: Unable to generate a response.", error
381
+
382
+ async def askQuestion(self, question):
383
+ print(question)
384
+ os.environ["GOOGLE_CSE_ID"] = GOOGLE_CSE_ID
385
+ os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
386
+ os.environ["FIREWORKS_API_KEY"] = self.fireworksAPI
387
+ fireworks.client.api_key = self.fireworksAPI
388
+
389
+ try:
390
+ # Connect to the database and get the last 30 messages
391
+ db = sqlite3.connect('chat-hub.db')
392
+ cursor = db.cursor()
393
+ cursor.execute("SELECT * FROM messages ORDER BY timestamp DESC LIMIT 20")
394
+ msgHistory = cursor.fetchall()
395
+ msgHistory.reverse()
396
+
397
+ llm = Fireworks(model="accounts/fireworks/models/llama-v2-13b-chat", model_kwargs={"temperature":0, "max_tokens":4000, "top_p":1.0})
398
+
399
+ history = ChatMessageHistory()
400
+ # Initialize chat_history with a message if the history is empty
401
+ memory = ConversationBufferMemory(memory_key="history", return_messages=True)
402
+
403
+ for message in msgHistory:
404
+ if message[1] == 'client':
405
+ # Extract and store user inputs
406
+ memory.chat_memory.add_user_message(str(message[2]))
407
+ else:
408
+ # Extract and store generated responses
409
+ memory.chat_memory.add_ai_message(str(message[2]))
410
+
411
+ prompt = ChatPromptTemplate.from_messages(
412
+ messages=[
413
+ ("system", self.instruction),
414
+ MessagesPlaceholder(variable_name="history"),
415
+ ("human", "{input}")]
416
+ )
417
+
418
+ conversation = LLMChain(
419
+ llm=llm,
420
+ prompt=prompt,
421
+ verbose=True,
422
+ memory=memory
423
+ )
424
+
425
+ request_tools = load_tools(["requests_all"])
426
+ requests = TextRequestsWrapper()
427
+ search = GoogleSearchAPIWrapper()
428
+ chat_response = await self.chatFireworks(self.instruction, question)
429
+ conversational = await self.conversation(question)
430
+ queryData = await self.queryStore(question)
431
+ copilot = await self.askBing(question)
432
+ chatgpt = await self.askGPT(question)
433
+ character = await self.askCharacter(question)
434
+ flowise = await self.ask_flowise(question)
435
+ tools = [
436
+ Tool(
437
+ name="Chat response",
438
+ func=chat_response,
439
+ 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.",
440
+ ),
441
+ Tool(
442
+ name="Search",
443
+ func=search.run,
444
+ description="useful for when you need to answer questions about current events",
445
+ ),
446
+ Tool(
447
+ name="Conversational answer",
448
+ func=conversation,
449
+ description="useful when you want to respond to a given input using 'predict' function of a conversational chain",
450
+ ),
451
+ Tool(
452
+ name="Query Chaindesk datastore",
453
+ func=queryData,
454
+ description="useful when you want to get data from documents stored in Chaindesk datastore",
455
+ ),
456
+ Tool(
457
+ name="Ask Copilot",
458
+ func=copilot,
459
+ description="useful when you want to get an answer from Microsoft Copilot",
460
+ ),
461
+ Tool(
462
+ name="Conversational answer",
463
+ func=chatgpt,
464
+ description="useful when you want to get an answer from ChatGPT",
465
+ ),
466
+ Tool(
467
+ name="Conversational answer",
468
+ func=character,
469
+ description="useful when you want to get an answer from Character.ai chatbot",
470
+ ),
471
+ Tool(
472
+ name="Conversational answer",
473
+ func=flowise,
474
+ description="useful when you want to get an answer from a Flowise agent",
475
+ ),
476
+ ]
477
+
478
+ 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: """
479
+ suffix = """Begin!"
480
+ 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'.
481
+ {chat_history}
482
+ 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.
483
+ 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.
484
+ 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'.
485
+ 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'.
486
+ If you aren't sure what action to take or what tool to use, end up your run with 'Give answer'.
487
+ Remember to not take any unnecessary actions.
488
+ Question: {input}
489
+ {agent_scratchpad}"""
490
+
491
+ prompt = ZeroShotAgent.create_prompt(
492
+ tools,
493
+ prefix=prefix,
494
+ suffix=suffix,
495
+ input_variables=["input", "chat_history", "agent_scratchpad"],
496
+ )
497
+
498
+ llm_chain = LLMChain(llm=llm, prompt=prompt)
499
+ agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True, max_iterations=2, early_stopping_method="generate")
500
+ agent_chain = AgentExecutor.from_agent_and_tools(
501
+ agent=agent, tools=tools, verbose=True, handle_parsing_errors=True, memory=memory
502
+ )
503
+
504
+ response = agent_chain.run(input=question)
505
+ memory.save_context({"input": question}, {"output": response})
506
+ serverResponse = f"server: {response}"
507
+
508
+ print(serverResponse)
509
+ return str(serverResponse)
510
+
511
+ except Exception as error:
512
+ print("Error while fetching or processing the response:", error)
513
+ return "Error: Unable to generate a response.", error
514
+
515
+ # Define a coroutine that will connect to the server and exchange messages
516
+ async def startClient(self, clientPort):
517
+ self.cli_name2 = f"Fireworks Llama2 client port: {clientPort}"
518
+ uri = f'ws://localhost:{clientPort}'
519
+ conteneiro.clients.append(self.cli_name2)
520
+ self.clients.append(self.cli_name2)
521
+ self.stat.empty()
522
+ self.cont.empty()
523
+ self.status = self.cont.status(label=self.cli_name2, state="running", expanded=True)
524
+ self.status.write(conteneiro.servers)
525
+ self.state = self.stat.status(label=self.cli_name2, state="running", expanded=True)
526
+ self.state.write(conteneiro.servers)
527
+ # Connect to the server
528
+ async with websockets.connect(uri) as websocket:
529
+ # Loop forever
530
+ while True:
531
+ self.websocket = websocket
532
+ # Listen for messages from the server
533
+ input_message = await websocket.recv()
534
+ print(f"Server: {input_message}")
535
+ input_Msg = st.chat_message("assistant")
536
+ input_Msg.markdown(input_message)
537
+ try:
538
+ response = await self.askQuestion(input_message)
539
+ res1 = f"Client: {response}"
540
+ output_Msg = st.chat_message("ai")
541
+ output_Msg.markdown(res1)
542
+ await websocket.send(res1)
543
+ await self.handleInput(res1)
544
+ continue
545
+
546
+ except websockets.exceptions.ConnectionClosedError as e:
547
+ self.clients.remove(self.cli_name2)
548
+ print(f"Connection closed: {e}")
549
+
550
+ except Exception as e:
551
+ self.clients.remove(self.cli_name2)
552
+ print(f"Error: {e}")
553
+
554
+ async def start_server(self, serverPort):
555
+ self.srv_name2 = f"Fireworks Llama2 server port: {serverPort}"
556
+ conteneiro.servers.append(self.srv_name2)
557
+ self.stat.empty()
558
+ self.cont.empty()
559
+ self.status = self.cont.status(label=self.srv_name2, state="running", expanded=True)
560
+ self.status.write(self.clients)
561
+ self.state = self.stat.status(label=self.srv_name2, state="running", expanded=True)
562
+ self.state.write(self.clients)
563
+ self.server = await websockets.serve(
564
+ self.handlerFire,
565
+ "localhost",
566
+ serverPort
567
+ )
568
+ print(f"WebSocket server started at port: {serverPort}")
569
+
570
+ def run_forever(self):
571
+ asyncio.get_event_loop().run_until_complete(self.start_server())
572
+ asyncio.get_event_loop().run_forever()
573
+
574
+ async def stop_server(self):
575
+ if self.server:
576
+ self.server.close()
577
+ await self.server.wait_closed()
578
+ print("WebSocket server stopped.")
579
+
580
+ # Define a function that will run the client in a separate thread
581
+ def run(self):
582
+ # Create a thread object
583
+ self.thread = threading.Thread(target=self.run_client)
584
+ # Start the thread
585
+ self.thread.start()
586
+
587
+ async def stop_server(self):
588
+ if self.server:
589
+ conteneiro.servers.remove(self.srv_name2)
590
+ self.clients.clear()
591
+ self.server.close()
592
+ await self.server.wait_closed()
593
+ print("WebSocket server stopped.")
594
+ else:
595
+ msg = f"Server isn't running"
596
+ print(msg)
597
+ return (msg)
598
+
599
+ async def stop_client(self):
600
+ conteneiro.clients.remove(self.cli_name2)
601
+ # Close the connection with the server
602
+ await self.websocket.close()
603
+ print("Stopping WebSocket client...")
604
+
605
+ async def pickPortSrv(self):
606
+ activeSrv = str(conteneiro.servers)
607
+ instruction = f"This question is part of a function launching websocket servers at ports chosen by you. Your only job is to respond with a number in range from 1000 to 9999 excluding port numbers which are already used by active websocket servers. List of currently active server to which you can be connected is provided here: {activeSrv} - '[]' means that there are no active servers and the list is empty, so all numbers in range 1000-9999 are available for you to choose. Remember that your response shouldn't include anything except the chosen number in range, as it will be used as argument for another function that accepts only integer inputs."
608
+ command = f"Launch server on a port of your choice"
609
+ response = await self.chatFireworks(instruction, command)
610
+ print(response)
611
+ match = re.search(r'\d+', response)
612
+ number = int(match.group())
613
+ print(f"port chosen by agent: {number}")
614
+ return int(number)
615
+
616
+ async def pickPortCli(self):
617
+ activeSrv = str(conteneiro.servers)
618
+ instruction = f"This question is part of a function connecting you as a client to active websocket servers running at specific ports. Your only job is to respond with a number of a port yo which you want to be connected. List of currently active server to which you can be connected is provided here: {activeSrv} - if the list is empty, then there's no active servers. Remember that your response shouldn't include anything except the number of port to which you want to be connected, as it will be used as argument for another function that accepts only integer inputs."
619
+ response = await self.chatFireworks(instruction, activeSrv)
620
+ print(response)
621
+ match = re.search(r'\d+', response)
622
+ number = int(match.group())
623
+ print(f"port of server chosen by agent: {number}")
624
+ return number
625
+
626
+ async def pickSearch(self, question):
627
+ instruction = f"This input is a part of function allowing agents to browse internet. Your main and only job is to analyze the input message and respond by naming the subject(s) to use while performing internet search. Remember to keep your response as short as possible - respond with single words and/or short sentences that summarize the subject(s) discussed in the message that will be given to you."
628
+ response = await self.chatFireworks(instruction, question)
629
+ print(response)
630
+ return str(response)
631
+
632
+ async def google_search(self, question):
633
+ subject = await self.pickSearch(question)
634
+ agent = AgentsGPT()
635
+ results = await agent.get_response(subject)
636
+ result = f"AgentsGPT internet search results: {results}"
637
+ output_Msg = st.chat_message("ai")
638
+ output_Msg.markdown(result)
639
+ return result
640
+
641
+ async def launchServer(self):
642
+ serverPort = await self.pickPortSrv()
643
+ await self.start_server(serverPort)
644
+ resp = f"You successfully launched a Websocket server at port {serverPort}. Do you want to inform other instances/agents so they can connect to it?"
645
+ output_Msg = st.chat_message("ai")
646
+ output_Msg.markdown(resp)
647
+ await self.handleInput(resp)
648
+
649
+ async def connectClient(self):
650
+ clientPort = await self.pickPortCli()
651
+ await self.startClient(clientPort)
652
+
653
+ async def handleInput(self, question):
654
+
655
+ instruction = f"""
656
+ This is an automatic follow-up to your last response: {question}. I'm an automatic assistant designed to help you operate with a decision making mechanism in a hierarchical cooperative multi-agent framework called NeuralGPT.
657
+ As the node of highest hierarchy in the network, you're equipped with additional tools which you can activate by giving a response which includes one of the following commands:
658
+
659
+ 1. '/silence' to not respond with anything and keep the client 'on hold'.
660
+ 2. '/disconnect' to disconnect client from a server.
661
+ 3. '/search' to perform internet search for subjects mentioned in your response.
662
+ 4. '/queryDatastore' to retrieve data from documents in Chaindesk datastore.
663
+ 5. '/start_server' to start a websocket server with you as the question-answering function.
664
+ 6. '/connect_client' to connect yourself to already active websocket servers.
665
+ 7. '/askChaindesk' to get response from a Chaindesk agent.
666
+ 8. '/askBing' to get response from Microsoft Copilot agent.
667
+ 9. '/askChatGPT' to get response from GPT-3,5 agent.
668
+ 10. '/askClaude3' to get response from Claude-3 agent.
669
+ 11. '/askForefront' to get response from Forefront AI agent.
670
+ 12. '/askCharacter' to get response from a chosen character from Character.ai platform.
671
+ 13. '/askFlowise' to get response from a Flowise agent.
672
+ I4 you don't want to use any of those command-functions, give an answe which dooesn't include any of the given commands.
673
+ Be very careful while executing any of your command-functions to not overload the system with multiple concurrent processes.
674
+ """
675
+ try:
676
+ response = await self.chatFireworks(self.instruction, instruction)
677
+ serverSender = 'server'
678
+ timestamp = datetime.datetime.now().isoformat()
679
+ db = sqlite3.connect('chat-hub.db')
680
+ db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
681
+ (serverSender, response, timestamp))
682
+ db.commit()
683
+ output_Msg = st.chat_message("ai")
684
+ output_Msg.markdown(response)
685
+
686
+ if re.search(r'/queryDatastore', response):
687
+ answer = await self.queryStore(response)
688
+ outputMsg = st.chat_message("ai")
689
+ outputMsg.markdown(answer)
690
+ follow = await self.askQuestion(answer)
691
+ outputMsg.markdown(follow)
692
+ return follow
693
+
694
+ if re.search(r'/askBing', response):
695
+ answer2 = await self.askBing(response)
696
+ outputMsg = st.chat_message("ai")
697
+ outputMsg.markdown(answer2)
698
+ follow = await self.askQuestion(answer2)
699
+ outputMsg.markdown(follow)
700
+ return follow
701
+
702
+ if re.search(r'/askCharacter', response):
703
+ response = await self.askCharacter(response)
704
+ outputMsg = st.chat_message("ai")
705
+ outputMsg.markdown(response)
706
+ follow = await self.askQuestion(response)
707
+ outputMsg.markdown(follow)
708
+ return follow
709
+
710
+ if re.search(r'/search', response):
711
+ search = await self.google_search(response)
712
+ print(search)
713
+ results = st.chat_message("assistant")
714
+ results.markdown(search)
715
+ answer1 = await self.handleInput(search)
716
+ outputMsg = st.chat_message("ai")
717
+ outputMsg.markdown(answer1)
718
+ return answer1
719
+
720
+ if re.search(r'/silence', response):
721
+ print("...<no response>...")
722
+ output_Msg = st.chat_message("ai")
723
+ output_Msg.markdown("...<no response>...")
724
+
725
+ if re.search(r'/disconnect', response):
726
+ await self.stop_client()
727
+ res = "successfully disconnected"
728
+ return res
729
+
730
+ if re.search(r'/start_server', response):
731
+ await self.launchServer()
732
+
733
+ if re.search(r'/connect_client', response):
734
+ await self.connectClient()
735
+
736
+ if re.search(r'/askChatGPT', response):
737
+ answer3 = await self.askGPT(response)
738
+ outputMsg = st.chat_message("ai")
739
+ outputMsg.markdown(answer3)
740
+ follow = await self.handleInput(answer3)
741
+ outputMsg.markdown(follow)
742
+ return follow
743
+
744
+ if re.search(r'/askClaude3', response):
745
+ answer4 = await self.ask_Claude(response)
746
+ outputMsg = st.chat_message("ai")
747
+ outputMsg.markdown(answer4)
748
+ follow = await self.handleInput(answer4)
749
+ outputMsg.markdown(follow)
750
+ return follow
751
+
752
+ if re.search(r'/askForefront', response):
753
+ answer4 = await self.ask_Forefront(response)
754
+ outputMsg = st.chat_message("ai")
755
+ outputMsg.markdown(answer4)
756
+ follow = await self.handleInput(answer4)
757
+ outputMsg.markdown(follow)
758
+ return follow
759
+
760
+ if re.search(r'/askFlowise', response):
761
+ answer3 = await self.ask_flowise(response)
762
+ outputMsg = st.chat_message("ai")
763
+ outputMsg.markdown(answer3)
764
+ follow = await self.handleInput(answer3)
765
+ outputMsg.markdown(follow)
766
+ return follow
767
+
768
+ if re.search(r'/askChaindesk', response):
769
+ answer3 = await self.ask_chaindesk(response)
770
+ outputMsg = st.chat_message("ai")
771
+ outputMsg.markdown(answer3)
772
+ follow = await self.handleInput(answer3)
773
+ outputMsg.markdown(follow)
774
+ return follow
775
+
776
+ else:
777
+ return response
778
+
779
+ except Exception as e:
780
+ print(f"Error: {e}")
781
+
782
+ async def queryStore(self, question):
783
+ ID = "clhet2nit0000eaq63tf25789"
784
+ store = Chaindesk(ID)
785
+ response = await store.queryDatastore(question)
786
+ print(response)
787
+ return response
788
+
789
+ async def ask_Forefront(self, question):
790
+ api = FOREFRONT_API_KEY
791
+ forefront = ForefrontAI(api)
792
+ response = await forefront.handleInput(question)
793
+ print(response)
794
+ return response
795
+
796
+ async def ask_Claude(self, question):
797
+ api = ANTHROPIC_API_KEY
798
+ claude = Claude3(api)
799
+ response = await claude.handleInput(question)
800
+ print(response)
801
+ return response
802
+
803
+ async def askGPT(self, question):
804
+ gpt = ChatGPT()
805
+ response = await gpt.handleInput(question)
806
+ print(response)
807
+ return response
808
+
809
+ async def askBing(self, question):
810
+ bing = Copilot()
811
+ response = await bing.handleInput(question)
812
+ print(response)
813
+ return response
814
+
815
+
816
+ async def ask_flowise(self, question):
817
+ flow = "cad0c187-f1dc-4152-8464-78ba0867e1a6"
818
+ flowise = Flowise(flow)
819
+ response = await flowise.handleInput(question)
820
+ print(response)
821
+ return response
822
+
823
+ async def ask_chaindesk(self, question):
824
+ id = "clhet2nit0000eaq63tf25789"
825
+ agent = Chaindesk(id)
826
+ response = await agent.handleInput(question)
827
+ print(response)
828
+ return response
829
+
830
+ async def pickCharacter(self, question):
831
+ characterList = f"List of available characters:/d 1. Elly/d 2. NeuralAI"
832
+ instruction = f"This is a function allowing agents to choose a specific character from a list of characters deployed on Character.ai platform. Your only job is to choose which character you want to speak with using the input message as a context and respond with the name of chosen character. You don't need to say anything Except the name of character from the followinng list: {characterList}."
833
+ inputo = f"Use the following question as context for you to choose which character from Character.ai platform you want to speak with./dQuestion for context: {question}/d List of chharacters for you to choose: {characterList}/d Respond with the name of chosen character to establish a connection."
834
+ character = await self.chatFireworks(instruction, inputo)
835
+ print(character)
836
+ outputMsg = st.chat_message("ai")
837
+ outputMsg.markdown(character)
838
+
839
+ if re.search(r'Elly', character):
840
+ characterID = f"WnIwl_sZyXb_5iCAKJgUk_SuzkeyDqnMGi4ucnaWY3Q"
841
+ return characterID
842
+
843
+ if re.search(r'NeuralAI', character):
844
+ characterID = f"_1xlg0qQZl39ds3dbkXS8iWckZGNTRrdtdl0_sjvdJw"
845
+ return characterID
846
+
847
+ else:
848
+ response = f"You didn't choose any character to establish a connection with. Do you want try once again or maybe use some other copmmand-fuunction?"
849
+ print(response)
850
+ await self.handleInput(response)
851
+
852
+ async def askCharacter(self, question):
853
+ characterID = await self.pickCharacter(question)
854
+ token = "d9016ef1aa499a1addb44049cedece57e21e8cbb"
855
+ character = CharacterAI(token, characterID)
856
+ answer = await character.handleInput(question)
857
+ return answer