Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 |
-
|
10 |
-
from
|
11 |
-
from
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
25 |
|
26 |
# Load environment variables
|
27 |
-
|
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
|
40 |
-
app =
|
41 |
-
|
42 |
-
|
43 |
-
app.
|
44 |
-
|
45 |
-
|
46 |
-
|
|
|
|
|
|
|
|
|
|
|
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":
|
70 |
retriever = PineconeHybridSearchRetriever(
|
71 |
embeddings=embed_model,
|
72 |
sparse_encoder=bm25,
|
73 |
index=pinecone_index,
|
74 |
-
top_k=
|
75 |
-
alpha=0.5
|
76 |
)
|
77 |
|
78 |
# Initialize LLM
|
79 |
-
llm =
|
80 |
|
81 |
# Initialize Reranker
|
82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
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 |
-
|
|
|
|
|
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 |
-
|
192 |
-
|
193 |
-
|
194 |
-
)
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
200 |
|
201 |
# Home route
|
202 |
-
@app.
|
203 |
-
def
|
204 |
-
return
|
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})
|
|
|
|
|
|
|
|