Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,173 +1,176 @@
|
|
1 |
-
import
|
2 |
-
|
3 |
-
import
|
4 |
-
|
5 |
-
from langchain.chains
|
6 |
-
from
|
7 |
-
from
|
8 |
-
from langchain_core.
|
9 |
-
from
|
10 |
-
from
|
11 |
-
from
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
#
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
st.
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
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 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
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 |
-
|
|
|
|
|
|
|
|
1 |
+
import subprocess
|
2 |
+
import streamlit as st
|
3 |
+
from decouple import config
|
4 |
+
import asyncio
|
5 |
+
from langchain.chains import create_retrieval_chain
|
6 |
+
from langchain.chains.combine_documents import create_stuff_documents_chain
|
7 |
+
from langchain_groq import ChatGroq
|
8 |
+
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
|
9 |
+
from langchain_core.messages import SystemMessage
|
10 |
+
from scraper.scraper import process_urls
|
11 |
+
from embedding.vector_store import initialize_vector_store, clear_chroma_db
|
12 |
+
from conversation.talks import clean_input, small_talks
|
13 |
+
|
14 |
+
subprocess.run(["playwright", "install"], check=True)
|
15 |
+
|
16 |
+
#Clearing ChromaDB at startup to clean up any previous data
|
17 |
+
clear_chroma_db()
|
18 |
+
|
19 |
+
|
20 |
+
|
21 |
+
|
22 |
+
#Groq API Key
|
23 |
+
groq_api = config("GROQ_API_KEY")
|
24 |
+
|
25 |
+
#Initializing LLM with memory
|
26 |
+
llm = ChatGroq(model="llama-3.2-1b-preview", groq_api_key=groq_api, temperature=0)
|
27 |
+
|
28 |
+
|
29 |
+
|
30 |
+
#Ensure proper asyncio handling for Windows
|
31 |
+
import sys
|
32 |
+
if sys.platform.startswith("win"):
|
33 |
+
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
|
34 |
+
|
35 |
+
#Async helper function
|
36 |
+
def run_asyncio_coroutine(coro):
|
37 |
+
loop = asyncio.new_event_loop()
|
38 |
+
asyncio.set_event_loop(loop)
|
39 |
+
return loop.run_until_complete(coro)
|
40 |
+
|
41 |
+
import streamlit as st
|
42 |
+
|
43 |
+
st.title("WebGPT 1.0 π€")
|
44 |
+
|
45 |
+
# URL inputs
|
46 |
+
urls = st.text_area("Enter URLs (one per line)")
|
47 |
+
run_scraper = st.button("Run Scraper", disabled=not urls.strip())
|
48 |
+
|
49 |
+
# Sessions & states
|
50 |
+
if "messages" not in st.session_state:
|
51 |
+
st.session_state.messages = [] # Chat history
|
52 |
+
if "history" not in st.session_state:
|
53 |
+
st.session_state.history = "" # Stores past Q&A for memory
|
54 |
+
if "scraping_done" not in st.session_state:
|
55 |
+
st.session_state.scraping_done = False
|
56 |
+
if "vector_store" not in st.session_state:
|
57 |
+
st.session_state.vector_store = None
|
58 |
+
|
59 |
+
# Run scraper
|
60 |
+
if run_scraper:
|
61 |
+
st.write("Fetching and processing URLs... This may take a while.")
|
62 |
+
split_docs = run_asyncio_coroutine(process_urls(urls.split("\n")))
|
63 |
+
st.session_state.vector_store = initialize_vector_store(split_docs)
|
64 |
+
st.session_state.scraping_done = True
|
65 |
+
st.success("Scraping and processing completed!")
|
66 |
+
|
67 |
+
# β
Clear chat button
|
68 |
+
if st.button("Clear Chat"):
|
69 |
+
st.session_state.messages = [] # Reset message history
|
70 |
+
st.session_state.history = "" # Reset history tracking
|
71 |
+
st.success("Chat cleared!")
|
72 |
+
|
73 |
+
# Ensuring chat only enables after scraping
|
74 |
+
if not st.session_state.scraping_done:
|
75 |
+
st.warning("Scrape some data first to enable chat!")
|
76 |
+
else:
|
77 |
+
st.write("### Chat With WebGPT π¬")
|
78 |
+
|
79 |
+
# Display chat history
|
80 |
+
for message in st.session_state.messages:
|
81 |
+
role, text = message["role"], message["text"]
|
82 |
+
with st.chat_message(role):
|
83 |
+
st.write(text)
|
84 |
+
|
85 |
+
# Takes in user input
|
86 |
+
user_query = st.chat_input("Ask a question...")
|
87 |
+
|
88 |
+
if user_query:
|
89 |
+
st.session_state.messages.append({"role": "user", "text": user_query})
|
90 |
+
with st.chat_message("user"):
|
91 |
+
st.write(user_query)
|
92 |
+
|
93 |
+
user_query_cleaned = clean_input(user_query)
|
94 |
+
response = "" # Default value for response
|
95 |
+
source_url = "" # Default value for source url
|
96 |
+
|
97 |
+
# Check for small talk responses
|
98 |
+
if user_query_cleaned in small_talks:
|
99 |
+
response = small_talks[user_query_cleaned]
|
100 |
+
source_url = "Knowledge base" # Small talk comes from the knowledge base
|
101 |
+
|
102 |
+
else:
|
103 |
+
# β
Setup retriever (with a similarity threshold or top-k retrieval)
|
104 |
+
retriever = st.session_state.vector_store.as_retriever(
|
105 |
+
search_kwargs={'k': 5}
|
106 |
+
)
|
107 |
+
|
108 |
+
# β
Retrieve context
|
109 |
+
retrieved_docs = retriever.invoke(user_query_cleaned)
|
110 |
+
retrieved_text = " ".join([doc.page_content for doc in retrieved_docs])
|
111 |
+
|
112 |
+
# β
Define Langchain PromptTemplate properly
|
113 |
+
system_prompt_template = PromptTemplate(
|
114 |
+
input_variables=["context", "query"],
|
115 |
+
template="""
|
116 |
+
You are WebGPT, an AI assistant for question-answering tasks that **only answers questions based on the provided context**.
|
117 |
+
|
118 |
+
- Understand the context {context} first and provide a relevant answer.
|
119 |
+
- If the answer is **not** found in the Context, reply with: "I can't find your request in the provided context."
|
120 |
+
- If the question is **unrelated** to the Context, reply with: "I can't answer that. do not generate responses."
|
121 |
+
- **Do not** use external knowledge, assumptions, or filler responses. Stick to the context provided.
|
122 |
+
- Keep responses clear, concise, and relevant to the userβs query.
|
123 |
+
|
124 |
+
Context:
|
125 |
+
{context}
|
126 |
+
|
127 |
+
Now, answer the user's question:
|
128 |
+
{input}
|
129 |
+
"""
|
130 |
+
)
|
131 |
+
|
132 |
+
# β
Generate prompt with retrieved context & user query
|
133 |
+
final_prompt = system_prompt_template.format(
|
134 |
+
context=retrieved_text,
|
135 |
+
input=user_query_cleaned
|
136 |
+
)
|
137 |
+
|
138 |
+
# β
Create chains (ensure the prompt is correct)
|
139 |
+
scraper_chain = create_stuff_documents_chain(llm=llm, prompt=system_prompt_template)
|
140 |
+
llm_chain = create_retrieval_chain(retriever, scraper_chain)
|
141 |
+
|
142 |
+
# β
Process response and source
|
143 |
+
if retrieved_docs:
|
144 |
+
try:
|
145 |
+
response_data = llm_chain.invoke({"context": retrieved_text, "input": user_query_cleaned})
|
146 |
+
response = response_data.get("answer", "").strip()
|
147 |
+
source_url = retrieved_docs[0].metadata.get("source", "Unknown")
|
148 |
+
|
149 |
+
# Fallback if response is still empty
|
150 |
+
if not response:
|
151 |
+
response = "I can't find your request in the provided context."
|
152 |
+
source_url = "No source found"
|
153 |
+
|
154 |
+
except Exception as e:
|
155 |
+
response = f"Error generating response: {str(e)}"
|
156 |
+
source_url = "Error"
|
157 |
+
|
158 |
+
else:
|
159 |
+
response = "I can't find your request in the provided context."
|
160 |
+
source_url = "No source found"
|
161 |
+
|
162 |
+
# β
Track history & update session state
|
163 |
+
history_text = "\n".join(
|
164 |
+
[f"User: {msg['text']}" if msg["role"] == "user" else f"AI: {msg['text']}" for msg in st.session_state.messages]
|
165 |
+
)
|
166 |
+
st.session_state.history = history_text
|
167 |
+
|
168 |
+
# β
Format and display response
|
169 |
+
formatted_response = f"**Answer:** {response}"
|
170 |
+
if response != "I can't find your request in the provided context." and source_url:
|
171 |
+
formatted_response += f"\n\n**Source:** {source_url}"
|
172 |
+
|
173 |
+
st.session_state.messages.append({"role": "assistant", "text": formatted_response})
|
174 |
+
with st.chat_message("assistant"):
|
175 |
+
st.write(formatted_response)
|
176 |
+
|