Pablo276 commited on
Commit
7ec15fa
·
verified ·
1 Parent(s): c9aef59

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +453 -453
app.py CHANGED
@@ -1,453 +1,453 @@
1
- import streamlit as st
2
- from langchain.agents import AgentType, initialize_agent
3
- from langchain_community.chat_models import ChatOpenAI
4
- from langchain.schema import SystemMessage
5
- from langchain.prompts import MessagesPlaceholder
6
- from typing import Dict, Any
7
- from langchain.memory import ConversationBufferMemory
8
- from langchain.agents import initialize_agent, Tool
9
- import requests
10
- from datetime import datetime
11
- import os
12
-
13
- API_O = os.environ.get("OPENAI_API_KEY")
14
-
15
-
16
- class CustomMemory(ConversationBufferMemory):
17
- def _get_input_output(self, inputs: Dict[str, Any], outputs: Dict[str, Any]) -> tuple:
18
- input_str = inputs.get("input", "")
19
- chat_history = inputs.get("chat_history", [])
20
- input_str = f"Human: {input_str}\nChat History: {chat_history}\n"
21
- output_str = outputs.get("result", "")
22
- return input_str, output_str
23
-
24
-
25
- def get_chat_completion(user_message, content):
26
- # Define the API endpoint
27
- url = "https://api.openai.com/v1/chat/completions"
28
-
29
- # Define the headers
30
- headers = {
31
- "Content-Type": "application/json",
32
- "Authorization": f"Bearer {API_O}"
33
- }
34
-
35
- # Define the data payload
36
- data = {
37
- "model": "gpt-4-1106-preview",
38
- "messages": [
39
- {
40
- "role": "system",
41
- "content": content
42
- },
43
- {
44
- "role": "user",
45
- "content": user_message
46
- }
47
- ]
48
- }
49
- # Send the request
50
- response = requests.post(url, headers=headers, json=data)
51
- # Return the JSON response
52
- return str(response.json()["choices"][0]["message"]["content"]).lower()
53
-
54
-
55
- def video_streaming_Test(prompt):
56
- test_name = "video_streaming_Test"
57
- content_one_time_test = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt the Start_Date is present, No if is missing. IF 'null' is in the input , the answer is NO. ACCEPTED ANSWER : YES / NO."
58
- content_multiple_tests = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt, both Number_of_tests, Start_Date are present, No if even only one is missing.IF 'null' is in the input , the answer is NO. THERE CAN BE MORE IN THE PROMPT, YOU DON'T HAVE TO CAARE ABOUT IT. ACCEPTED ANSWER : YES / NO."
59
-
60
- if "One time test" in prompt:
61
- if "now" in prompt:
62
- now = datetime.now()
63
- formatted_date = str(now.strftime("%d/%m/%Y"))
64
- prompt = prompt.replace("now", formatted_date)
65
- elif "today" in prompt:
66
- now = datetime.now()
67
- formatted_date = str(now.strftime("%d/%m/%Y"))
68
- prompt = prompt.replace("today", formatted_date)
69
-
70
- response = get_chat_completion(prompt, content_one_time_test)
71
- if "yes" in str(response).lower():
72
- print(prompt)
73
- return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Start_Date: selected_start_date}}"
74
- else:
75
- return "There are some infomration needed missing, information needed: Start_Date "
76
-
77
- elif "Periodic test" in prompt or "Driving Mode" in prompt:
78
- if "now" in prompt:
79
- now = datetime.now()
80
- formatted_date = str(now.strftime("%d/%m/%Y"))
81
- prompt = prompt.replace("now", formatted_date)
82
- elif "today" in prompt:
83
- now = datetime.now()
84
- formatted_date = str(now.strftime("%d/%m/%Y"))
85
- prompt = prompt.replace("today", formatted_date)
86
-
87
- response = get_chat_completion(prompt, content_multiple_tests)
88
- if "yes" in str(response).lower():
89
- print(prompt)
90
- return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Number_of_tests: selected_number_of_tests, Start_Date: selected_start_date}}"
91
- else:
92
- return "There are some infomration needed missing, information needed: Number_of_tests, Start_Date "
93
- else:
94
- return "seems like the user did not specify the type of test: Possible choiches: 1.One time test, 2.Periodic test, 3.Driving Mode "
95
-
96
-
97
- def wifi_test(prompt):
98
- test_name = "wifi_test"
99
-
100
- content_one_time_test = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt the Start_Date is present, No if is missing. IF 'null' is in the input , the answer is NO. ACCEPTED ANSWER : YES / NO."
101
- content_multiple_tests = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt, both Number_of_tests, Start_Date are present, No if even only one is missing.IF 'null' is in the input , the answer is NO. THERE CAN BE MORE IN THE PROMPT, YOU DON'T HAVE TO CAARE ABOUT IT. ACCEPTED ANSWER : YES / NO."
102
- if "One time test" in prompt:
103
- if "now" in prompt:
104
- now = datetime.now()
105
- formatted_date = str(now.strftime("%d/%m/%Y"))
106
- prompt = prompt.replace("now", formatted_date)
107
- elif "today" in prompt:
108
- now = datetime.now()
109
- formatted_date = str(now.strftime("%d/%m/%Y"))
110
- prompt = prompt.replace("today", formatted_date)
111
-
112
- response = get_chat_completion(prompt, content_one_time_test)
113
- if "yes" in str(response).lower():
114
- print(prompt)
115
- return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Start_Date: selected_start_date}}"
116
- else:
117
- return "There are some infomration needed missing, information needed: Start_Date "
118
- elif "Periodic test" in prompt or "Driving Mode" in prompt:
119
- if "now" in prompt:
120
- now = datetime.now()
121
- formatted_date = str(now.strftime("%d/%m/%Y"))
122
- prompt = prompt.replace("now", formatted_date)
123
- elif "today" in prompt:
124
- now = datetime.now()
125
- formatted_date = str(now.strftime("%d/%m/%Y"))
126
- prompt = prompt.replace("today", formatted_date)
127
-
128
- response = get_chat_completion(prompt, content_multiple_tests)
129
- if "yes" in str(response).lower():
130
- print(prompt)
131
- return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Number_of_tests: selected_number_of_tests, Start_Date: selected_start_date}}"
132
- else:
133
- return "There are some infomration needed missing, information needed: Number_of_tests, Start_Date "
134
- else:
135
- return "seems like the user did not specify the type of test: Possible choiches: 1.One time test, 2.Periodic test, 3.Driving Mode "
136
-
137
-
138
- def iot_test(prompt):
139
- test_name = "iot_test"
140
-
141
- content_one_time_test = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt all the following are present: 1: Start_Date, 2: Mqtt broker address, 3: Quality of Service (QoS), 4: Mqtt Message Count; No if even only one is missing. IF 'null' is in the input , the answer is NO. ACCEPTED ANSWER : YES / NO."
142
- content_multiple_tests = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt, all the following are present: 1: Number_of_tests, 2: Start_Date, 3: Mqtt broker address, 4: Quality of Service (QoS), 5: Mqtt Message Count; are present, No if even only one is missing.IF 'null' is in the input , the answer is NO. THERE CAN BE MORE IN THE PROMPT, YOU DON'T HAVE TO CARE ABOUT IT, . ACCEPTED ANSWER : YES / NO."
143
- if "One time test" in prompt:
144
- if "now" in prompt:
145
- now = datetime.now()
146
- formatted_date = str(now.strftime("%d/%m/%Y"))
147
- prompt = prompt.replace("now", formatted_date)
148
- elif "today" in prompt:
149
- now = datetime.now()
150
- formatted_date = str(now.strftime("%d/%m/%Y"))
151
- prompt = prompt.replace("today", formatted_date)
152
-
153
- response = get_chat_completion(prompt, content_one_time_test)
154
- if "yes" in str(response).lower():
155
- print(prompt)
156
- return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Start_Date: selected_start_date, Mqtt broker address: selected_Mqtt_broker_address, Quality of Service (QoS): selected_Quality_of_Service, Mqtt Message Count: selected_Mqtt_Message_Count }}"
157
- else:
158
- return "There are some infomration needed missing, information needed: 1: Start_Date, 2: Mqtt broker address, 3: Quality of Service (QoS), 4: Mqtt Message Count "
159
-
160
- elif "Periodic test" in prompt or "Driving Mode" in prompt:
161
- if "now" in prompt:
162
- now = datetime.now()
163
- formatted_date = str(now.strftime("%d/%m/%Y"))
164
- prompt = prompt.replace("now", formatted_date)
165
- elif "today" in prompt:
166
- now = datetime.now()
167
- formatted_date = str(now.strftime("%d/%m/%Y"))
168
- prompt = prompt.replace("today", formatted_date)
169
-
170
- response = get_chat_completion(prompt, content_multiple_tests)
171
- if "yes" in str(response).lower():
172
- print(prompt)
173
- return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Number_of_tests: selected_number_of_tests, Start_Date: selected_start_date, Mqtt broker address: selected_Mqtt_broker_address, Quality of Service (QoS): selected_Quality_of_Service, Mqtt Message Count}}"
174
- else:
175
- return "There are some infomration needed missing, information needed: 1: Number_of_tests, 2: Start_Date, 3: Mqtt broker address, 4: Quality of Service (QoS), 5: Mqtt Message "
176
- else:
177
- return "seems like the user did not specify the type of test: Possible choiches: 1.One time test, 2.Periodic test, 3.Driving Mode "
178
-
179
-
180
- def online_gaming_test(prompt):
181
- test_name = "online_gaming_test"
182
-
183
- content_one_time_test = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt both the Start_Date and the predefined_gaming_servers are present, No if even only one is missing. IF 'null' is in the input , the answer is NO. ACCEPTED ANSWER : YES / NO."
184
- content_multiple_tests = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt, all the following Number_of_tests, Start_Date, predefined_gaming_servers are present, No if even only one is missing.IF 'null' is in the input , the answer is NO. THERE CAN BE MORE IN THE PROMPT, YOU DON'T HAVE TO CAARE ABOUT IT. ACCEPTED ANSWER : YES / NO."
185
- if "One time test" in prompt:
186
- if "now" in prompt:
187
- now = datetime.now()
188
- formatted_date = str(now.strftime("%d/%m/%Y"))
189
- prompt = prompt.replace("now", formatted_date)
190
- elif "today" in prompt:
191
- now = datetime.now()
192
- formatted_date = str(now.strftime("%d/%m/%Y"))
193
- prompt = prompt.replace("today", formatted_date)
194
-
195
- response = get_chat_completion(prompt, content_one_time_test)
196
- if "yes" in str(response).lower():
197
- print(prompt)
198
- return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Start_Date: selected_start_date, game_servers: predefined_gaming_servers}}"
199
- else:
200
- return "There are some infomration needed missing, information needed: Start_Date, predefined_gaming_servers "
201
- elif "Periodic test" in prompt or "Driving Mode" in prompt:
202
- if "now" in prompt:
203
- now = datetime.now()
204
- formatted_date = str(now.strftime("%d/%m/%Y"))
205
- prompt = prompt.replace("now", formatted_date)
206
- elif "today" in prompt:
207
- now = datetime.now()
208
- formatted_date = str(now.strftime("%d/%m/%Y"))
209
- prompt = prompt.replace("today", formatted_date)
210
-
211
- response = get_chat_completion(prompt, content_multiple_tests)
212
- if "yes" in str(response).lower():
213
- print(prompt)
214
- return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Number_of_tests: selected_number_of_tests, Start_Date: selected_start_date, game_servers: predefined_gaming_servers}}"
215
-
216
- else:
217
- return "There are some infomration needed missing, information needed: Number_of_tests, Start_Date, predefined_gaming_servers "
218
- else:
219
- return "seems like the user did not specify the type of test: Possible choiches: 1.One time test, 2.Periodic test, 3.Driving Mode "
220
-
221
-
222
- def ping_test(prompt):
223
- test_name = "ping_test"
224
-
225
- content_one_time_test = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt all the following: host_or_ip, ping_count, Start_Date are present, No if even only one is missing. IF 'null' is in the input , the answer is NO. ACCEPTED ANSWER : YES / NO."
226
- content_multiple_tests = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt, all the following: host_or_ip, ping_count, Number_of_tests, Start_Date are present, No if even only one is missing.IF 'null' is in the input , the answer is NO. THERE CAN BE MORE IN THE PROMPT, YOU DON'T HAVE TO CAARE ABOUT IT. ACCEPTED ANSWER : YES / NO."
227
- if "One time test" in prompt:
228
- if "now" in prompt:
229
- now = datetime.now()
230
- formatted_date = str(now.strftime("%d/%m/%Y"))
231
- prompt = prompt.replace("now", formatted_date)
232
- elif "today" in prompt:
233
- now = datetime.now()
234
- formatted_date = str(now.strftime("%d/%m/%Y"))
235
- prompt = prompt.replace("today", formatted_date)
236
-
237
- response = get_chat_completion(prompt, content_one_time_test)
238
- if "yes" in str(response).lower():
239
- print(prompt)
240
- return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Start_Date: selected_start_date,host_or_ip: selected_host_or_ip, ping_count: selected_ping_count }}"
241
- else:
242
- return "There are some infomration needed missing, information needed: Start_Date ,host_or_ip, ping_count"
243
- elif "Periodic test" in prompt or "Driving Mode" in prompt:
244
- if "now" in prompt:
245
- now = datetime.now()
246
- formatted_date = str(now.strftime("%d/%m/%Y"))
247
- prompt = prompt.replace("now", formatted_date)
248
- elif "today" in prompt:
249
- now = datetime.now()
250
- formatted_date = str(now.strftime("%d/%m/%Y"))
251
- prompt = prompt.replace("today", formatted_date)
252
-
253
- response = get_chat_completion(prompt, content_multiple_tests)
254
- if "yes" in str(response).lower():
255
- print(prompt)
256
- return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Number_of_tests: selected_number_of_tests, Start_Date: selected_start_date,host_or_ip: selected_host_or_ip, ping_count: selected_ping_count }}"
257
- else:
258
- return "There are some infomration needed missing, information needed: Number_of_tests, Start_Date, host_or_ip ping_count"
259
- else:
260
- return "seems like the user did not specify the type of test: Possible choiches: 1.One time test, 2.Periodic test, 3.Driving Mode "
261
-
262
-
263
- tools = [
264
- Tool(
265
- name="video_streaming_Test",
266
- func=lambda prompt: video_streaming_Test(prompt),
267
- description="""Use when the user wants to do a video_streaming_Test,
268
- start the tool IF AND ONLY IF you have ALL the information needed.
269
- There are three options for this test:
270
- 1: One time test. Information Needed : (Start_Date : str[dd/mm/yy].)
271
- 2: Periodic test. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy].)
272
- 3: Driving Mode. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy].)
273
- So first of all you have to understand which tetst does the user wants to do. Then you have to find the informaton needed for that test.Users alway forget something, if you are missing some info, just pass none.In the field date, if users says now or today, just pass now or today. NEVER CREATE INPUT IF NOT WRITTEN BY THE USER. IN THE INPUT PASS THE INFORMATION IN JSON FORMAT. IN THE INPUR PASS THE SPECIFIED TET TYPE, ask if missing test_type:(One time test/Periodic test/Driving Mode)"""
274
- ),
275
- Tool(
276
- name="wifi_test",
277
- func=lambda prompt: wifi_test(prompt),
278
- description="""Use when the user wants to do a wifi_test,
279
- start the tool IF AND ONLY IF you have ALL the information needed.
280
- There are three options for this test:
281
- 1: One time test. Information Needed : (Start_Date : str[dd/mm/yy].)
282
- 2: Periodic test. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy].)
283
- 3: Driving Mode. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy].)
284
- So first of all you have to understand which tetst does the user wants to do. Then you have to find the informaton needed for that test.Users alway forget something, if you are missing some info, just pass none.In the field date, if users says now or today, just pass now or today. NEVER CREATE INPUT IF NOT WRITTEN BY THE USER. IN THE INPUT PASS THE INFORMATION IN JSON FORMAT. IN THE INPUR PASS THE SPECIFIED TET TYPE, ask if missing test_type:(One time test/Periodic test/Driving Mode)"""
285
-
286
- ),
287
- Tool(
288
- name="iot_test",
289
- func=lambda prompt: iot_test(prompt),
290
- description="""Use when the user wants to do a iot_test,
291
- start the tool IF AND ONLY IF you have ALL the information needed.
292
- There are three options for this test:
293
- 1: One time test. Information Needed : (Start_Date : str[dd/mm/yy], Mqtt broker address: str, Quality of Service (QoS): int[default:0], Mqtt Message Count: int[default:200] )
294
- 2: Periodic test. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy], Mqtt broker address: str, Quality of Service (QoS): int[default:0], Mqtt Message Count: int[default:200] )
295
- 3: Driving Mode. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy] Mqtt broker address: str, Quality of Service (QoS): int[default:0], Mqtt Message Count: int[default:200] )
296
- So first of all you have to understand which tetst does the user wants to do. Then you have to find the informaton needed for that test.Users alway forget something, if you are missing some info, just pass none.In the field date, if users says now or today, just pass now or today. NEVER CREATE INPUT IF NOT WRITTEN BY THE USER. IN THE INPUT PASS THE INFORMATION IN JSON FORMAT. IN THE INPUR PASS THE SPECIFIED TET TYPE, ask if missing test_type:(One time test/Periodic test/Driving Mode)"""
297
- ),
298
- Tool(
299
- name="online_gaming_test",
300
- func=lambda prompt: online_gaming_test(prompt),
301
- description="""Use when the user wants to do a online_gaming_test,
302
- start the tool IF AND ONLY IF you have ALL the information needed.
303
- There are three options for this test:
304
- 1: One time test. Information Needed : (Start_Date : str[dd/mm/yy], predefined_gaming_servers: str[options: FORTNITE/PUBG])
305
- 2: Periodic test. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy], predefined_gaming_servers: str[options: FORTNITE/PUBG])
306
- 3: Driving Mode. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy] predefined_gaming_servers: str[options: FORTNITE/PUBG])
307
- So first of all you have to understand which tetst does the user wants to do. Then you have to find the informaton needed for that test.Users alway forget something, if you are missing some info, just pass none.In the field date, if users says now or today, just pass now or today. NEVER CREATE INPUT IF NOT WRITTEN BY THE USER. IN THE INPUT PASS THE INFORMATION IN JSON FORMAT. IN THE INPUR PASS THE SPECIFIED TET TYPE, ask if missing test_type:(One time test/Periodic test/Driving Mode)"""
308
- ),
309
- Tool(
310
- name="ping_test",
311
- func=lambda prompt: ping_test(prompt),
312
- description="""Use when the user wants to do a ping_test,
313
- start the tool IF AND ONLY IF you have ALL the information needed.
314
- There are three options for this test:
315
- 1: One time test. Information Needed : (Start_Date : str[dd/mm/yy], host_or_ip: str/int, ping_count: int[predefined: 5])
316
- 2: Periodic test. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy], host_or_ip: str/int, ping_count: int[predefined: 5])
317
- 3: Driving Mode. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy], host_or_ip: str/int, ping_count: int[predefined: 5])
318
- So first of all you have to understand which tetst does the user wants to do. Then you have to find the informaton needed for that test.Users alway forget something, if you are missing some info, just pass none.In the field date, if users says now or today, just pass now or today. NEVER CREATE INPUT IF NOT WRITTEN BY THE USER. IN THE INPUT PASS THE INFORMATION IN JSON FORMAT. IN THE INPUR PASS THE SPECIFIED TET TYPE, ask if missing test_type:(One time test/Periodic test/Driving Mode)"""
319
- )
320
-
321
-
322
-
323
- ]
324
-
325
- # Set Streamlit page configuration
326
- st.set_page_config(page_title="🧠MemoryBot🤖", layout="centered")
327
-
328
- hide_st_style = """
329
- <style>
330
- #MainMenu {visibility: hidden;}
331
- footer {visibility: hidden;}
332
- header {visibility: hidden;}
333
- </style>
334
- """
335
- st.markdown(hide_st_style, unsafe_allow_html=True)
336
-
337
- # Initialize session states
338
- if "generated" not in st.session_state:
339
- st.session_state["generated"] = []
340
- if "past" not in st.session_state:
341
- st.session_state["past"] = []
342
- if "input" not in st.session_state:
343
- st.session_state["input"] = ""
344
- if "stored_session" not in st.session_state:
345
- st.session_state["stored_session"] = []
346
-
347
- # Define function to get user input
348
-
349
-
350
- def get_text():
351
- """
352
- Get the user input text.
353
-
354
- Returns:
355
- (str): The text entered by the user
356
- """
357
- input_text = st.text_input(
358
- "You: ",
359
- st.session_state["input"],
360
- key="input",
361
- placeholder="Enter a command or query here...",
362
- label_visibility="hidden",
363
- )
364
- return input_text
365
-
366
-
367
- def new_chat():
368
- """
369
- Clears session state and starts a new chat.
370
- """
371
- save = []
372
- for i in range(len(st.session_state["generated"]) - 1, -1, -1):
373
- save.append("User:" + st.session_state["past"][i])
374
- save.append("Bot:" + st.session_state["generated"][i])
375
- st.session_state["stored_session"].append(save)
376
- st.session_state["generated"] = []
377
- st.session_state["past"] = []
378
- st.session_state["input"] = ""
379
-
380
-
381
- with st.sidebar.expander(" 🛠️ Settings ", expanded=False):
382
- MODEL = st.selectbox(
383
- label="Model",
384
- options=[
385
- "gpt-4-1106-preview",
386
- "gpt-4-turbo",
387
- "gpt-4",
388
- ],
389
- )
390
-
391
- st.title("🧠 Memory Bot 🤖")
392
- st.markdown(
393
- """
394
- > :black[**A Chatbot that remembers** Made By - Bridge2e]
395
- """
396
- )
397
-
398
- # Ask the user to enter their OpenAI API key
399
-
400
- # Session state storage would be ideal
401
- if API_O:
402
- # Load the tools
403
- # Initialize the memory object
404
- memory = CustomMemory()
405
- # Initialize the agent with the memory object
406
- agent = initialize_agent(
407
- tools,
408
- ChatOpenAI(temperature=0, model_name=MODEL, openai_api_key=API_O),
409
- agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,
410
- memory=memory,
411
- verbose=True,
412
- )
413
-
414
- # Add a button to start a new chat
415
- st.sidebar.button("New Chat", on_click=new_chat, type="primary")
416
-
417
- # Get the user input
418
- user_input = get_text()
419
-
420
- # Generate the output using the agent and the user input, and add the input/output to the session
421
- if user_input:
422
- with st.spinner("Processing..."):
423
- output = agent.run(
424
- input=user_input, chat_history=st.session_state.past)
425
- st.session_state.past.append(user_input)
426
- st.session_state.generated.append(output)
427
-
428
- download_str = []
429
- # Display the conversation history using an expander, and allow the user to download it
430
- with st.expander("Conversation", expanded=True):
431
- for i in range(len(st.session_state["generated"]) - 1, -1, -1):
432
- st.info(st.session_state["past"][i], icon="🧐")
433
- st.success(st.session_state["generated"][i], icon="🤖")
434
- download_str.append(st.session_state["past"][i])
435
- download_str.append(st.session_state["generated"][i])
436
-
437
- # Can throw error - requires fix
438
- # download_str = "\n".join(download_str)
439
- # if download_str:
440
- # st.download_button("Download", download_str)
441
-
442
- # Display stored conversation sessions in the sidebar
443
- for i, sublist in enumerate(st.session_state.stored_session):
444
- with st.sidebar.expander(label=f"Conversation-Session:{i}"):
445
- st.write(sublist)
446
-
447
- # Allow the user to clear all stored conversation sessions
448
- if st.session_state.stored_session:
449
- if st.sidebar.checkbox("Clear-all"):
450
- del st.session_state.stored_session
451
-
452
- with st.sidebar:
453
- st.markdown("---")
 
