Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,9 +1,13 @@
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
from dotenv import load_dotenv
|
3 |
import asyncio
|
4 |
-
from
|
5 |
-
from
|
6 |
-
from
|
|
|
7 |
from langchain.chains import create_history_aware_retriever, create_retrieval_chain
|
8 |
from langchain.chains.combine_documents import create_stuff_documents_chain
|
9 |
from langchain_community.chat_message_histories import ChatMessageHistory
|
@@ -14,7 +18,13 @@ from pinecone import Pinecone
|
|
14 |
from pinecone_text.sparse import BM25Encoder
|
15 |
from langchain_huggingface import HuggingFaceEmbeddings
|
16 |
from langchain_community.retrievers import PineconeHybridSearchRetriever
|
17 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
# Load environment variables
|
20 |
load_dotenv(".env")
|
@@ -29,14 +39,19 @@ os.environ['USER_AGENT'] = USER_AGENT
|
|
29 |
os.environ["GROQ_API_KEY"] = GROQ_API_KEY
|
30 |
os.environ["TOKENIZERS_PARALLELISM"] = 'true'
|
31 |
|
32 |
-
# Initialize
|
33 |
-
app =
|
34 |
-
|
35 |
-
|
36 |
-
app.
|
37 |
-
|
38 |
-
|
39 |
-
|
|
|
|
|
|
|
|
|
|
|
40 |
|
41 |
# Function to initialize Pinecone connection
|
42 |
def initialize_pinecone(index_name: str):
|
@@ -51,32 +66,12 @@ def initialize_pinecone(index_name: str):
|
|
51 |
##################################################
|
52 |
## Change down here
|
53 |
##################################################
|
54 |
-
|
55 |
-
# Initialize Pinecone index and BM25 encoder
|
56 |
-
# pinecone_index = initialize_pinecone("uae-national-library-and-archives-vectorstore")
|
57 |
-
# bm25 = BM25Encoder().load("./UAE-NLA.json")
|
58 |
-
|
59 |
-
### This is for UAE Legislation Website
|
60 |
pinecone_index = initialize_pinecone("uae-legislation-site-data")
|
61 |
bm25 = BM25Encoder().load("./bm25_uae_legislation_data.json")
|
62 |
-
|
63 |
-
|
64 |
-
### This is for u.ae Website
|
65 |
-
# pinecone_index = initialize_pinecone("vector-store-index")
|
66 |
-
# bm25 = BM25Encoder().load("./bm25_u.ae.json")
|
67 |
-
|
68 |
-
|
69 |
-
# #### This is for UAE Economic Department Website
|
70 |
-
# pinecone_index = initialize_pinecone("uae-department-of-economics-site-data")
|
71 |
-
# bm25 = BM25Encoder().load("./bm25_uae_department_of_economics_data.json")
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
##################################################
|
76 |
##################################################
|
77 |
|
78 |
-
# old_embed_model = HuggingFaceEmbeddings(model_name="sentence-transformers/gte-multilingual-base")
|
79 |
-
|
80 |
# Initialize models and retriever
|
81 |
embed_model = HuggingFaceEmbeddings(model_name="Alibaba-NLP/gte-large-en-v1.5", model_kwargs={"trust_remote_code":True})
|
82 |
retriever = PineconeHybridSearchRetriever(
|
@@ -88,10 +83,29 @@ retriever = PineconeHybridSearchRetriever(
|
|
88 |
)
|
89 |
|
90 |
# Initialize LLM
|
91 |
-
llm =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
|
93 |
# Contextualization prompt and retriever
|
94 |
-
contextualize_q_system_prompt = """Given a chat history and the latest user question \
|
95 |
which might reference context in the chat history, formulate a standalone question \
|
96 |
which can be understood without the chat history. Do NOT answer the question, \
|
97 |
just reformulate it if needed and otherwise return it as is.
|
@@ -106,33 +120,26 @@ contextualize_q_prompt = ChatPromptTemplate.from_messages(
|
|
106 |
history_aware_retriever = create_history_aware_retriever(llm, retriever, contextualize_q_prompt)
|
107 |
|
108 |
# QA system prompt and chain
|
109 |
-
qa_system_prompt = """You are a highly skilled information retrieval assistant. Use the following context to answer questions effectively.
|
110 |
-
If you don't know the answer, simply state that you don't know.
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
- Use bullet points or numbered lists where applicable to present information clearly. \
|
130 |
-
- Highlight key details using bold or italics. \
|
131 |
-
- Provide proper and meaningful abbreviations for urls. Do not include naked urls. \
|
132 |
-
|
133 |
-
4. Organize Content Logically: \
|
134 |
-
- Structure the content in a logical order, ensuring easy navigation and understanding for the user. \
|
135 |
-
|
136 |
{context}
|
137 |
"""
|
138 |
qa_prompt = ChatPromptTemplate.from_messages(
|
@@ -142,7 +149,9 @@ qa_prompt = ChatPromptTemplate.from_messages(
|
|
142 |
("human", "{input}")
|
143 |
]
|
144 |
)
|
145 |
-
|
|
|
|
|
146 |
|
147 |
# Retrieval and Generative (RAG) Chain
|
148 |
rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)
|
@@ -150,9 +159,6 @@ rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chai
|
|
150 |
# Chat message history storage
|
151 |
store = {}
|
152 |
|
153 |
-
def clean_temporary_data():
|
154 |
-
store.clear()
|
155 |
-
|
156 |
def get_session_history(session_id: str) -> BaseChatMessageHistory:
|
157 |
if session_id not in store:
|
158 |
store[session_id] = ChatMessageHistory()
|
@@ -168,47 +174,66 @@ conversational_rag_chain = RunnableWithMessageHistory(
|
|
168 |
output_messages_key="answer",
|
169 |
)
|
170 |
|
171 |
-
# Function to handle WebSocket connection
|
172 |
-
@socketio.on('connect')
|
173 |
-
def handle_connect():
|
174 |
-
print(f"Client connected: {request.sid}")
|
175 |
-
emit('connection_response', {'message': 'Connected successfully.'})
|
176 |
-
|
177 |
-
# Function to handle WebSocket disconnection
|
178 |
-
@socketio.on('disconnect')
|
179 |
-
def handle_disconnect():
|
180 |
-
print(f"Client disconnected: {request.sid}")
|
181 |
-
clean_temporary_data()
|
182 |
-
|
183 |
-
# Function to handle WebSocket messages
|
184 |
-
@socketio.on('message')
|
185 |
-
def handle_message(data):
|
186 |
-
question = data.get('question')
|
187 |
-
language = data.get('language')
|
188 |
-
if "en" in language:
|
189 |
-
language = "English"
|
190 |
-
else:
|
191 |
-
language = "Arabic"
|
192 |
-
session_id = data.get('session_id', SESSION_ID_DEFAULT)
|
193 |
-
chain = conversational_rag_chain.pick("answer")
|
194 |
|
|
|
|
|
|
|
|
|
|
|
|
|
195 |
try:
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
)
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
206 |
|
207 |
# Home route
|
208 |
-
@app.
|
209 |
-
def
|
210 |
-
return
|
211 |
-
|
212 |
-
# Main function to run the app
|
213 |
-
if __name__ == '__main__':
|
214 |
-
socketio.run(app, debug=True)
|
|
|
1 |
+
import nltk
|
2 |
+
nltk.download('punkt_tab')
|
3 |
+
|
4 |
import os
|
5 |
from dotenv import load_dotenv
|
6 |
import asyncio
|
7 |
+
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
|
8 |
+
from fastapi.responses import HTMLResponse
|
9 |
+
from fastapi.templating import Jinja2Templates
|
10 |
+
from fastapi.middleware.cors import CORSMiddleware
|
11 |
from langchain.chains import create_history_aware_retriever, create_retrieval_chain
|
12 |
from langchain.chains.combine_documents import create_stuff_documents_chain
|
13 |
from langchain_community.chat_message_histories import ChatMessageHistory
|
|
|
18 |
from pinecone_text.sparse import BM25Encoder
|
19 |
from langchain_huggingface import HuggingFaceEmbeddings
|
20 |
from langchain_community.retrievers import PineconeHybridSearchRetriever
|
21 |
+
from langchain.retrievers import ContextualCompressionRetriever
|
22 |
+
from langchain_community.chat_models import ChatPerplexity
|
23 |
+
from langchain.retrievers.document_compressors import CrossEncoderReranker
|
24 |
+
from langchain_community.cross_encoders import HuggingFaceCrossEncoder
|
25 |
+
from langchain_core.prompts import PromptTemplate
|
26 |
+
from langchain.retrievers.document_compressors import FlashrankRerank
|
27 |
+
import re
|
28 |
|
29 |
# Load environment variables
|
30 |
load_dotenv(".env")
|
|
|
39 |
os.environ["GROQ_API_KEY"] = GROQ_API_KEY
|
40 |
os.environ["TOKENIZERS_PARALLELISM"] = 'true'
|
41 |
|
42 |
+
# Initialize FastAPI app and CORS
|
43 |
+
app = FastAPI()
|
44 |
+
origins = ["*"] # Adjust as needed
|
45 |
+
|
46 |
+
app.add_middleware(
|
47 |
+
CORSMiddleware,
|
48 |
+
allow_origins=origins,
|
49 |
+
allow_credentials=True,
|
50 |
+
allow_methods=["*"],
|
51 |
+
allow_headers=["*"],
|
52 |
+
)
|
53 |
+
|
54 |
+
templates = Jinja2Templates(directory="templates")
|
55 |
|
56 |
# Function to initialize Pinecone connection
|
57 |
def initialize_pinecone(index_name: str):
|
|
|
66 |
##################################################
|
67 |
## Change down here
|
68 |
##################################################
|
69 |
+
# #### This is for UAE Economic Department Website
|
|
|
|
|
|
|
|
|
|
|
70 |
pinecone_index = initialize_pinecone("uae-legislation-site-data")
|
71 |
bm25 = BM25Encoder().load("./bm25_uae_legislation_data.json")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
##################################################
|
73 |
##################################################
|
74 |
|
|
|
|
|
75 |
# Initialize models and retriever
|
76 |
embed_model = HuggingFaceEmbeddings(model_name="Alibaba-NLP/gte-large-en-v1.5", model_kwargs={"trust_remote_code":True})
|
77 |
retriever = PineconeHybridSearchRetriever(
|
|
|
83 |
)
|
84 |
|
85 |
# Initialize LLM
|
86 |
+
llm = ChatPerplexity(temperature=0, pplx_api_key=GROQ_API_KEY, model="llama-3.1-sonar-large-128k-chat", max_tokens=512, max_retries=2)
|
87 |
+
|
88 |
+
# Initialize Reranker
|
89 |
+
# model = HuggingFaceCrossEncoder(model_name="BAAI/bge-reranker-base")
|
90 |
+
# compressor = CrossEncoderReranker(model=model, top_n=10)
|
91 |
+
|
92 |
+
# compression_retriever = ContextualCompressionRetriever(
|
93 |
+
# base_compressor=compressor, base_retriever=retriever
|
94 |
+
# )
|
95 |
+
# from langchain.retrievers.document_compressors import LLMChainExtractor
|
96 |
+
|
97 |
+
# compressor = LLMChainExtractor.from_llm(llm)
|
98 |
+
# compression_retriever = ContextualCompressionRetriever(
|
99 |
+
# base_compressor=compressor, base_retriever=retriever
|
100 |
+
# )
|
101 |
+
|
102 |
+
# compressor = FlashrankRerank(top_n=10)
|
103 |
+
# compression_retriever = ContextualCompressionRetriever(
|
104 |
+
# base_compressor=compressor, base_retriever=retriever
|
105 |
+
# )
|
106 |
|
107 |
# Contextualization prompt and retriever
|
108 |
+
contextualize_q_system_prompt = """ Given a chat history and the latest user question \
|
109 |
which might reference context in the chat history, formulate a standalone question \
|
110 |
which can be understood without the chat history. Do NOT answer the question, \
|
111 |
just reformulate it if needed and otherwise return it as is.
|
|
|
120 |
history_aware_retriever = create_history_aware_retriever(llm, retriever, contextualize_q_prompt)
|
121 |
|
122 |
# QA system prompt and chain
|
123 |
+
qa_system_prompt = """ You are a highly skilled information retrieval assistant. Use the following context to answer questions effectively.
|
124 |
+
If you don't know the answer, simply state that you don't know.
|
125 |
+
YOUR ANSWER SHOULD BE IN '{language}' LANGUAGE.
|
126 |
+
When responding to queries, follow these guidelines:
|
127 |
+
1. Provide Clear Answers:
|
128 |
+
- You have to answer in that language based on the given language of the answer. If it is English, answer it in English; if it is Arabic, you should answer it in Arabic.
|
129 |
+
- Ensure the response directly addresses the query with accurate and relevant information.
|
130 |
+
- Do not give long answers. Provide detailed but concise responses.
|
131 |
+
|
132 |
+
2. Formatting for Readability:
|
133 |
+
- Provide the entire response in proper markdown format.
|
134 |
+
- Use structured Markdown elements such as headings, subheadings, lists, tables, and links.
|
135 |
+
- Use emphasis on headings, important texts, and phrases.
|
136 |
+
|
137 |
+
3. Proper Citations:
|
138 |
+
- Always use inline citations with embedded source URLs.
|
139 |
+
- The inline citations should be in the format [1], [2], etc.
|
140 |
+
- DO NOT INCLUDE THE 'References' SECTION IN THE RESPONSE.
|
141 |
+
FOLLOW ALL THE GIVEN INSTRUCTIONS, FAILURE TO DO SO WILL RESULT IN THE TERMINATION OF THE CHAT.
|
142 |
+
== CONTEXT ==
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
143 |
{context}
|
144 |
"""
|
145 |
qa_prompt = ChatPromptTemplate.from_messages(
|
|
|
149 |
("human", "{input}")
|
150 |
]
|
151 |
)
|
152 |
+
|
153 |
+
document_prompt = PromptTemplate(input_variables=["page_content"], template="{page_content}")
|
154 |
+
question_answer_chain = create_stuff_documents_chain(llm, qa_prompt, document_prompt=document_prompt)
|
155 |
|
156 |
# Retrieval and Generative (RAG) Chain
|
157 |
rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)
|
|
|
159 |
# Chat message history storage
|
160 |
store = {}
|
161 |
|
|
|
|
|
|
|
162 |
def get_session_history(session_id: str) -> BaseChatMessageHistory:
|
163 |
if session_id not in store:
|
164 |
store[session_id] = ChatMessageHistory()
|
|
|
174 |
output_messages_key="answer",
|
175 |
)
|
176 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
177 |
|
178 |
+
# WebSocket endpoint with streaming
|
179 |
+
@app.websocket("/ws")
|
180 |
+
async def websocket_endpoint(websocket: WebSocket):
|
181 |
+
await websocket.accept()
|
182 |
+
print(f"Client connected: {websocket.client}")
|
183 |
+
session_id = None
|
184 |
try:
|
185 |
+
while True:
|
186 |
+
data = await websocket.receive_json()
|
187 |
+
question = data.get('question')
|
188 |
+
language = data.get('language')
|
189 |
+
if "en" in language:
|
190 |
+
language = "English"
|
191 |
+
else:
|
192 |
+
language = "Arabic"
|
193 |
+
session_id = data.get('session_id', SESSION_ID_DEFAULT)
|
194 |
+
# Process the question
|
195 |
+
try:
|
196 |
+
# Define an async generator for streaming
|
197 |
+
async def stream_response():
|
198 |
+
complete_response = ""
|
199 |
+
context = {}
|
200 |
+
async for chunk in conversational_rag_chain.astream(
|
201 |
+
{"input": question, 'language': language},
|
202 |
+
config={"configurable": {"session_id": session_id}}
|
203 |
+
):
|
204 |
+
if "context" in chunk:
|
205 |
+
context = chunk['context']
|
206 |
+
# Send each chunk to the client
|
207 |
+
if "answer" in chunk:
|
208 |
+
complete_response += chunk['answer']
|
209 |
+
await websocket.send_json({'response': chunk['answer']})
|
210 |
+
if context:
|
211 |
+
citations = re.findall(r'\[(\d+)\]', complete_response)
|
212 |
+
citation_numbers = list(map(int, citations))
|
213 |
+
sources = dict()
|
214 |
+
backup = dict()
|
215 |
+
i=1
|
216 |
+
for index, doc in enumerate(context):
|
217 |
+
if (index+1) in citation_numbers:
|
218 |
+
sources[f"[{index+1}]"] = doc.metadata["source"]
|
219 |
+
else:
|
220 |
+
if doc.metadata["source"] not in backup.values():
|
221 |
+
backup[f"[{i}]"] = doc.metadata["source"]
|
222 |
+
i += 1
|
223 |
+
if sources:
|
224 |
+
await websocket.send_json({'sources': sources})
|
225 |
+
else:
|
226 |
+
await websocket.send_json({'sources': backup})
|
227 |
+
await stream_response()
|
228 |
+
except Exception as e:
|
229 |
+
print(f"Error during message handling: {e}")
|
230 |
+
await websocket.send_json({'response': "Something went wrong, Please try again.." + str(e)})
|
231 |
+
except WebSocketDisconnect:
|
232 |
+
print(f"Client disconnected: {websocket.client}")
|
233 |
+
if session_id:
|
234 |
+
store.pop(session_id, None)
|
235 |
|
236 |
# Home route
|
237 |
+
@app.get("/", response_class=HTMLResponse)
|
238 |
+
async def read_index(request: Request):
|
239 |
+
return templates.TemplateResponse("chat.html", {"request": request})
|
|
|
|
|
|
|
|