Ritesh-hf commited on
Commit
103a1eb
1 Parent(s): 8ff6cec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -95
app.py CHANGED
@@ -3,9 +3,11 @@ nltk.download('punkt_tab')
3
 
4
  import os
5
  from dotenv import load_dotenv
6
- from flask import Flask, request, render_template
7
- from flask_cors import CORS
8
- from flask_socketio import SocketIO, emit, join_room, leave_room
 
 
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 langchain_groq import ChatGroq
 
 
 
 
 
20
 
21
  # Load environment variables
22
- # load_dotenv(".env")
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 Flask app and SocketIO with CORS
35
- app = Flask(__name__)
36
- CORS(app)
37
- socketio = SocketIO(app, cors_allowed_origins="*")
38
- app.config['SESSION_COOKIE_SECURE'] = True # Use HTTPS
39
- app.config['SESSION_COOKIE_HTTPONLY'] = True
40
- app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
41
- app.config['SECRET_KEY'] = SECRET_KEY
 
 
 
 
 
42
 
43
  # Function to initialize Pinecone connection
44
  def initialize_pinecone(index_name: str):
@@ -49,34 +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
-
58
- # #### This is for UAE Economic Department Website
59
- pinecone_index = initialize_pinecone("abu-dhabi-government")
60
- bm25 = BM25Encoder().load("./abu-dhabi-governemnt.json")
61
-
62
-
63
 
64
  ##################################################
65
  ##################################################
66
 
67
-
68
  # Initialize models and retriever
69
- embed_model = HuggingFaceEmbeddings(model_name="jinaai/jina-embeddings-v3",model_kwargs={"trust_remote_code": True})
70
  retriever = PineconeHybridSearchRetriever(
71
  embeddings=embed_model,
72
  sparse_encoder=bm25,
73
  index=pinecone_index,
74
- top_k=20,
75
- alpha=0.5
76
  )
77
 
78
  # Initialize LLM
79
- llm = ChatGroq(model="llama-3.1-70b-versatile", temperature=0, max_tokens=1024, max_retries=2)
 
 
 
 
 
 
 
 
80
 
81
  # Contextualization prompt and retriever
82
  contextualize_q_system_prompt = """Given a chat history and the latest user question \
@@ -94,33 +109,27 @@ contextualize_q_prompt = ChatPromptTemplate.from_messages(
94
  history_aware_retriever = create_history_aware_retriever(llm, retriever, contextualize_q_prompt)
95
 
96
  # QA system prompt and chain
97
- qa_system_prompt = """You are a highly skilled information retrieval assistant. Use the following context to answer questions effectively. \
98
- If you don't know the answer, simply state that you don't know. \
99
- Your answer should be in {language} language. \
100
- Provide answers in proper HTML format and keep them concise. \
101
-
102
- When responding to queries, follow these guidelines: \
103
-
104
- 1. Provide Clear Answers: \
105
- - 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. /
106
- - Ensure the response directly addresses the query with accurate and relevant information.\
107
-
108
- 2. Include Detailed References: \
109
- - Links to Sources: Include URLs to credible sources where users can verify information or explore further. \
110
- - Reference Sites: Mention specific websites or platforms that offer additional information. \
111
- - Downloadable Materials: Provide links to any relevant downloadable resources if applicable. \
112
-
113
- 3. Formatting for Readability: \
114
- - The answer should be in a proper HTML format with appropriate tags. \
115
- - For arabic language response align the text to right and convert numbers also.
116
- - Double check if the language of answer is correct or not.
117
- - Use bullet points or numbered lists where applicable to present information clearly. \
118
- - Highlight key details using bold or italics. \
119
- - Provide proper and meaningful abbreviations for urls. Do not include naked urls. \
120
-
121
- 4. Organize Content Logically: \
122
- - Structure the content in a logical order, ensuring easy navigation and understanding for the user. \
123
-
124
  {context}
