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