antfraia commited on
Commit
c2ca5df
1 Parent(s): 2900706

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -55
app.py CHANGED
@@ -1,34 +1,39 @@
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(
@@ -38,49 +43,16 @@ def scrape_website():
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):
86
  def __init__(self, container: st.delta_generator.DeltaGenerator, initial_text: str = ''):
@@ -91,9 +63,25 @@ 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()
 
 
 
1
  import os
2
  import streamlit as st
 
3
  from apify_client import ApifyClient
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
+ from langchain.document_loaders import ApifyDatasetLoader
13
+ from langchain.document_loaders.base import Document
14
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
15
 
 
16
  load_dotenv()
17
+
18
+ st.set_page_config(page_title='Chat with a website')
19
+
20
+ website_url = st.text_input("Please enter the website URL to scrape:", value="https://www.example.com/")
21
+ st.title(f'Chat with {website_url}')
22
+
23
  APIFY_API_TOKEN = os.environ.get('APIFY_API_TOKEN')
24
 
25
+ @st.cache_resource(ttl='1h')
26
+ def get_retriever():
27
+ embeddings = OpenAIEmbeddings()
28
+ vectordb = Chroma(persist_directory='db', embedding_function=embeddings)
29
+ retriever = vectordb.as_retriever(search_type='mmr')
30
+ return retriever
31
+
32
+ def scrape_website(website_url: str):
33
  apify_client = ApifyClient(APIFY_API_TOKEN)
 
34
  actor_run_info = apify_client.actor('apify/website-content-crawler').call(
35
+ run_input={'startUrls': [{'url': website_url}]}
36
  )
 
37
  loader = ApifyDatasetLoader(
38
  dataset_id=actor_run_info['defaultDatasetId'],
39
  dataset_mapping_function=lambda item: Document(
 
43
  documents = loader.load()
44
  text_splitter = RecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=100)
45
  docs = text_splitter.split_documents(documents)
46
+ embedding = OpenAIEmbeddings()
 
47
  vectordb = Chroma.from_documents(
48
  documents=docs,
49
  embedding=embedding,
50
  persist_directory='db2',
51
  )
52
  vectordb.persist()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
+ if st.button("Start Scraping"):
55
+ scrape_website(website_url)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
  class StreamHandler(BaseCallbackHandler):
58
  def __init__(self, container: st.delta_generator.DeltaGenerator, initial_text: str = ''):
 
63
  self.text += token
64
  self.container.markdown(self.text)
65
 
66
+ retriever = get_retriever()
67
+ msgs = StreamlitChatMessageHistory()
68
+ memory = ConversationBufferMemory(memory_key='chat_history', chat_memory=msgs, return_messages=True)
69
+ llm = ChatOpenAI(model_name='gpt-3.5-turbo', temperature=0, streaming=True)
70
+ qa_chain = ConversationalRetrievalChain.from_llm(
71
+ llm, retriever=retriever, memory=memory, verbose=False
72
+ )
73
+
74
+ if st.sidebar.button('Clear message history') or len(msgs.messages) == 0:
75
+ msgs.clear()
76
+ msgs.add_ai_message(f'Ask me anything about {website_url}!')
77
+
78
+ avatars = {'human': 'user', 'ai': 'assistant'}
79
+ for msg in msgs.messages:
80
+ st.chat_message(avatars[msg.type]).write(msg.content)
81
+
82
+ if user_query := st.chat_input(placeholder='Ask me anything!'):
83
+ st.chat_message('user').write(user_query)
84
 
85
+ with st.chat_message('assistant'):
86
+ stream_handler = StreamHandler(st.empty())
87
+ response = qa_chain.run(user_query, callbacks=[stream_handler])