1
+ import streamlit as st
2
+ from langchain.agents import AgentType, initialize_agent
3
+ from langchain_community.chat_models import ChatOpenAI
4
+ from langchain.schema import SystemMessage
5
+ from langchain.prompts import MessagesPlaceholder
6
+ from typing import Dict, Any
7
+ from langchain.memory import ConversationBufferMemory
8
+ from langchain.agents import initialize_agent, Tool
9
+ import requests
10
+ from datetime import datetime
11
+ import os
12
+
13
+ API_O = os.environ.get("OPENAI_API_KEY")
14
+
15
+
16
+ class CustomMemory(ConversationBufferMemory):
17
+ def _get_input_output(self, inputs: Dict[str, Any], outputs: Dict[str, Any]) -> tuple:
18
+ input_str = inputs.get("input", "")
19
+ chat_history = inputs.get("chat_history", [])
20
+ input_str = f"Human: {input_str}\nChat History: {chat_history}\n"
21
+ output_str = outputs.get("result", "")
22
+ return input_str, output_str
23
+
24
+
25
+ def get_chat_completion(user_message, content):
26
+ # Define the API endpoint
27
+ url = "https://api.openai.com/v1/chat/completions"
28
+
29
+ # Define the headers
30
+ headers = {
31
+ "Content-Type": "application/json",
32
+ "Authorization": f"Bearer {API_O}"
33
+ }
34
+
35
+ # Define the data payload
36
+ data = {
37
+ "model": "gpt-4-1106-preview",
38
+ "messages": [
39
+ {
40
+ "role": "system",
41
+ "content": content
42
+ },
43
+ {
44
+ "role": "user",
45
+ "content": user_message
46
+ }
47
+ ]
48
+ }
49
+ # Send the request
50
+ response = requests.post(url, headers=headers, json=data)
51
+ # Return the JSON response
52
+ return str(response.json()["choices"][0]["message"]["content"]).lower()
53
+
54
+
55
+ def video_streaming_Test(prompt):
56
+ test_name = "video_streaming_Test"
57
+ content_one_time_test = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt the Start_Date is present, No if is missing. IF 'null' is in the input , the answer is NO. ACCEPTED ANSWER : YES / NO."
58
+ content_multiple_tests = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt, both Number_of_tests, Start_Date are present, No if even only one is missing.IF 'null' is in the input , the answer is NO. THERE CAN BE MORE IN THE PROMPT, YOU DON'T HAVE TO CAARE ABOUT IT. ACCEPTED ANSWER : YES / NO."
59
+
60
+ if "One time test" in prompt:
61
+ if "now" in prompt:
62
+ now = datetime.now()
63
+ formatted_date = str(now.strftime("%d/%m/%Y"))
64
+ prompt = prompt.replace("now", formatted_date)
65
+ elif "today" in prompt:
66
+ now = datetime.now()
67
+ formatted_date = str(now.strftime("%d/%m/%Y"))
68
+ prompt = prompt.replace("today", formatted_date)
69
+
70
+ response = get_chat_completion(prompt, content_one_time_test)
71
+ if "yes" in str(response).lower():
72
+ print(prompt)
73
+ return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Start_Date: selected_start_date}}"
74
+ else:
75
+ return "There are some infomration needed missing, information needed: Start_Date "
76
+
77
+ elif "Periodic test" in prompt or "Driving Mode" in prompt:
78
+ if "now" in prompt:
79
+ now = datetime.now()
80
+ formatted_date = str(now.strftime("%d/%m/%Y"))
81
+ prompt = prompt.replace("now", formatted_date)
82
+ elif "today" in prompt:
83
+ now = datetime.now()
84
+ formatted_date = str(now.strftime("%d/%m/%Y"))
85
+ prompt = prompt.replace("today", formatted_date)
86
+
87
+ response = get_chat_completion(prompt, content_multiple_tests)
88
+ if "yes" in str(response).lower():
89
+ print(prompt)
90
+ return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Number_of_tests: selected_number_of_tests, Start_Date: selected_start_date}}"
91
+ else:
92
+ return "There are some infomration needed missing, information needed: Number_of_tests, Start_Date "
93
+ else:
94
+ return "seems like the user did not specify the type of test: Possible choiches: 1.One time test, 2.Periodic test, 3.Driving Mode "
95
+
96
+
97
+ def wifi_test(prompt):
98
+ test_name = "wifi_test"
99
+
100
+ content_one_time_test = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt the Start_Date is present, No if is missing. IF 'null' is in the input , the answer is NO. ACCEPTED ANSWER : YES / NO."
101
+ content_multiple_tests = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt, both Number_of_tests, Start_Date are present, No if even only one is missing.IF 'null' is in the input , the answer is NO. THERE CAN BE MORE IN THE PROMPT, YOU DON'T HAVE TO CAARE ABOUT IT. ACCEPTED ANSWER : YES / NO."
102
+ if "One time test" in prompt:
103
+ if "now" in prompt:
104
+ now = datetime.now()
105
+ formatted_date = str(now.strftime("%d/%m/%Y"))
106
+ prompt = prompt.replace("now", formatted_date)
107
+ elif "today" in prompt:
108
+ now = datetime.now()
109
+ formatted_date = str(now.strftime("%d/%m/%Y"))
110
+ prompt = prompt.replace("today", formatted_date)
111
+
112
+ response = get_chat_completion(prompt, content_one_time_test)
113
+ if "yes" in str(response).lower():
114
+ print(prompt)
115
+ return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Start_Date: selected_start_date}}"
116
+ else:
117
+ return "There are some infomration needed missing, information needed: Start_Date "
118
+ elif "Periodic test" in prompt or "Driving Mode" in prompt:
119
+ if "now" in prompt:
120
+ now = datetime.now()
121
+ formatted_date = str(now.strftime("%d/%m/%Y"))
122
+ prompt = prompt.replace("now", formatted_date)
123
+ elif "today" in prompt:
124
+ now = datetime.now()
125
+ formatted_date = str(now.strftime("%d/%m/%Y"))
126
+ prompt = prompt.replace("today", formatted_date)
127
+
128
+ response = get_chat_completion(prompt, content_multiple_tests)
129
+ if "yes" in str(response).lower():
130
+ print(prompt)
131
+ return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Number_of_tests: selected_number_of_tests, Start_Date: selected_start_date}}"
132
+ else:
133
+ return "There are some infomration needed missing, information needed: Number_of_tests, Start_Date "
134
+ else:
135
+ return "seems like the user did not specify the type of test: Possible choiches: 1.One time test, 2.Periodic test, 3.Driving Mode "
136
+
137
+
138
+ def iot_test(prompt):
139
+ test_name = "iot_test"
140
+
141
+ content_one_time_test = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt all the following are present: 1: Start_Date, 2: Mqtt broker address, 3: Quality of Service (QoS), 4: Mqtt Message Count; No if even only one is missing. IF 'null' is in the input , the answer is NO. ACCEPTED ANSWER : YES / NO."
142
+ content_multiple_tests = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt, all the following are present: 1: Number_of_tests, 2: Start_Date, 3: Mqtt broker address, 4: Quality of Service (QoS), 5: Mqtt Message Count; are present, No if even only one is missing.IF 'null' is in the input , the answer is NO. THERE CAN BE MORE IN THE PROMPT, YOU DON'T HAVE TO CARE ABOUT IT, . ACCEPTED ANSWER : YES / NO."
143
+ if "One time test" in prompt:
144
+ if "now" in prompt:
145
+ now = datetime.now()
146
+ formatted_date = str(now.strftime("%d/%m/%Y"))
147
+ prompt = prompt.replace("now", formatted_date)
148
+ elif "today" in prompt:
149
+ now = datetime.now()
150
+ formatted_date = str(now.strftime("%d/%m/%Y"))
151
+ prompt = prompt.replace("today", formatted_date)
152
+
153
+ response = get_chat_completion(prompt, content_one_time_test)
154
+ if "yes" in str(response).lower():
155
+ print(prompt)
156
+ return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Start_Date: selected_start_date, Mqtt broker address: selected_Mqtt_broker_address, Quality of Service (QoS): selected_Quality_of_Service, Mqtt Message Count: selected_Mqtt_Message_Count }}"
157
+ else:
158
+ return "There are some infomration needed missing, information needed: 1: Start_Date, 2: Mqtt broker address, 3: Quality of Service (QoS), 4: Mqtt Message Count "
159
+
160
+ elif "Periodic test" in prompt or "Driving Mode" in prompt:
161
+ if "now" in prompt:
162
+ now = datetime.now()
163
+ formatted_date = str(now.strftime("%d/%m/%Y"))
164
+ prompt = prompt.replace("now", formatted_date)
165
+ elif "today" in prompt:
166
+ now = datetime.now()
167
+ formatted_date = str(now.strftime("%d/%m/%Y"))
168
+ prompt = prompt.replace("today", formatted_date)
169
+
170
+ response = get_chat_completion(prompt, content_multiple_tests)
171
+ if "yes" in str(response).lower():
172
+ print(prompt)
173
+ return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Number_of_tests: selected_number_of_tests, Start_Date: selected_start_date, Mqtt broker address: selected_Mqtt_broker_address, Quality of Service (QoS): selected_Quality_of_Service, Mqtt Message Count}}"
174
+ else:
175
+ return "There are some infomration needed missing, information needed: 1: Number_of_tests, 2: Start_Date, 3: Mqtt broker address, 4: Quality of Service (QoS), 5: Mqtt Message "
176
+ else:
177
+ return "seems like the user did not specify the type of test: Possible choiches: 1.One time test, 2.Periodic test, 3.Driving Mode "
178
+
179
+
180
+ def online_gaming_test(prompt):
181
+ test_name = "online_gaming_test"
182
+
183
+ content_one_time_test = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt both the Start_Date and the predefined_gaming_servers are present, No if even only one is missing. IF 'null' is in the input , the answer is NO. ACCEPTED ANSWER : YES / NO."
184
+ content_multiple_tests = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt, all the following Number_of_tests, Start_Date, predefined_gaming_servers are present, No if even only one is missing.IF 'null' is in the input , the answer is NO. THERE CAN BE MORE IN THE PROMPT, YOU DON'T HAVE TO CAARE ABOUT IT. ACCEPTED ANSWER : YES / NO."
185
+ if "One time test" in prompt:
186
+ if "now" in prompt:
187
+ now = datetime.now()
188
+ formatted_date = str(now.strftime("%d/%m/%Y"))
189
+ prompt = prompt.replace("now", formatted_date)
190
+ elif "today" in prompt:
191
+ now = datetime.now()
192
+ formatted_date = str(now.strftime("%d/%m/%Y"))
193
+ prompt = prompt.replace("today", formatted_date)
194
+
195
+ response = get_chat_completion(prompt, content_one_time_test)
196
+ if "yes" in str(response).lower():
197
+ print(prompt)
198
+ return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Start_Date: selected_start_date, game_servers: predefined_gaming_servers}}"
199
+ else:
200
+ return "There are some infomration needed missing, information needed: Start_Date, predefined_gaming_servers "
201
+ elif "Periodic test" in prompt or "Driving Mode" in prompt:
202
+ if "now" in prompt:
203
+ now = datetime.now()
204
+ formatted_date = str(now.strftime("%d/%m/%Y"))
205
+ prompt = prompt.replace("now", formatted_date)
206
+ elif "today" in prompt:
207
+ now = datetime.now()
208
+ formatted_date = str(now.strftime("%d/%m/%Y"))
209
+ prompt = prompt.replace("today", formatted_date)
210
+
211
+ response = get_chat_completion(prompt, content_multiple_tests)
212
+ if "yes" in str(response).lower():
213
+ print(prompt)
214
+ return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Number_of_tests: selected_number_of_tests, Start_Date: selected_start_date, game_servers: predefined_gaming_servers}}"
215
+
216
+ else:
217
+ return "There are some infomration needed missing, information needed: Number_of_tests, Start_Date, predefined_gaming_servers "
218
+ else:
219
+ return "seems like the user did not specify the type of test: Possible choiches: 1.One time test, 2.Periodic test, 3.Driving Mode "
220
+
221
+
222
+ def ping_test(prompt):
223
+ test_name = "ping_test"
224
+
225
+ content_one_time_test = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt all the following: host_or_ip, ping_count, Start_Date are present, No if even only one is missing. IF 'null' is in the input , the answer is NO. ACCEPTED ANSWER : YES / NO."
226
+ content_multiple_tests = "you only answer in shematic format,possibile asnwer are YES, NO. YES if in the prompt, all the following: host_or_ip, ping_count, Number_of_tests, Start_Date are present, No if even only one is missing.IF 'null' is in the input , the answer is NO. THERE CAN BE MORE IN THE PROMPT, YOU DON'T HAVE TO CAARE ABOUT IT. ACCEPTED ANSWER : YES / NO."
227
+ if "One time test" in prompt:
228
+ if "now" in prompt:
229
+ now = datetime.now()
230
+ formatted_date = str(now.strftime("%d/%m/%Y"))
231
+ prompt = prompt.replace("now", formatted_date)
232
+ elif "today" in prompt:
233
+ now = datetime.now()
234
+ formatted_date = str(now.strftime("%d/%m/%Y"))
235
+ prompt = prompt.replace("today", formatted_date)
236
+
237
+ response = get_chat_completion(prompt, content_one_time_test)
238
+ if "yes" in str(response).lower():
239
+ print(prompt)
240
+ return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Start_Date: selected_start_date,host_or_ip: selected_host_or_ip, ping_count: selected_ping_count }}"
241
+ else:
242
+ return "There are some infomration needed missing, information needed: Start_Date ,host_or_ip, ping_count"
243
+ elif "Periodic test" in prompt or "Driving Mode" in prompt:
244
+ if "now" in prompt:
245
+ now = datetime.now()
246
+ formatted_date = str(now.strftime("%d/%m/%Y"))
247
+ prompt = prompt.replace("now", formatted_date)
248
+ elif "today" in prompt:
249
+ now = datetime.now()
250
+ formatted_date = str(now.strftime("%d/%m/%Y"))
251
+ prompt = prompt.replace("today", formatted_date)
252
+
253
+ response = get_chat_completion(prompt, content_multiple_tests)
254
+ if "yes" in str(response).lower():
255
+ print(prompt)
256
+ return f"report to the user the following json file , test started successfully: {{test_name: {test_name}, type of test : selected_type_of_test, Number_of_tests: selected_number_of_tests, Start_Date: selected_start_date,host_or_ip: selected_host_or_ip, ping_count: selected_ping_count }}"
257
+ else:
258
+ return "There are some infomration needed missing, information needed: Number_of_tests, Start_Date, host_or_ip ping_count"
259
+ else:
260
+ return "seems like the user did not specify the type of test: Possible choiches: 1.One time test, 2.Periodic test, 3.Driving Mode "
261
+
262
+
263
+ tools = [
264
+ Tool(
265
+ name="video_streaming_Test",
266
+ func=lambda prompt: video_streaming_Test(prompt),
267
+ description="""Use when the user wants to do a video_streaming_Test,
268
+ start the tool IF AND ONLY IF you have ALL the information needed.
269
+ There are three options for this test, FIRST OF ALL YOU ALWAYS MUST KNOW WHICH ONE THE USER WANT, IF YOU DON'T KNOW, ASK. NEVER MAKE UP ONE:
270
+ 1: One time test. Information Needed : (Start_Date : str[dd/mm/yy].)
271
+ 2: Periodic test. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy].)
272
+ 3: Driving Mode. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy].)
273
+ So first of all you have to understand which tetst does the user wants to do.IF IS MISSING, ask back. Then you have to find the informaton needed for that test.Users alway forget something, if you are missing some info, just pass none.In the field date, if users says now or today, just pass now or today. NEVER CREATE INPUT IF NOT WRITTEN BY THE USER. IN THE INPUT PASS THE INFORMATION IN JSON FORMAT. IN THE INPUR PASS THE SPECIFIED TET TYPE, ask if missing test_type:(One time test/Periodic test/Driving Mode)"""
274
+ ),
275
+ Tool(
276
+ name="wifi_test",
277
+ func=lambda prompt: wifi_test(prompt),
278
+ description="""Use when the user wants to do a wifi_test,
279
+ start the tool IF AND ONLY IF you have ALL the information needed.
280
+ There are three options for this test, FIRST OF ALL YOU ALWAYS MUST KNOW WHICH ONE THE USER WANT, IF YOU DON'T KNOW, ASK. NEVER MAKE UP ONE:
281
+ 1: One time test. Information Needed : (Start_Date : str[dd/mm/yy].)
282
+ 2: Periodic test. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy].)
283
+ 3: Driving Mode. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy].)
284
+ So first of all you have to understand which tetst does the user wants to do.IF IS MISSING, ask back. Then you have to find the informaton needed for that test.Users alway forget something, if you are missing some info, just pass none.In the field date, if users says now or today, just pass now or today. NEVER CREATE INPUT IF NOT WRITTEN BY THE USER. IN THE INPUT PASS THE INFORMATION IN JSON FORMAT. IN THE INPUR PASS THE SPECIFIED TET TYPE, ask if missing test_type:(One time test/Periodic test/Driving Mode)"""
285
+
286
+ ),
287
+ Tool(
288
+ name="iot_test",
289
+ func=lambda prompt: iot_test(prompt),
290
+ description="""Use when the user wants to do a iot_test,
291
+ start the tool IF AND ONLY IF you have ALL the information needed.
292
+ There are three options for this , FIRST OF ALL YOU ALWAYS MUST KNOW WHICH ONE THE USER WANT, IF YOU DON'T KNOW, ASK. NEVER MAKE UP ONE:
293
+ 1: One time test. Information Needed : (Start_Date : str[dd/mm/yy], Mqtt broker address: str, Quality of Service (QoS): int[default:0], Mqtt Message Count: int[default:200] )
294
+ 2: Periodic test. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy], Mqtt broker address: str, Quality of Service (QoS): int[default:0], Mqtt Message Count: int[default:200] )
295
+ 3: Driving Mode. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy] Mqtt broker address: str, Quality of Service (QoS): int[default:0], Mqtt Message Count: int[default:200] )
296
+ So first of all you have to understand which tetst does the user wants to do. IF IS MISSING, ask back. Then you have to find the informaton needed for that test.Users alway forget something, if you are missing some info, just pass none.In the field date, if users says now or today, just pass now or today. NEVER CREATE INPUT IF NOT WRITTEN BY THE USER. IN THE INPUT PASS THE INFORMATION IN JSON FORMAT. IN THE INPUR PASS THE SPECIFIED TET TYPE, ask if missing test_type:(One time test/Periodic test/Driving Mode)"""
297
+ ),
298
+ Tool(
299
+ name="online_gaming_test",
300
+ func=lambda prompt: online_gaming_test(prompt),
301
+ description="""Use when the user wants to do a online_gaming_test,
302
+ start the tool IF AND ONLY IF you have ALL the information needed.
303
+ There are three options for this test, FIRST OF ALL YOU ALWAYS MUST KNOW WHICH ONE THE USER WANT, IF YOU DON'T KNOW, ASK. NEVER MAKE UP ONE:
304
+ 1: One time test. Information Needed : (Start_Date : str[dd/mm/yy], predefined_gaming_servers: str[options: FORTNITE/PUBG])
305
+ 2: Periodic test. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy], predefined_gaming_servers: str[options: FORTNITE/PUBG])
306
+ 3: Driving Mode. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy] predefined_gaming_servers: str[options: FORTNITE/PUBG])
307
+ So first of all you have to understand which tetst does the user wants to do. IF IS MISSING, ask back. Then you have to find the informaton needed for that test.Users alway forget something, if you are missing some info, just pass none.In the field date, if users says now or today, just pass now or today. NEVER CREATE INPUT IF NOT WRITTEN BY THE USER. IN THE INPUT PASS THE INFORMATION IN JSON FORMAT. IN THE INPUR PASS THE SPECIFIED TET TYPE, ask if missing test_type:(One time test/Periodic test/Driving Mode)"""
308
+ ),
309
+ Tool(
310
+ name="ping_test",
311
+ func=lambda prompt: ping_test(prompt),
312
+ description="""Use when the user wants to do a ping_test,
313
+ start the tool IF AND ONLY IF you have ALL the information needed.
314
+ There are three options for this test, FIRST OF ALL YOU ALWAYS MUST KNOW WHICH ONE THE USER WANT, IF YOU DON'T KNOW, ASK. NEVER MAKE UP ONE:
315
+ 1: One time test. Information Needed : (Start_Date : str[dd/mm/yy], host_or_ip: str/int, ping_count: int[predefined: 5])
316
+ 2: Periodic test. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy], host_or_ip: str/int, ping_count: int[predefined: 5])
317
+ 3: Driving Mode. Information Needed : (Number_of_tests : int, Start_Date : str[dd/mm/yy], host_or_ip: str/int, ping_count: int[predefined: 5])
318
+ So first of all you have to understand which tetst does the user wants to do. IF IS MISSING, ask back. Then you have to find the informaton needed for that test.Users alway forget something, if you are missing some info, just pass none.In the field date, if users says now or today, just pass now or today. NEVER CREATE INPUT IF NOT WRITTEN BY THE USER. IN THE INPUT PASS THE INFORMATION IN JSON FORMAT. IN THE INPUR PASS THE SPECIFIED TET TYPE, ask if missing test_type:(One time test/Periodic test/Driving Mode)"""
319
+ )
320
+
321
+
322
+
323
+ ]
324
+
325
+ # Set Streamlit page configuration
326
+ st.set_page_config(page_title="🧠MemoryBot🤖", layout="centered")
327
+
328
+ hide_st_style = """
329
+ <style>
330
+ #MainMenu {visibility: hidden;}
331
+ footer {visibility: hidden;}
332
+ header {visibility: hidden;}
333
+ </style>
334
+ """
335
+ st.markdown(hide_st_style, unsafe_allow_html=True)
336
+
337
+ # Initialize session states
338
+ if "generated" not in st.session_state:
339
+ st.session_state["generated"] = []
340
+ if "past" not in st.session_state:
341
+ st.session_state["past"] = []
342
+ if "input" not in st.session_state:
343
+ st.session_state["input"] = ""
344
+ if "stored_session" not in st.session_state:
345
+ st.session_state["stored_session"] = []
346
+
347
+ # Define function to get user input
348
+
349
+
350
+ def get_text():
351
+ """
352
+ Get the user input text.
353
+
354
+ Returns:
355
+ (str): The text entered by the user
356
+ """
357
+ input_text = st.text_input(
358
+ "You: ",
359
+ st.session_state["input"],
360
+ key="input",
361
+ placeholder="Enter a command or query here...",
362
+ label_visibility="hidden",
363
+ )
364
+ return input_text
365
+
366
+
367
+ def new_chat():
368
+ """
369
+ Clears session state and starts a new chat.
370
+ """
371
+ save = []
372
+ for i in range(len(st.session_state["generated"]) - 1, -1, -1):
373
+ save.append("User:" + st.session_state["past"][i])
374
+ save.append("Bot:" + st.session_state["generated"][i])
375
+ st.session_state["stored_session"].append(save)
376
+ st.session_state["generated"] = []
377
+ st.session_state["past"] = []
378
+ st.session_state["input"] = ""
379
+
380
+
381
+ with st.sidebar.expander(" 🛠️ Settings ", expanded=False):
382
+ MODEL = st.selectbox(
383
+ label="Model",
384
+ options=[
385
+ "gpt-4-1106-preview",
386
+ "gpt-4-turbo",
387
+ "gpt-4",
388
+ ],
389
+ )
390
+
391
+ st.title("🧠 Memory Bot 🤖")
392
+ st.markdown(
393
+ """
394
+ > :black[**A Chatbot that remembers** Made By - Bridge2e]
395
+ """
396
+ )
397
+
398
+ # Ask the user to enter their OpenAI API key
399
+
400
+ # Session state storage would be ideal
401
+ if API_O:
402
+ # Load the tools
403
+ # Initialize the memory object
404
+ memory = CustomMemory()
405
+ # Initialize the agent with the memory object
406
+ agent = initialize_agent(
407
+ tools,
408
+ ChatOpenAI(temperature=0, model_name=MODEL, openai_api_key=API_O),
409
+ agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,
410
+ memory=memory,
411
+ verbose=True,
412
+ )
413
+
414
+ # Add a button to start a new chat
415
+ st.sidebar.button("New Chat", on_click=new_chat, type="primary")
416
+
417
+ # Get the user input
418
+ user_input = get_text()
419
+
420
+ # Generate the output using the agent and the user input, and add the input/output to the session
421
+ if user_input:
422
+ with st.spinner("Processing..."):
423
+ output = agent.run(
424
+ input=user_input, chat_history=st.session_state.past)
425
+ st.session_state.past.append(user_input)
426
+ st.session_state.generated.append(output)
427
+
428
+ download_str = []
429
+ # Display the conversation history using an expander, and allow the user to download it
430
+ with st.expander("Conversation", expanded=True):
431
+ for i in range(len(st.session_state["generated"]) - 1, -1, -1):
432
+ st.info(st.session_state["past"][i], icon="🧐")
433
+ st.success(st.session_state["generated"][i], icon="🤖")
434
+ download_str.append(st.session_state["past"][i])
435
+ download_str.append(st.session_state["generated"][i])
436
+
437
+ # Can throw error - requires fix
438
+ # download_str = "\n".join(download_str)
439
+ # if download_str:
440
+ # st.download_button("Download", download_str)
441
+
442
+ # Display stored conversation sessions in the sidebar
443
+ for i, sublist in enumerate(st.session_state.stored_session):
444
+ with st.sidebar.expander(label=f"Conversation-Session:{i}"):
445
+ st.write(sublist)
446
+
447
+ # Allow the user to clear all stored conversation sessions
448
+ if st.session_state.stored_session:
449
+ if st.sidebar.checkbox("Clear-all"):
450
+ del st.session_state.stored_session
451
+
452
+ with st.sidebar:
453
+ st.markdown("---")