Ritesh-hf commited on
Commit
418eb10
1 Parent(s): 198b425

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -106
app.py CHANGED
@@ -1,9 +1,13 @@
 
 
 
1
  import os
2
  from dotenv import load_dotenv
3
  import asyncio
4
- from flask import Flask, request, render_template
5
- from flask_cors import CORS
6
- from flask_socketio import SocketIO, emit, join_room, leave_room
 
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,12 @@ 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 langchain_groq import ChatGroq
 
 
 
 
 
18
 
19
  # Load environment variables
20
  load_dotenv(".env")
@@ -29,14 +38,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 Flask app and SocketIO with CORS
33
- app = Flask(__name__)
34
- CORS(app)
35
- socketio = SocketIO(app, cors_allowed_origins="*")
36
- app.config['SESSION_COOKIE_SECURE'] = True # Use HTTPS
37
- app.config['SESSION_COOKIE_HTTPONLY'] = True
38
- app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
39
- app.config['SECRET_KEY'] = SECRET_KEY
 
 
 
 
 
40
 
41
  # Function to initialize Pinecone connection
42
  def initialize_pinecone(index_name: str):
@@ -47,36 +61,17 @@ def initialize_pinecone(index_name: str):
47
  print(f"Error initializing Pinecone: {e}")
48
  raise
49
 
50
-
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-multilingual-base", model_kwargs={"trust_remote_code":True})
82
  retriever = PineconeHybridSearchRetriever(
@@ -84,11 +79,19 @@ retriever = PineconeHybridSearchRetriever(
84
  sparse_encoder=bm25,
85
  index=pinecone_index,
86
  top_k=20,
87
- alpha=0.5
88
  )
89
 
90
  # Initialize LLM
91
- llm = ChatGroq(model="llama-3.1-70b-versatile", temperature=0, max_tokens=1024, max_retries=2)
 
 
 
 
 
 
 
 
92
 
93
  # Contextualization prompt and retriever
94
  contextualize_q_system_prompt = """Given a chat history and the latest user question \
@@ -103,36 +106,26 @@ contextualize_q_prompt = ChatPromptTemplate.from_messages(
103
  ("human", "{input}")
104
  ]
105
  )
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
- Your answer should be in {language} language. \
112
- Provide answers in proper HTML format and keep them concise. \
113
-
114
- When responding to queries, follow these guidelines: \
115
-
116
- 1. Provide Clear Answers: \
117
- - Based on the language of the question, you have to answer in that language. E.g. if the question is in English language then answer in the English language or if the question is in Arabic language then you should answer in Arabic language. /
118
- - Ensure the response directly addresses the query with accurate and relevant information.\
119
-
120
- 2. Include Detailed References: \
121
- - Links to Sources: Include URLs to credible sources where users can verify information or explore further. \
122
- - Reference Sites: Mention specific websites or platforms that offer additional information. \
123
- - Downloadable Materials: Provide links to any relevant downloadable resources if applicable. \
124
-
125
- 3. Formatting for Readability: \
126
- - The answer should be in a proper HTML format with appropriate tags. \
127
- - For arabic language response align the text to right and convert numbers also.
128
- - Double check if the language of answer is correct or not.
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 +135,9 @@ qa_prompt = ChatPromptTemplate.from_messages(
142
  ("human", "{input}")
143
  ]
144
  )
145
- question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)
 
 
146
 
147
  # Retrieval and Generative (RAG) Chain
148
  rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)
@@ -150,9 +145,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,48 +160,59 @@ 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
- for chunk in chain.stream(
197
- {"input": question, 'language': language},
198
- config={"configurable": {"session_id": session_id}},
199
- ):
200
- print(chunk)
201
- emit('response', chunk, room=request.sid)
202
- except Exception as e:
203
- print(e)
204
- print(f"Error during message handling: {e}")
205
- emit('response', {"error": "An error occurred while processing your request."}, room=request.sid)
206
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
 
208
  # Home route
209
- @app.route("/")
210
- def index_view():
211
- return render_template('chat.html')
212
-
213
- # Main function to run the app
214
- if __name__ == '__main__':
215
- 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
+ import re
27
 
28
  # Load environment variables
29
  load_dotenv(".env")
 
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("vector-store-index")
70
  bm25 = BM25Encoder().load("./bm25_u.ae.json")
71
 
 
 
 
 
 
 
 
72
  ##################################################
73
  ##################################################
74
 
 
 
75
  # Initialize models and retriever
76
  embed_model = HuggingFaceEmbeddings(model_name="Alibaba-NLP/gte-multilingual-base", model_kwargs={"trust_remote_code":True})
77
  retriever = PineconeHybridSearchRetriever(
 
79
  sparse_encoder=bm25,
80
  index=pinecone_index,
81
  top_k=20,
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 \
 
106
  ("human", "{input}")
107
  ]
108
  )
109
+ history_aware_retriever = create_history_aware_retriever(llm, compression_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, simply 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
+ - Based on the language of the question, you have to answer in that language. E.g., if the question is in English, then answer in English; if the question is in Arabic, you should answer 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
+ 2. Formatting for Readability:
121
+ - Provide the entire response in proper markdown format.
122
+ - Use structured Maekdown elements such as headings, subheading, lists, tables, and links.
123
+ - Use emaphsis on headings, important texts and phrases.
124
+ 3. Proper Citations:
125
+ - ALWAYS USE INLINE CITATIONS with embed source URLs where users can verify information or explore further.
126
+ - The inline citations should be in the format [1], [2], etc.
127
+ - DO not inlcude references at the end of response.
128
+ FOLLOW ALL THE GIVEN INSTRUCTIONS, FAILURE TO DO SO WILL RESULT IN TERMINATION OF THE CHAT.
 
 
 
 
 
 
 
 
 
 
129
  {context}
130
  """
131
  qa_prompt = ChatPromptTemplate.from_messages(
 
135
  ("human", "{input}")
136
  ]
137
  )
