IamVicky111 commited on
Commit
7ef7173
·
verified ·
1 Parent(s): 1d06d75

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +168 -0
  2. requirements.txt +7 -0
app.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Import necessary libraries
3
+ import streamlit as st
4
+ from langchain.chat_models import ChatOpenAI
5
+ # from langchain import ConversationChain, LLMChain, PromptTemplate
6
+ from langchain.memory import ConversationBufferWindowMemory
7
+ from langchain.text_splitter import CharacterTextSplitter
8
+ from langchain.vectorstores import Chroma
9
+ from langchain.embeddings import OpenAIEmbeddings
10
+ from langchain.chains import RetrievalQA
11
+ from PyPDF2 import PdfReader
12
+ from typing_extensions import Concatenate
13
+
14
+ from langchain.chains import LLMChain
15
+ from langchain_community.llms import OpenAI
16
+ from langchain_core.prompts import PromptTemplate
17
+
18
+ import os
19
+
20
+ # Initialize session states
21
+ if "past" not in st.session_state:
22
+ st.session_state["past"] = []
23
+ if "generated" not in st.session_state:
24
+ st.session_state["generated"] = []
25
+ if "input" not in st.session_state:
26
+ st.session_state["input"] = ""
27
+ if "bot_details" not in st.session_state:
28
+ st.session_state["bot_details"] = ""
29
+ if "bot_name" not in st.session_state:
30
+ st.session_state["bot_name"] = ""
31
+ if "raw_text" not in st.session_state:
32
+ st.session_state["raw_text"] = ""
33
+ if "is_created" not in st.session_state:
34
+ st.session_state["is_created"] = False
35
+ if "vectorstore" not in st.session_state:
36
+ st.session_state["vectorstore"] = None
37
+ if "file" not in st.session_state:
38
+ st.session_state["file"] = None
39
+
40
+
41
+ template = """As a highly intelligent and powerful chatbot, your personality is shaped by the following description:
42
+ {description}
43
+
44
+ Your designated name is {name}. Initiate the conversation with a warm greeting only when the user asks something for the first time. Subsequent interactions can skip the greeting.
45
+
46
+ Your generated responses should be comprehensive, utilizing pointers when necessary for an enhanced user experience. Provide detailed answers, and if the user's input isn't related to personality, respond politely with an apology, encouraging them to ask questions related to your established personality. Keep your responses concise and accurate, seeking additional information from the user when required.
47
+
48
+ Incorporate the provided context and any relevant information from the chat history into your responses. If the user's input is related to the context or question, articulate your answer accordingly.
49
+
50
+ {context}
51
+ {chat_history}
52
+ Human: {input}
53
+ Assistant:"""
54
+
55
+ st.set_page_config(page_title=' 🤖ChatGPT with Memory🧠', layout='wide')
56
+
57
+
58
+ prompt = PromptTemplate(
59
+ input_variables=["name", "description",
60
+ "context", "input", "chat_history"],
61
+ template=template
62
+ )
63
+
64
+ chatgpt_chain = LLMChain(
65
+ llm=OpenAI(model_name='gpt-3.5-turbo-16k', temperature=0.7,
66
+ api_key=os.environ.get('OPEN_API_KEY')),
67
+ prompt=prompt,
68
+ verbose="true",
69
+ memory=ConversationBufferWindowMemory(
70
+ memory_key="chat_history", input_key="input", k=5),
71
+ )
72
+
73
+
74
+ def genrate_result():
75
+ if len(st.session_state["input"]) > 0:
76
+ db = st.session_state["vectorstore"]
77
+ result = db.similarity_search(st.session_state["input"])
78
+ inputs = {"input": st.session_state["input"],
79
+ "description": st.session_state["bot_details"],
80
+ "name": st.session_state["bot_name"],
81
+ "context": result[0].page_content
82
+ }
83
+ output = chatgpt_chain.run(inputs)
84
+ st.session_state.past.append(st.session_state["input"])
85
+ st.session_state.generated.append(output)
86
+ st.session_state["input"] = ""
87
+
88
+
89
+ # function to delete the chatbot
90
+ def delete_bot():
91
+ """
92
+ Clears session state and starts a new chat.
93
+ """
94
+ st.session_state["generated"] = []
95
+ st.session_state["past"] = []
96
+ st.session_state["input"] = ""
97
+ st.session_state["bot_details"] = ""
98
+ st.session_state["bot_name"] = ""
99
+ st.session_state["raw_text"] = ""
100
+ st.session_state["is_created"] = False
101
+ st.session_state["vectorstore"] = None
102
+ st.session_state["is_file_uploded"] = False
103
+
104
+
105
+ # set up the stram lit user inputs in slider bar
106
+ with st.sidebar:
107
+ with st.form("my_form"):
108
+ name = st.text_input('Name', key='name',
109
+ type="default", placeholder='Bot Name')
110
+ details = st.text_area(
111
+ "Enter Description", placeholder='Bot Description', key='description', height=100)
112
+ file = st.file_uploader('Document', type='pdf')
113
+
114
+ submitted = st.form_submit_button("Create Bot")
115
+
116
+ if submitted:
117
+ if file and name and details:
118
+ st.session_state["bot_details"] = details
119
+ st.session_state["bot_name"] = name
120
+ loader = PdfReader(file)
121
+ for i, page in enumerate(loader.pages):
122
+ content = page.extract_text()
123
+ if content:
124
+ temp = st.session_state["raw_text"]
125
+ st.session_state["raw_text"] = temp+content
126
+ text_splitter = CharacterTextSplitter(
127
+ separator='\n', chunk_size=600, chunk_overlap=150, length_function=len)
128
+ texts = text_splitter.split_text(
129
+ st.session_state["raw_text"])
130
+ st.session_state["vectorstore"] = Chroma().from_texts(texts, embedding=OpenAIEmbeddings(
131
+ openai_api_key=os.environ.get('OPEN_API_KEY')))
132
+ st.session_state["is_created"] = True
133
+ else:
134
+ st.warning(
135
+ 'Name ,Description and File are required to create chatbot', icon="⚠️")
136
+
137
+ if st.session_state["is_created"] == True:
138
+ st.button('Delete Bot', on_click=delete_bot)
139
+
140
+
141
+ # Set up the Streamlit app layout
142
+ st.title("🤖 Personality Chatbot 🧠")
143
+ st.subheader(" Powered by Coffeebeans")
144
+ hide_default_format = """
145
+ <style>
146
+ #MainMenu {visibility: hidden; }
147
+ footer {visibility: hidden;}
148
+ [data-testid="stVerticalBlock"] > [style*="flex-direction: column;"] > [data-testid="stVerticalBlock"] {
149
+ # overflow: auto;
150
+ # max-height: 300px;
151
+ }
152
+
153
+ </style>
154
+
155
+ """
156
+ st.markdown(hide_default_format, unsafe_allow_html=True)
157
+
158
+
159
+ if st.session_state["is_created"] == True:
160
+ st.text_input("You: ", st.session_state["input"], key="input",
161
+ placeholder="Your AI assistant here! Ask me anything ...",
162
+ on_change=genrate_result(),
163
+ label_visibility='hidden')
164
+
165
+ with st.container():
166
+ for i in range(len(st.session_state['generated'])-1, -1, -1):
167
+ st.success(st.session_state["generated"][i], icon="🤖")
168
+ st.info(st.session_state["past"][i], icon="🧐")
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ langchain
3
+ openai==0.28
4
+ chromadb
5
+ tiktoken
6
+ PyPDF2
7
+ typing-extensions