Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,9 +1,9 @@
|
|
| 1 |
import os
|
| 2 |
os.system("pip install --upgrade pip")
|
| 3 |
-
|
| 4 |
import re
|
| 5 |
import time
|
| 6 |
import io
|
|
|
|
| 7 |
from io import StringIO
|
| 8 |
from typing import Any, Dict, List
|
| 9 |
#Modules to Import
|
|
@@ -14,7 +14,6 @@ from langchain.agents import AgentExecutor, Tool, ZeroShotAgent
|
|
| 14 |
from langchain.chains import RetrievalQA
|
| 15 |
from langchain.chains.question_answering import load_qa_chain
|
| 16 |
from langchain.docstore.document import Document
|
| 17 |
-
from langchain.document_loaders import PyPDFLoader
|
| 18 |
from langchain.embeddings.openai import OpenAIEmbeddings
|
| 19 |
from langchain.llms import OpenAI
|
| 20 |
from langchain.memory import ConversationBufferMemory
|
|
@@ -23,6 +22,32 @@ from langchain.vectorstores import VectorStore
|
|
| 23 |
from langchain.vectorstores.faiss import FAISS
|
| 24 |
from pypdf import PdfReader
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
@st.cache_data
|
| 27 |
def parse_pdf (file: io.BytesIO)-> List[str]:
|
| 28 |
pdf = PdfReader(file)
|
|
@@ -70,108 +95,236 @@ def text_to_docs(text: str) -> List [Document]:
|
|
| 70 |
doc.metadata["source"] = f"{doc.metadata['page']}-{doc.metadata['chunk']}"
|
| 71 |
doc_chunks.append(doc)
|
| 72 |
return doc_chunks
|
|
|
|
| 73 |
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
|
|
|
| 78 |
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
st.
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
)
|
|
|
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
)
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
input_variables=["input", "chat_history", "agent_scratchpad"],
|
| 128 |
-
)
|
| 129 |
|
| 130 |
-
|
| 131 |
-
st.session_state.memory = ConversationBufferMemory(memory_key ="chat_history")
|
| 132 |
|
| 133 |
-
#Chain
|
| 134 |
-
# ZeroShotAgent
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
|
|
|
| 149 |
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
# st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
os.system("pip install --upgrade pip")
|
|
|
|
| 3 |
import re
|
| 4 |
import time
|
| 5 |
import io
|
| 6 |
+
|
| 7 |
from io import StringIO
|
| 8 |
from typing import Any, Dict, List
|
| 9 |
#Modules to Import
|
|
|
|
| 14 |
from langchain.chains import RetrievalQA
|
| 15 |
from langchain.chains.question_answering import load_qa_chain
|
| 16 |
from langchain.docstore.document import Document
|
|
|
|
| 17 |
from langchain.embeddings.openai import OpenAIEmbeddings
|
| 18 |
from langchain.llms import OpenAI
|
| 19 |
from langchain.memory import ConversationBufferMemory
|
|
|
|
| 22 |
from langchain.vectorstores.faiss import FAISS
|
| 23 |
from pypdf import PdfReader
|
| 24 |
|
| 25 |
+
import os
|
| 26 |
+
|
| 27 |
+
from langchain.chat_models import ChatOpenAI
|
| 28 |
+
from langchain.prompts import ChatPromptTemplate
|
| 29 |
+
|
| 30 |
+
from langchain.chains import ConversationChain
|
| 31 |
+
from langchain.memory import ConversationBufferWindowMemory
|
| 32 |
+
from langchain.memory import ConversationSummaryBufferMemory
|
| 33 |
+
|
| 34 |
+
from langchain import OpenAI, LLMChain, PromptTemplate
|
| 35 |
+
from langchain.vectorstores import Chroma
|
| 36 |
+
from langchain.document_loaders import TextLoader, PyPDFLoader
|
| 37 |
+
from langchain.chains import ConversationalRetrievalChain
|
| 38 |
+
from langchain.chains.summarize import load_summarize_chain
|
| 39 |
+
import tempfile
|
| 40 |
+
|
| 41 |
+
import warnings
|
| 42 |
+
warnings.filterwarnings('ignore')
|
| 43 |
+
|
| 44 |
+
from dotenv import load_dotenv, find_dotenv
|
| 45 |
+
_ = load_dotenv(find_dotenv())
|
| 46 |
+
# openai.api_key = "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"
|
| 47 |
+
global openai_api_key
|
| 48 |
+
openai_api_key = "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"
|
| 49 |
+
os.environ['OPENAI_API_KEY'] = "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"
|
| 50 |
+
|
| 51 |
@st.cache_data
|
| 52 |
def parse_pdf (file: io.BytesIO)-> List[str]:
|
| 53 |
pdf = PdfReader(file)
|
|
|
|
| 95 |
doc.metadata["source"] = f"{doc.metadata['page']}-{doc.metadata['chunk']}"
|
| 96 |
doc_chunks.append(doc)
|
| 97 |
return doc_chunks
|
| 98 |
+
def tool(index):
|
| 99 |
|
| 100 |
+
qa = RetrievalQA.from_chain_type(
|
| 101 |
+
llm = OpenAI(openai_api_key = api),
|
| 102 |
+
chain_type = "stuff",
|
| 103 |
+
retriever = index.as_retriever()
|
| 104 |
+
)
|
| 105 |
+
# our tool
|
| 106 |
+
tools = [
|
| 107 |
+
Tool(
|
| 108 |
+
name="State of Union QA System",
|
| 109 |
+
func=qa.run,
|
| 110 |
+
description="Useful for when you need to answer questions about the aspects asked.\
|
| 111 |
+
Input may be a partial or fully formed question."
|
| 112 |
+
)
|
| 113 |
+
]
|
| 114 |
+
return tools,qa
|
| 115 |
+
def process(kind, tools, qa):
|
| 116 |
+
if kind == "Sumarized":
|
| 117 |
+
prefix=""""Have a conversation with a human, answering the human questions as best you can based on the context and memory available. \
|
| 118 |
+
You have access to a single tool:"""
|
| 119 |
+
suffix="""Begin!"
|
| 120 |
+
{chat_history}
|
| 121 |
+
Question: {input}
|
| 122 |
+
{agent_scratchpad}"""
|
| 123 |
|
| 124 |
+
elif kind == "Chat":
|
| 125 |
+
prefix=""""Have a conversation with a human, answering the human questions as best you can \
|
| 126 |
+
You have access to a single tool:"""
|
| 127 |
|
| 128 |
+
suffix="""Begin!"
|
| 129 |
+
{chat_history}
|
| 130 |
+
the human just say: {input}
|
| 131 |
+
{agent_scratchpad}"""
|
| 132 |
|
| 133 |
+
prompt = ZeroShotAgent.create_prompt(
|
| 134 |
+
tools,
|
| 135 |
+
prefix=prefix,
|
| 136 |
+
suffix=suffix,
|
| 137 |
+
input_variables=["input", "chat_history", "agent_scratchpad"],
|
| 138 |
+
)
|
| 139 |
+
if "memory" not in st.session_state:
|
| 140 |
+
st.session_state.memory = ConversationBufferMemory(memory_key ="chat_history")
|
| 141 |
+
#Chain
|
| 142 |
+
# ZeroShotAgent
|
| 143 |
+
llm_chain = LLMChain(
|
| 144 |
+
llm=OpenAI(
|
| 145 |
+
temperature=0, openai_api_key=api, model_name="gpt-3.5-turbo"
|
| 146 |
+
),
|
| 147 |
+
prompt=prompt,
|
| 148 |
+
)
|
| 149 |
+
agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True)
|
| 150 |
+
agent_chain = AgentExecutor.from_agent_and_tools(
|
| 151 |
+
agent=agent, tools=tools, verbose=True, memory=st.session_state.memory
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
option = st.sidebar.selectbox(
|
| 156 |
+
'What do you want to ?',
|
| 157 |
+
('Chat', 'Sumarization'))
|
| 158 |
+
|
| 159 |
+
api = st.sidebar.text_input(
|
| 160 |
+
"Open api key",
|
| 161 |
+
type="password",
|
| 162 |
+
placeholder="sk-",
|
| 163 |
+
help="https://platform.openai.com/account/api-keys",
|
| 164 |
)
|
| 165 |
+
uploaded_file = st.sidebar.file_uploader(":blue[Upload]", type=["pdf"])
|
| 166 |
|
| 167 |
+
if api:
|
| 168 |
+
if option == "Sumarization":
|
| 169 |
+
|
| 170 |
+
if uploaded_file:
|
| 171 |
+
|
| 172 |
+
doc = parse_pdf(uploaded_file)
|
| 173 |
+
|
| 174 |
+
pages = text_to_docs(doc)
|
| 175 |
+
# pages
|
| 176 |
+
if pages:
|
| 177 |
+
with st.expander('Show page contents', expanded=False):
|
| 178 |
+
page_sel =st.number_input(
|
| 179 |
+
label="selected page", min_value=1, max_value=len(pages), step=1
|
| 180 |
)
|
| 181 |
+
st.write(pages[page_sel-1])
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
embeddings = OpenAIEmbeddings(openai_api_key = api)
|
| 185 |
+
# Indexing
|
| 186 |
+
# Save in a Vector DB_
|
| 187 |
+
with st.spinner("It's indexing. .."):
|
| 188 |
+
index = FAISS.from_documents(pages, embeddings)
|
| 189 |
+
|
| 190 |
+
tools,qa = tool(index)
|
| 191 |
+
|
|
|
|
|
|
|
| 192 |
|
| 193 |
+
process("Sumarized",tools)
|
|
|
|
| 194 |
|
|
|
|
|
|
|
| 195 |
|
| 196 |
+
container = st.container()
|
| 197 |
+
with container:
|
| 198 |
+
st.title("🤖 AI ChatBot")
|
| 199 |
+
|
| 200 |
+
# Initialize chat history
|
| 201 |
+
if "messages" not in st.session_state:
|
| 202 |
+
st.session_state.messages = []
|
| 203 |
+
# Display chat messages from history on app rerun
|
| 204 |
+
for message in st.session_state.messages:
|
| 205 |
+
with st.chat_message(message["role"]):
|
| 206 |
+
st.markdown(message["content"])
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
if query := st.chat_input("Hey yo !!! Wazzups!"):
|
| 210 |
|
| 211 |
+
st.chat_message("user").markdown(query)
|
| 212 |
+
# Add user message to chat history
|
| 213 |
+
st.session_state.messages.append({"role": "user", "content": query})
|
| 214 |
+
|
| 215 |
+
# response=llm_chain.memory.chat_memory.add_user_message(prompt)
|
| 216 |
+
if len(api) == 0:
|
| 217 |
+
response = f"""I will answer the question "{query}" if you give the API key"""
|
| 218 |
+
# st.write(response)
|
| 219 |
+
# #f"Echo: {prompt}" get_completion(template_string) #
|
| 220 |
+
# Display assistant response in chat message container
|
| 221 |
+
with st.chat_message("assistant"):
|
| 222 |
+
st.markdown(response)
|
| 223 |
+
# Add assistant response to chat history
|
| 224 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 225 |
+
|
| 226 |
+
else:
|
| 227 |
+
|
| 228 |
+
with st.spinner("It's indexing. .."):
|
| 229 |
+
response = agent_chain.run(query)
|
| 230 |
+
# st.write(response)
|
| 231 |
+
# #f"Echo: {prompt}" get_completion(template_string) #
|
| 232 |
+
# Display assistant response in chat message container
|
| 233 |
+
with st.chat_message("assistant"):
|
| 234 |
+
st.markdown(response)
|
| 235 |
+
# Add assistant response to chat history
|
| 236 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 237 |
+
# with st.expander("History/Memory"):
|
| 238 |
+
# st.write(st.session_state.memory)
|
| 239 |
+
|
| 240 |
+
elif option == "Chat":
|
| 241 |
+
|
| 242 |
+
def get_completion(prompt, model="gpt-3.5-turbo"):
|
| 243 |
+
messages = [{"role": "user", "content": prompt}]
|
| 244 |
+
response = openai.ChatCompletion.create(
|
| 245 |
+
model=model,
|
| 246 |
+
messages=messages,
|
| 247 |
+
temperature=0,
|
| 248 |
+
)
|
| 249 |
+
return response.choices[0].message["content"]
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
chat = ChatOpenAI(temperature=0.0, max_tokens=20)
|
| 253 |
+
memory = ConversationBufferWindowMemory(k=15)
|
| 254 |
+
conversation = ConversationChain(
|
| 255 |
+
llm=chat,
|
| 256 |
+
memory = memory,
|
| 257 |
+
verbose=False,
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def reply(message, custom_style):
|
| 262 |
+
style = """ in a funny \
|
| 263 |
+
and joke tone
|
| 264 |
+
"""
|
| 265 |
+
if len(custom_style) > 0: style = custom_style
|
| 266 |
+
|
| 267 |
+
template_string = f"""You are talking with a person \
|
| 268 |
+
replying to the message\
|
| 269 |
+
with a style that is {style}. \
|
| 270 |
+
the person just say: {message}.
|
| 271 |
+
"""
|
| 272 |
+
|
| 273 |
+
prompt_template = ChatPromptTemplate.from_template(template_string)
|
| 274 |
+
|
| 275 |
+
bot_messages = prompt_template.format_messages(
|
| 276 |
+
style= style,
|
| 277 |
+
text= message)
|
| 278 |
+
|
| 279 |
+
response = conversation.predict(input=message)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
return response
|
| 283 |
+
|
| 284 |
+
def sumarization():
|
| 285 |
+
pass
|
| 286 |
+
|
| 287 |
+
def document_question(question):
|
| 288 |
+
pass
|
| 289 |
+
ask_about_doc = False
|
| 290 |
+
with st.sidebar:
|
| 291 |
+
st.subheader("How do you want your bot reply to your message ?")
|
| 292 |
+
custom_style = st.text_input("Tell me here", placeholder="joke tone")
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
container = st.container()
|
| 296 |
+
with container:
|
| 297 |
+
st.title("🤖 AI ChatBot")
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
# Initialize chat history
|
| 301 |
+
if "messages" not in st.session_state:
|
| 302 |
+
st.session_state.messages = []
|
| 303 |
|
| 304 |
+
# Display chat messages from history on app rerun
|
| 305 |
+
for message in st.session_state.messages:
|
| 306 |
+
with st.chat_message(message["role"]):
|
| 307 |
+
st.markdown(message["content"])
|
| 308 |
+
# React to user input
|
| 309 |
+
if prompt := st.chat_input("What is up?"):
|
| 310 |
+
# Display user message in chat message container
|
| 311 |
+
st.chat_message("user").markdown(prompt)
|
| 312 |
+
# Add user message to chat history
|
| 313 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 314 |
+
|
| 315 |
+
with st.spinner("It's indexing. .."):
|
| 316 |
+
response = reply(prompt,custom_style)
|
| 317 |
+
# with st.spinner("It's indexing. .."):
|
| 318 |
+
# tools,qa = tool()
|
| 319 |
+
# process("chat", tools, qa)
|
| 320 |
+
# response = agent_chain.run(query)
|
| 321 |
+
if memory not in st.session_state:
|
| 322 |
+
st.session_state.memory = ConversationBufferWindowMemory(k=15)
|
| 323 |
+
# response=llm_chain.memory.chat_memory.add_user_message(prompt)
|
| 324 |
+
# st.write(memory.buffer)
|
| 325 |
+
# #f"Echo: {prompt}" get_completion(template_string) #
|
| 326 |
+
# Display assistant response in chat message container
|
| 327 |
+
with st.chat_message("assistant"):
|
| 328 |
+
st.markdown(response)
|
| 329 |
+
# Add assistant response to chat history
|
| 330 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|