138
+
139
+ document_prompt = PromptTemplate(input_variables=["page_content", "source"], template="{page_content} \n\n Source: {source}")
140
+ question_answer_chain = create_stuff_documents_chain(llm, qa_prompt, document_prompt=document_prompt)
141
 
142
  # Retrieval and Generative (RAG) Chain
143
  rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)
 
145
  # Chat message history storage
146
  store = {}
147
 
 
 
 
148
  def get_session_history(session_id: str) -> BaseChatMessageHistory:
149
  if session_id not in store:
150
  store[session_id] = ChatMessageHistory()
 
160
  output_messages_key="answer",
161
  )
162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
+ # WebSocket endpoint with streaming
165
+ @app.websocket("/ws")
166
+ async def websocket_endpoint(websocket: WebSocket):
167
+ await websocket.accept()
168
+ print(f"Client connected: {websocket.client}")
169
+ session_id = None
170
  try:
171
+ while True:
172
+ data = await websocket.receive_json()
173
+ question = data.get('question')
174
+ language = data.get('language')
175
+ if "en" in language:
176
+ language = "English"
177
+ else:
178
+ language = "Arabic"
179
+ session_id = data.get('session_id', SESSION_ID_DEFAULT)
180
+ # Process the question
181
+ try:
182
+ # Define an async generator for streaming
183
+ async def stream_response():
184
+ complete_response = ""
185
+ context = {}
186
+ async for chunk in conversational_rag_chain.astream(
187
+ {"input": question, 'language': language},
188
+ config={"configurable": {"session_id": session_id}}
189
+ ):
190
+ if "context" in chunk:
191
+ context = chunk['context']
192
+ # Send each chunk to the client
193
+ if "answer" in chunk:
194
+ complete_response += chunk['answer']
195
+ await websocket.send_json({'response': chunk['answer']})
196
+
197
+ if context:
198
+ citations = re.findall(r'\[(\d+)\]', complete_response)
199
+ citation_numbers = list(map(int, citations))
200
+ sources = dict()
201
+ for index, doc in enumerate(context):
202
+ if (index+1) in citation_numbers:
203
+ sources[f"[{index+1}]"] = doc.metadata["source"]
204
+ await websocket.send_json({'sources': sources})
205
+
206
+ await stream_response()
207
+ except Exception as e:
208
+ print(f"Error during message handling: {e}")
209
+ await websocket.send_json({'response': "Something went wrong, Please try again.."})
210
+ except WebSocketDisconnect:
211
+ print(f"Client disconnected: {websocket.client}")
212
+ if session_id:
213
+ store.pop(session_id, None)
214
 
215
  # Home route
216
+ @app.get("/", response_class=HTMLResponse)
217
+ async def read_index(request: Request):
218
+ return templates.TemplateResponse("chat.html", {"request": request})