alex6095 commited on
Commit
dc9cc1a
โ€ข
1 Parent(s): ed4e5a2

Add password & streaming

Browse files
Files changed (1) hide show
  1. app.py +106 -34
app.py CHANGED
@@ -1,5 +1,13 @@
1
  ## Import Modules
2
 
 
 
 
 
 
 
 
 
3
  from langchain.document_loaders.csv_loader import CSVLoader
4
  from langchain.text_splitter import RecursiveCharacterTextSplitter
5
  from langchain.embeddings.openai import OpenAIEmbeddings
@@ -11,12 +19,43 @@ from langchain.prompts import PromptTemplate
11
  from langchain.prompts.few_shot import FewShotPromptTemplate
12
  import os
13
 
 
 
14
  import streamlit as st
15
  from streamlit_chat import message
16
  from PIL import Image
17
 
18
  os.environ['OPENAI_API_KEY'] = st.secrets["OPENAI_API_KEY"]
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  # ์ฃผ์„ ๋ถ€๋ถ„ ์ž๋™์œผ๋กœ ๋˜๋Š” ์˜์—ญ ๊ฐ™์Œ
21
  loader = CSVLoader(file_path='./parsed_texts.csv',
22
  encoding='utf-8',
@@ -148,9 +187,31 @@ fewshot_prompt = FewShotPromptTemplate(
148
 
149
  # print(fewshot_prompt.format(context="Hello, world!", question="Who was the father of Mary Ball Washington?"))
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  ## Load up your LLM
152
  # llm = OpenAI() # 'text-davinci-003', model_name="gpt-4"
153
- chat = ChatOpenAI(model_name="gpt-3.5-turbo-16k") # gpt-3.5-turbo, gpt-3.5-turbo-16k, gpt-4-32k : ์ •์ œ๋œ Prompt 7์žฅ์„ ๋„ฃ์œผ๋ ค๋ฉด Prompt๋งŒ 4k ์ด์ƒ์ด์–ด์•ผ ํ•จ
 
154
 
155
  chain_type_kwargs = {"prompt": fewshot_prompt}
156
  qa = RetrievalQA.from_chain_type(llm=chat,
@@ -163,22 +224,22 @@ qa = RetrievalQA.from_chain_type(llm=chat,
163
 
164
  img = Image.open('resource/hume.jpg')
165
 
166
- def generate_response(prompt):
167
- # query = "How do you define the notion of a cause in his A Treatise of Human Nature? And how is it different from the traditional definition that you reject?"
168
- result = qa({"query": prompt})
169
- message = result['result']
170
- sources = []
171
- for src in result['source_documents']:
172
- if src.page_content.startswith('Paragraph:'):
173
- sources.append(src.metadata['source'])
174
 
175
- if len(sources)==0:
176
- message = message + "\n\n[No sources]"
177
- else:
178
- message = message + "\n\n[" + ", ".join(sources) + "]"
179
 
180
- return message
181
-
182
 
183
  col1, col2, col3 = st.columns(3)
184
 
@@ -194,22 +255,33 @@ with col3:
194
 
195
  st.header("Chat with Hume (Demo)")
196
 
197
- if 'generated' not in st.session_state:
198
- st.session_state['generated'] = []
199
-
200
- if 'past' not in st.session_state:
201
- st.session_state['past'] = []
202
-
203
- with st.form('form', clear_on_submit=True):
204
- user_input = st.text_input('You: ', '', key='input')
205
- submitted = st.form_submit_button('Send')
206
-
207
- if submitted and user_input:
208
- output = generate_response(user_input)
209
- st.session_state.past.append(user_input)
210
- st.session_state.generated.append(output)
211
-
212
- if st.session_state['generated']:
213
- for i in range(len(st.session_state['generated'])-1, -1, -1):
214
- message(st.session_state['past'][i], is_user=True, key=str(i) + '_user')
215
- message(st.session_state["generated"][i], key=str(i))
 
 
 
 
 
 
 
 
 
 
 
 
1
  ## Import Modules
2
 
3
+ from langchain.document_loaders.csv_loader import CSVLoader
4
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
5
+ from langchain.embeddings.openai import OpenAIEmbeddings
6
+ from langchain.vectorstores import FAISS
7
+ from langchain import OpenAI
8
+ from langchain.chains import RetrievalQA
9
+ ## Import Modules
10
+
11
  from langchain.document_loaders.csv_loader import CSVLoader
12
  from langchain.text_splitter import RecursiveCharacterTextSplitter
13
  from langchain.embeddings.openai import OpenAIEmbeddings
 
19
  from langchain.prompts.few_shot import FewShotPromptTemplate
20
  import os
21
 
22
+ # Web App
23
+ import hmac
24
  import streamlit as st
25
  from streamlit_chat import message
26
  from PIL import Image
27
 
28
  os.environ['OPENAI_API_KEY'] = st.secrets["OPENAI_API_KEY"]
29
 
30
+ def check_password():
31
+ """Returns `True` if the user had the correct password."""
32
+
33
+ def password_entered():
34
+ """Checks whether a password entered by the user is correct."""
35
+ # Add at secret
36
+ if hmac.compare_digest(st.session_state["password"], st.secrets["password"]):
37
+ st.session_state["password_correct"] = True
38
+ del st.session_state["password"] # Don't store the password.
39
+ else:
40
+ st.session_state["password_correct"] = False
41
+
42
+ # Return True if the passward is validated.
43
+ if st.session_state.get("password_correct", False):
44
+ return True
45
+
46
+ # Show input for password.
47
+ st.text_input(
48
+ "Password", type="password", on_change=password_entered, key="password"
49
+ )
50
+ if "password_correct" in st.session_state:
51
+ st.error("๐Ÿ˜• Password incorrect")
52
+ return False
53
+
54
+
55
+ if not check_password():
56
+ st.stop() # Do not continue if check_password is not True.
57
+
58
+
59
  # ์ฃผ์„ ๋ถ€๋ถ„ ์ž๋™์œผ๋กœ ๋˜๋Š” ์˜์—ญ ๊ฐ™์Œ
60
  loader = CSVLoader(file_path='./parsed_texts.csv',
61
  encoding='utf-8',
 
187
 
188
  # print(fewshot_prompt.format(context="Hello, world!", question="Who was the father of Mary Ball Washington?"))
189
 
190
+
191
+ # from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
192
+ from langchain.callbacks.base import BaseCallbackHandler
193
+
194
+ class MyCustomHandler(BaseCallbackHandler):
195
+ def __init__(self):
196
+ super().__init__()
197
+ self.tokens = []
198
+
199
+ def on_llm_new_token(self, token: str, **kwargs) -> None:
200
+ # print(f"My custom handler, token: {token}")
201
+ global full_response
202
+ global message_placeholder
203
+ self.tokens.append(token)
204
+ # print(self.tokens)
205
+
206
+ full_response += token
207
+ message_placeholder.markdown(full_response + "โ–Œ")
208
+
209
+
210
+
211
  ## Load up your LLM
212
  # llm = OpenAI() # 'text-davinci-003', model_name="gpt-4"
213
+ # , streaming=True, callbacks=[StreamingStdOutCallbackHandler()]
214
+ chat = ChatOpenAI(model_name="gpt-3.5-turbo-16k", streaming=True, callbacks=[MyCustomHandler()]) # gpt-3.5-turbo, gpt-3.5-turbo-16k, gpt-4-32k : ์ •์ œ๋œ Prompt 7์žฅ์„ ๋„ฃ์œผ๋ ค๋ฉด Prompt๋งŒ 4k ์ด์ƒ์ด์–ด์•ผ ํ•จ
215
 
216
  chain_type_kwargs = {"prompt": fewshot_prompt}
217
  qa = RetrievalQA.from_chain_type(llm=chat,
 
224
 
225
  img = Image.open('resource/hume.jpg')
226
 
227
+ # def generate_response(prompt):
228
+ # # query = "How do you define the notion of a cause in his A Treatise of Human Nature? And how is it different from the traditional definition that you reject?"
229
+ # result = qa({"query": prompt})
230
+ # message = result['result']
231
+ # sources = []
232
+ # for src in result['source_documents']:
233
+ # if src.page_content.startswith('Paragraph:'):
234
+ # sources.append(src.metadata['source'])
235
 
236
+ # if len(sources)==0:
237
+ # message = message + "\n\n[No sources]"
238
+ # else:
239
+ # message = message + "\n\n[" + ", ".join(sources) + "]"
240
 
241
+ # return message
242
+
243
 
244
  col1, col2, col3 = st.columns(3)
245
 
 
255
 
256
  st.header("Chat with Hume (Demo)")
257
 
258
+ if "messages" not in st.session_state:
259
+ st.session_state.messages = []
260
+
261
+ for message in st.session_state.messages:
262
+ with st.chat_message(message["role"]):
263
+ st.markdown(message["content"])
264
+
265
+ if prompt := st.chat_input("What is up?"):
266
+ st.session_state.messages.append({"role": "user", "content": prompt})
267
+ with st.chat_message("user"):
268
+ st.markdown(prompt)
269
+
270
+ with st.chat_message("assistant"):
271
+ message_placeholder = st.empty()
272
+
273
+ full_response = ""
274
+ result = qa({"query": prompt})
275
+
276
+ sources = []
277
+ for src in result['source_documents']:
278
+ if src.page_content.startswith('Paragraph:'):
279
+ sources.append(src.metadata['source'])
280
+
281
+ if len(sources)==0:
282
+ full_response = full_response + "\n\n[No sources]"
283
+ else:
284
+ full_response = full_response + "\n\n[" + ", ".join(sources) + "]"
285
+
286
+ message_placeholder.markdown(full_response)
287
+ st.session_state.messages.append({"role": "assistant", "content": full_response})