Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,29 +1,85 @@
|
|
|
|
1 |
import os
|
2 |
-
|
3 |
import streamlit as st
|
4 |
from dotenv import load_dotenv
|
|
|
5 |
from langchain.callbacks.base import BaseCallbackHandler
|
6 |
from langchain.chains import ConversationalRetrievalChain
|
7 |
from langchain.chat_models import ChatOpenAI
|
|
|
|
|
8 |
from langchain.embeddings import OpenAIEmbeddings
|
|
|
9 |
from langchain.memory import ConversationBufferMemory
|
10 |
from langchain.memory.chat_message_histories import StreamlitChatMessageHistory
|
|
|
11 |
from langchain.vectorstores import Chroma
|
12 |
|
|
|
13 |
load_dotenv()
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
@st.cache_resource(ttl='1h')
|
21 |
def get_retriever():
|
22 |
embeddings = OpenAIEmbeddings()
|
23 |
vectordb = Chroma(persist_directory='db', embedding_function=embeddings)
|
24 |
-
|
25 |
retriever = vectordb.as_retriever(search_type='mmr')
|
26 |
-
|
27 |
return retriever
|
28 |
|
29 |
class StreamHandler(BaseCallbackHandler):
|
@@ -35,27 +91,9 @@ class StreamHandler(BaseCallbackHandler):
|
|
35 |
self.text += token
|
36 |
self.container.markdown(self.text)
|
37 |
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
memory = ConversationBufferMemory(memory_key='chat_history', chat_memory=msgs, return_messages=True)
|
42 |
-
|
43 |
-
llm = ChatOpenAI(model_name='gpt-3.5-turbo', temperature=0, streaming=True)
|
44 |
-
qa_chain = ConversationalRetrievalChain.from_llm(
|
45 |
-
llm, retriever=retriever, memory=memory, verbose=False
|
46 |
-
)
|
47 |
-
|
48 |
-
if st.sidebar.button('Clear message history') or len(msgs.messages) == 0:
|
49 |
-
msgs.clear()
|
50 |
-
msgs.add_ai_message(f'Ask me anything about {website_url}!')
|
51 |
-
|
52 |
-
avatars = {'human': 'user', 'ai': 'assistant'}
|
53 |
-
for msg in msgs.messages:
|
54 |
-
st.chat_message(avatars[msg.type]).write(msg.content)
|
55 |
-
|
56 |
-
if user_query := st.chat_input(placeholder='Ask me anything!'):
|
57 |
-
st.chat_message('user').write(user_query)
|
58 |
|
59 |
-
|
60 |
-
|
61 |
-
response = qa_chain.run(user_query, callbacks=[stream_handler])
|
|
|
1 |
+
# Combined Imports
|
2 |
import os
|
|
|
3 |
import streamlit as st
|
4 |
from dotenv import load_dotenv
|
5 |
+
from apify_client import ApifyClient
|
6 |
from langchain.callbacks.base import BaseCallbackHandler
|
7 |
from langchain.chains import ConversationalRetrievalChain
|
8 |
from langchain.chat_models import ChatOpenAI
|
9 |
+
from langchain.document_loaders import ApifyDatasetLoader
|
10 |
+
from langchain.document_loaders.base import Document
|
11 |
from langchain.embeddings import OpenAIEmbeddings
|
12 |
+
from langchain.embeddings.openai import OpenAIEmbeddings
|
13 |
from langchain.memory import ConversationBufferMemory
|
14 |
from langchain.memory.chat_message_histories import StreamlitChatMessageHistory
|
15 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
16 |
from langchain.vectorstores import Chroma
|
17 |
|
18 |
+
# Environment variables and configuration
|
19 |
load_dotenv()
|
20 |
+
WEBSITE_URL = os.environ.get('WEBSITE_URL', 'a website')
|
21 |
+
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY')
|
22 |
+
APIFY_API_TOKEN = os.environ.get('APIFY_API_TOKEN')
|
23 |
+
|
24 |
+
# Scraper Functionality
|
25 |
+
def scrape_website():
|
26 |
+
apify_client = ApifyClient(APIFY_API_TOKEN)
|
27 |
+
st.write(f'Extracting data from "{WEBSITE_URL}". Please wait...')
|
28 |
+
actor_run_info = apify_client.actor('apify/website-content-crawler').call(
|
29 |
+
run_input={'startUrls': [{'url': WEBSITE_URL}]}
|
30 |
+
)
|
31 |
+
st.write('Saving data into the vector database. Please wait...')
|
32 |
+
loader = ApifyDatasetLoader(
|
33 |
+
dataset_id=actor_run_info['defaultDatasetId'],
|
34 |
+
dataset_mapping_function=lambda item: Document(
|
35 |
+
page_content=item['text'] or '', metadata={'source': item['url']}
|
36 |
+
),
|
37 |
+
)
|
38 |
+
documents = loader.load()
|
39 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=100)
|
40 |
+
docs = text_splitter.split_documents(documents)
|
41 |
+
|
42 |
+
embedding = OpenAIEmbeddings(api_key=OPENAI_API_KEY)
|
43 |
+
vectordb = Chroma.from_documents(
|
44 |
+
documents=docs,
|
45 |
+
embedding=embedding,
|
46 |
+
persist_directory='db2',
|
47 |
+
)
|
48 |
+
vectordb.persist()
|
49 |
+
st.write('All done!')
|
50 |
+
|
51 |
+
# Chat Functionality
|
52 |
+
def chat_with_website():
|
53 |
+
st.set_page_config(page_title=f'Chat with {WEBSITE_URL}')
|
54 |
+
st.title('Chat with a website')
|
55 |
+
retriever = get_retriever()
|
56 |
+
msgs = StreamlitChatMessageHistory()
|
57 |
+
memory = ConversationBufferMemory(memory_key='chat_history', chat_memory=msgs, return_messages=True)
|
58 |
+
|
59 |
+
llm = ChatOpenAI(model_name='gpt-3.5-turbo', temperature=0, streaming=True)
|
60 |
+
qa_chain = ConversationalRetrievalChain.from_llm(
|
61 |
+
llm, retriever=retriever, memory=memory, verbose=False
|
62 |
+
)
|
63 |
+
|
64 |
+
if st.sidebar.button('Clear message history') or len(msgs.messages) == 0:
|
65 |
+
msgs.clear()
|
66 |
+
msgs.add_ai_message(f'Ask me anything about {WEBSITE_URL}!')
|
67 |
+
|
68 |
+
avatars = {'human': 'user', 'ai': 'assistant'}
|
69 |
+
for msg in msgs.messages:
|
70 |
+
st.chat_message(avatars[msg.type]).write(msg.content)
|
71 |
+
|
72 |
+
if user_query := st.chat_input(placeholder='Ask me anything!'):
|
73 |
+
st.chat_message('user').write(user_query)
|
74 |
+
with st.chat_message('assistant'):
|
75 |
+
stream_handler = StreamHandler(st.empty())
|
76 |
+
response = qa_chain.run(user_query, callbacks=[stream_handler])
|
77 |
|
78 |
@st.cache_resource(ttl='1h')
|
79 |
def get_retriever():
|
80 |
embeddings = OpenAIEmbeddings()
|
81 |
vectordb = Chroma(persist_directory='db', embedding_function=embeddings)
|
|
|
82 |
retriever = vectordb.as_retriever(search_type='mmr')
|
|
|
83 |
return retriever
|
84 |
|
85 |
class StreamHandler(BaseCallbackHandler):
|
|
|
91 |
self.text += token
|
92 |
self.container.markdown(self.text)
|
93 |
|
94 |
+
# Main App Flow
|
95 |
+
if st.sidebar.button("Scrape a new website"):
|
96 |
+
scrape_website()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
|
98 |
+
if st.sidebar.button("Chat with scraped website"):
|
99 |
+
chat_with_website()
|
|