Stevross commited on
Commit
414ae8a
·
1 Parent(s): 8aac90f

Create app,py

Browse files
Files changed (1) hide show
  1. app,py +135 -0
app,py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This is a Python script that serves as a frontend for a conversational AI model built with the `langchain` and `llms` libraries.
3
+ The code creates a web application using Streamlit, a Python library for building interactive web apps.
4
+ # Author: Avratanu Biswas
5
+ # Date: March 11, 2023
6
+ """
7
+
8
+ # Import necessary libraries
9
+ import streamlit as st
10
+ from langchain.chains import ConversationChain
11
+ from langchain.chains.conversation.memory import ConversationEntityMemory
12
+ from langchain.chains.conversation.prompt import ENTITY_MEMORY_CONVERSATION_TEMPLATE
13
+ from langchain.llms import OpenAI
14
+
15
+ # Set Streamlit page configuration
16
+ st.set_page_config(page_title='🧠MemoryBot🤖', layout='wide')
17
+ # Initialize session states
18
+ if "generated" not in st.session_state:
19
+ st.session_state["generated"] = []
20
+ if "past" not in st.session_state:
21
+ st.session_state["past"] = []
22
+ if "input" not in st.session_state:
23
+ st.session_state["input"] = ""
24
+ if "stored_session" not in st.session_state:
25
+ st.session_state["stored_session"] = []
26
+
27
+ # Define function to get user input
28
+ def get_text():
29
+ """
30
+ Get the user input text.
31
+
32
+ Returns:
33
+ (str): The text entered by the user
34
+ """
35
+ input_text = st.text_input("You: ", st.session_state["input"], key="input",
36
+ placeholder="Your AI assistant here! Ask me anything ...",
37
+ label_visibility='hidden')
38
+ return input_text
39
+
40
+ # Define function to start a new chat
41
+ def new_chat():
42
+ """
43
+ Clears session state and starts a new chat.
44
+ """
45
+ save = []
46
+ for i in range(len(st.session_state['generated'])-1, -1, -1):
47
+ save.append("User:" + st.session_state["past"][i])
48
+ save.append("Bot:" + st.session_state["generated"][i])
49
+ st.session_state["stored_session"].append(save)
50
+ st.session_state["generated"] = []
51
+ st.session_state["past"] = []
52
+ st.session_state["input"] = ""
53
+ st.session_state.entity_memory.entity_store = {}
54
+ st.session_state.entity_memory.buffer.clear()
55
+
56
+ # Set up sidebar with various options
57
+ with st.sidebar.expander("🛠️ ", expanded=False):
58
+ # Option to preview memory store
59
+ if st.checkbox("Preview memory store"):
60
+ with st.expander("Memory-Store", expanded=False):
61
+ st.session_state.entity_memory.store
62
+ # Option to preview memory buffer
63
+ if st.checkbox("Preview memory buffer"):
64
+ with st.expander("Bufffer-Store", expanded=False):
65
+ st.session_state.entity_memory.buffer
66
+ MODEL = st.selectbox(label='Model', options=['gpt-3.5-turbo','text-davinci-003','text-davinci-002','code-davinci-002'])
67
+ K = st.number_input(' (#)Summary of prompts to consider',min_value=3,max_value=1000)
68
+
69
+ # Set up the Streamlit app layout
70
+ st.title("🤖 Chat Bot with 🧠")
71
+ st.subheader(" Powered by 🦜 LangChain + OpenAI + Streamlit")
72
+
73
+ # Ask the user to enter their OpenAI API key
74
+ API_O = st.sidebar.text_input("API-KEY", type="password")
75
+
76
+ # Session state storage would be ideal
77
+ if API_O:
78
+ # Create an OpenAI instance
79
+ llm = OpenAI(temperature=0,
80
+ openai_api_key=API_O,
81
+ model_name=MODEL,
82
+ verbose=False)
83
+
84
+
85
+ # Create a ConversationEntityMemory object if not already created
86
+ if 'entity_memory' not in st.session_state:
87
+ st.session_state.entity_memory = ConversationEntityMemory(llm=llm, k=K )
88
+
89
+ # Create the ConversationChain object with the specified configuration
90
+ Conversation = ConversationChain(
91
+ llm=llm,
92
+ prompt=ENTITY_MEMORY_CONVERSATION_TEMPLATE,
93
+ memory=st.session_state.entity_memory
94
+ )
95
+ else:
96
+ st.sidebar.warning('API key required to try this app.The API key is not stored in any form.')
97
+ # st.stop()
98
+
99
+
100
+ # Add a button to start a new chat
101
+ st.sidebar.button("New Chat", on_click = new_chat, type='primary')
102
+
103
+ # Get the user input
104
+ user_input = get_text()
105
+
106
+ # Generate the output using the ConversationChain object and the user input, and add the input/output to the session
107
+ if user_input:
108
+ output = Conversation.run(input=user_input)
109
+ st.session_state.past.append(user_input)
110
+ st.session_state.generated.append(output)
111
+
112
+ # Allow to download as well
113
+ download_str = []
114
+ # Display the conversation history using an expander, and allow the user to download it
115
+ with st.expander("Conversation", expanded=True):
116
+ for i in range(len(st.session_state['generated'])-1, -1, -1):
117
+ st.info(st.session_state["past"][i],icon="🧐")
118
+ st.success(st.session_state["generated"][i], icon="🤖")
119
+ download_str.append(st.session_state["past"][i])
120
+ download_str.append(st.session_state["generated"][i])
121
+
122
+ # Can throw error - requires fix
123
+ download_str = '\n'.join(download_str)
124
+ if download_str:
125
+ st.download_button('Download',download_str)
126
+
127
+ # Display stored conversation sessions in the sidebar
128
+ for i, sublist in enumerate(st.session_state.stored_session):
129
+ with st.sidebar.expander(label= f"Conversation-Session:{i}"):
130
+ st.write(sublist)
131
+
132
+ # Allow the user to clear all stored conversation sessions
133
+ if st.session_state.stored_session:
134
+ if st.sidebar.checkbox("Clear-all"):
135
+ del st.session_state.stored_session