Spaces:
Sleeping
Sleeping
Add password & streaming
Browse files
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 |
-
|
|
|
|
| 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 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
|
| 180 |
-
|
| 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
|
| 198 |
-
st.session_state
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
st.
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
st.
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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})
|