Ritesh-hf commited on
Commit
99c9119
·
verified ·
1 Parent(s): f702512

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -94
app.py CHANGED
@@ -1,14 +1,13 @@
1
- from gevent import monkey
2
- monkey.patch_all()
3
-
4
  import nltk
5
  nltk.download('punkt_tab')
6
 
7
  import os
8
  from dotenv import load_dotenv
9
- from flask import Flask, request, render_template
10
- from flask_cors import CORS
11
- from flask_socketio import SocketIO, emit, join_room, leave_room
 
 
12
  from langchain.chains import create_history_aware_retriever, create_retrieval_chain
13
  from langchain.chains.combine_documents import create_stuff_documents_chain
14
  from langchain_community.chat_message_histories import ChatMessageHistory
@@ -19,12 +18,15 @@ from pinecone import Pinecone
19
  from pinecone_text.sparse import BM25Encoder
20
  from langchain_huggingface import HuggingFaceEmbeddings
21
  from langchain_community.retrievers import PineconeHybridSearchRetriever
22
- from langchain_groq import ChatGroq
23
  from langchain.retrievers import ContextualCompressionRetriever
24
- from langchain.retrievers.document_compressors import FlashrankRerank
 
 
 
 
25
 
26
  # Load environment variables
27
- # load_dotenv(".env")
28
  USER_AGENT = os.getenv("USER_AGENT")
29
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
30
  SECRET_KEY = os.getenv("SECRET_KEY")
@@ -36,14 +38,19 @@ os.environ['USER_AGENT'] = USER_AGENT
36
  os.environ["GROQ_API_KEY"] = GROQ_API_KEY
37
  os.environ["TOKENIZERS_PARALLELISM"] = 'true'
38
 
39
- # Initialize Flask app and SocketIO with CORS
40
- app = Flask(__name__)
41
- CORS(app)
42
- socketio = SocketIO(app, async_mode='gevent', cors_allowed_origins="*")
43
- app.config['SESSION_COOKIE_SECURE'] = True # Use HTTPS
44
- app.config['SESSION_COOKIE_HTTPONLY'] = True
45
- app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
46
- app.config['SECRET_KEY'] = SECRET_KEY
 
 
 
 
 
47
 
48
  # Function to initialize Pinecone connection
49
  def initialize_pinecone(index_name: str):
@@ -64,22 +71,29 @@ bm25 = BM25Encoder().load("./saudi-arabia-bm25-encoder.json")
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=10,
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
  # Initialize Reranker
82
- compressor = FlashrankRerank()
 
 
 
 
 
 
 
 
83
  compression_retriever = ContextualCompressionRetriever(
84
  base_compressor=compressor, base_retriever=retriever
85
  )
@@ -100,34 +114,23 @@ contextualize_q_prompt = ChatPromptTemplate.from_messages(
100
  history_aware_retriever = create_history_aware_retriever(llm, compression_retriever, contextualize_q_prompt)
101
 
102
  # QA system prompt and chain
103
- qa_system_prompt = """You are a highly skilled information retrieval assistant. Use the following context to answer questions effectively. \
104
- If you don't know the answer, simply state that you don't know. \
105
- Your answer should be in {language} language. \
106
- Provide answers in proper HTML format and keep them concise. \
107
-
108
- When responding to queries, follow these guidelines: \
109
-
110
- 1. Provide Clear Answers: \
111
- - 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. /
112
- - Ensure the response directly addresses the query with accurate and relevant information.\
113
-
114
- 2. Include Detailed References: \
115
- - Links to Sources: Include URLs to credible sources where users can verify information or explore further. \
116
- - Reference Sites: Mention specific websites or platforms that offer additional information. \
117
- - Downloadable Materials: Provide links to any relevant downloadable resources if applicable. \
118
-
119
- 3. Formatting for Readability: \
120
- - The answer should be in a proper Markdown format with appropriate tags. \
121
- - For arabic language response align the text to right and convert numbers also.
122
- - Double check if the language of answer is correct or not.
123
- - Use bullet points or numbered lists where applicable to present information clearly. \
124
- - Highlight key details using bold or italics. \
125
- - Provide referenced urls for when necessary.
126
- - Provide proper and meaningful abbreviations for urls. Do not include naked urls. \
127
-
128
- 4. Organize Content Logically: \
129
- - Structure the content in a logical order, ensuring easy navigation and understanding for the user. \
130
-
131
  {context}
132
  """
133
  qa_prompt = ChatPromptTemplate.from_messages(
@@ -137,7 +140,9 @@ qa_prompt = ChatPromptTemplate.from_messages(
137
  ("human", "{input}")
138
  ]
139
  )
140
- question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)
 
 
141
 
142
  # Retrieval and Generative (RAG) Chain
143
  rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)
@@ -145,9 +150,6 @@ rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chai
145
  # Chat message history storage
146
  store = {}
147
 
148
- def clean_temporary_data():
149
- store.clear()
150
-
151
  def get_session_history(session_id: str) -> BaseChatMessageHistory:
152
  if session_id not in store:
153
  store[session_id] = ChatMessageHistory()