125
  """
126
  qa_prompt = ChatPromptTemplate.from_messages(
@@ -130,7 +139,9 @@ qa_prompt = ChatPromptTemplate.from_messages(
130
  ("human", "{input}")
131
  ]
132
  )
133
- question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)
 
 
134
 
135
  # Retrieval and Generative (RAG) Chain
136
  rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)
@@ -138,9 +149,6 @@ rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chai
138
  # Chat message history storage
139
  store = {}
140
 
141
- def clean_temporary_data():
142
- store.clear()
143
-
144
  def get_session_history(session_id: str) -> BaseChatMessageHistory:
145
  if session_id not in store:
146
  store[session_id] = ChatMessageHistory()
@@ -156,46 +164,68 @@ conversational_rag_chain = RunnableWithMessageHistory(
156
  output_messages_key="answer",
157
  )
158
 
159
- # Function to handle WebSocket connection
160
- @socketio.on('connect')
161
- def handle_connect():
162
- print(f"Client connected: {request.sid}")
163
- emit('connection_response', {'message': 'Connected successfully.'})
164
-
165
- # Function to handle WebSocket disconnection
166
- @socketio.on('disconnect')
167
- def handle_disconnect():
168
- print(f"Client disconnected: {request.sid}")
169
- clean_temporary_data()
170
-
171
- # Function to handle WebSocket messages
172
- @socketio.on('message')
173
- def handle_message(data):
174
- question = data.get('question')
175
- language = data.get('language')
176
- if "en" in language:
177
- language = "English"
178
- else:
179
- language = "Arabic"
180
- session_id = data.get('session_id', SESSION_ID_DEFAULT)
181
- chain = conversational_rag_chain.pick("answer")
182
 
 
 
 
 
 
 
183
  try:
184
- for chunk in chain.stream(
185
- {"input": question, 'language': language},
186
- config={"configurable": {"session_id": session_id}},
187
- ):
188
- emit('response', chunk, room=request.sid)
189
- except Exception as e:
190
- print(f"Error during message handling: {e}")
191
- emit('response', {"error": "An error occurred while processing your request."}, room=request.sid)
192
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
 
194
  # Home route
195
- @app.route("/")
196
- def index_view():
197
- return render_template('chat.html')
198
-
199
- # Main function to run the app
200
- if __name__ == '__main__':
201
- 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("updated-abu-dhabi-government")
70
+ bm25 = BM25Encoder().load("./updated-abu-dhabi-governemnt.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, 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
+ - 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
+ == CONTEXT ==
 
 
 
 
 
 
133
  {context}
134
  """
135
  qa_prompt = ChatPromptTemplate.from_messages(
 
139
  ("human", "{input}")
140
  ]
141
  )
142
+
143
+ document_prompt = PromptTemplate(input_variables=["page_content", "source"], template="{page_content} \n\n Source: {source}")
144
+ question_answer_chain = create_stuff_documents_chain(llm, qa_prompt, document_prompt=document_prompt)
145
 
146
  # Retrieval and Generative (RAG) Chain
147
  rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)
 
149
  # Chat message history storage
150
  store = {}
151
 
 
 
 
152
  def get_session_history(session_id: str) -> BaseChatMessageHistory:
153
  if session_id not in store:
154
  store[session_id] = ChatMessageHistory()
 
164
  output_messages_key="answer",
165
  )
166
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
 
168
+ # WebSocket endpoint with streaming
169
+ @app.websocket("/ws")
170
+ async def websocket_endpoint(websocket: WebSocket):
171
+ await websocket.accept()
172
+ print(f"Client connected: {websocket.client}")
173
+ session_id = None
174
  try:
175
+ while True:
176
+ data = await websocket.receive_json()
177
+ question = data.get('question')
178
+ language = data.get('language')
179
+ if "en" in language:
180
+ language = "English"
181
+ else:
182
+ language = "Arabic"
183
+ session_id = data.get('session_id', SESSION_ID_DEFAULT)
184
+ # Process the question
185
+ try:
186
+ # Define an async generator for streaming
187
+ async def stream_response():
188
+ complete_response = ""
189
+ context = {}
190
+ async for chunk in conversational_rag_chain.astream(
191
+ {"input": question, 'language': language},
192
+ config={"configurable": {"session_id": session_id}}
193
+ ):
194
+ if "context" in chunk:
195
+ context = chunk['context']
196
+ # Send each chunk to the client
197
+ if "answer" in chunk:
198
+ complete_response += chunk['answer']
199
+ await websocket.send_json({'response': chunk['answer']})
200
+
201
+ if context:
202
+ citations = re.findall(r'\[(\d+)\]', complete_response)
203
+ citation_numbers = list(map(int, citations))
204
+ sources = dict()
205
+ backup = dict()
206
+ i=1
207
+ for index, doc in enumerate(context):
208
+ if (index+1) in citation_numbers:
209
+ sources[f"[{index+1}]"] = doc.metadata["source"]
210
+ else:
211
+ if doc.metadata["source"] not in backup.values():
212
+ backup[f"[{i}]"] = doc.metadata["source"]
213
+ i += 1
214
+ if sources:
215
+ await websocket.send_json({'sources': sources})
216
+ else:
217
+ await websocket.send_json({'sources': backup})
218
+
219
+ await stream_response()
220
+ except Exception as e:
221
+ print(f"Error during message handling: {e}")
222
+ await websocket.send_json({'response': "Something went wrong, Please try again." + str(e)})
223
+ except WebSocketDisconnect:
224
+ print(f"Client disconnected: {websocket.client}")
225
+ if session_id:
226
+ store.pop(session_id, None)
227
 
228
  # Home route
229
+ @app.get("/", response_class=HTMLResponse)
230
+ async def read_index(request: Request):
231
+ return templates.TemplateResponse("chat.html", {"request": request})