@@ -163,46 +165,59 @@ conversational_rag_chain = RunnableWithMessageHistory(
163
  output_messages_key="answer",
164
  )
165
 
166
- # Function to handle WebSocket connection
167
- @socketio.on('connect')
168
- def handle_connect():
169
- print(f"Client connected: {request.sid}")
170
- emit('connection_response', {'message': 'Connected successfully.'})
171
-
172
- # Function to handle WebSocket disconnection
173
- @socketio.on('disconnect')
174
- def handle_disconnect():
175
- print(f"Client disconnected: {request.sid}")
176
- clean_temporary_data()
177
-
178
- # Function to handle WebSocket messages
179
- @socketio.on('message')
180
- def handle_message(data):
181
- question = data.get('question')
182
- language = data.get('language')
183
- if "en" in language:
184
- language = "English"
185
- else:
186
- language = "Arabic"
187
- session_id = data.get('session_id', SESSION_ID_DEFAULT)
188
- chain = conversational_rag_chain.pick("answer")
189
 
 
 
 
 
 
 
190
  try:
191
- for chunk in chain.stream(
192
- {"input": question, 'language': language},
193
- config={"configurable": {"session_id": session_id}},
194
- ):
195
- emit('response', chunk, room=request.sid)
196
- except Exception as e:
197
- print(f"Error during message handling: {e}")
198
- emit('response', "An error occurred while processing your request.", room=request.sid)
199
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
 
201
  # Home route
202
- @app.route("/")
203
- def index_view():
204
- return render_template('chat.html')
205
-
206
- # Main function to run the app
207
- if __name__ == '__main__':
208
- 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")
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):
 
71
  ##################################################
72
  ##################################################
73
 
 
74
  # Initialize models and retriever
75
+ embed_model = HuggingFaceEmbeddings(model_name="jinaai/jina-embeddings-v3", model_kwargs={"trust_remote_code":True})
76
  retriever = PineconeHybridSearchRetriever(
77
  embeddings=embed_model,
78
  sparse_encoder=bm25,
79
  index=pinecone_index,
80
+ top_k=20,
81
+ alpha=0.5,
82
  )
83
 
84
  # Initialize LLM
85
+ llm = ChatPerplexity(temperature=0, pplx_api_key=GROQ_API_KEY, model="llama-3.1-sonar-large-128k-chat", max_tokens=512, max_retries=2)
86
 
87
  # Initialize Reranker
88
+ # model = HuggingFaceCrossEncoder(model_name="BAAI/bge-reranker-base")
89
+ # compressor = CrossEncoderReranker(model=model, top_n=10)
90
+
91
+ # compression_retriever = ContextualCompressionRetriever(
92
+ # base_compressor=compressor, base_retriever=retriever
93
+ # )
94
+ from langchain.retrievers.document_compressors import LLMChainExtractor
95
+
96
+ compressor = LLMChainExtractor.from_llm(llm)
97
  compression_retriever = ContextualCompressionRetriever(
98
  base_compressor=compressor, base_retriever=retriever
99
  )
 
114
  history_aware_retriever = create_history_aware_retriever(llm, compression_retriever, contextualize_q_prompt)
115
 
116
  # QA system prompt and chain
117
+ qa_system_prompt = """ You are a highly skilled information retrieval assistant. Use the following context to answer questions effectively.
118
+ If you don't know the answer, simply state that you don't know.
119
+ Your answer should be in {language} language.
120
+ When responding to queries, follow these guidelines:
121
+ 1. Provide Clear Answers:
122
+ - 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.
123
+ - Ensure the response directly addresses the query with accurate and relevant information.
124
+ - Do not give long answers. Provide detailed but concise responses.
125
+ 2. Formatting for Readability:
126
+ - Provide the entire response in proper markdown format.
127
+ - Use structured Maekdown elements such as headings, subheading, lists, tables, and links.
128
+ - Use emaphsis on headings, important texts and phrases.
129
+ 3. Proper Citations:
130
+ - ALWAYS USE INLINE CITATIONS with embed source URLs where users can verify information or explore further.
131
+ - The inline citations should be in the format [1], [2], etc.
132
+ - DO not inlcude references at the end of response.
133
+ FOLLOW ALL THE GIVEN INSTRUCTIONS, FAILURE TO DO SO WILL RESULT IN TERMINATION OF THE CHAT.
 
 
 
 
 
 
 
 
 
 
 
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
+ for index, doc in enumerate(context):
207
+ if (index+1) in citation_numbers:
208
+ sources[f"[{index+1}]"] = doc.metadata["source"]
209
+ await websocket.send_json({'sources': sources})
210
+
211
+ await stream_response()
212
+ except Exception as e:
213
+ print(f"Error during message handling: {e}")
214
+ await websocket.send_json({'response': "Something went wrong, Please try again.."})
215
+ except WebSocketDisconnect:
216
+ print(f"Client disconnected: {websocket.client}")
217
+ if session_id:
218
+ store.pop(session_id, None)
219
 
220
  # Home route
221
+ @app.get("/", response_class=HTMLResponse)
222
+ async def read_index(request: Request):
223
+ return templates.TemplateResponse("chat.html", {"request": request})