Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,9 +1,13 @@
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
from dotenv import load_dotenv
|
3 |
import asyncio
|
4 |
-
from
|
5 |
-
from
|
6 |
-
from
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
# Load environment variables
|
20 |
load_dotenv(".env")
|
@@ -22,6 +31,7 @@ USER_AGENT = os.getenv("USER_AGENT")
|
|
22 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
23 |
SECRET_KEY = os.getenv("SECRET_KEY")
|
24 |
PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")
|
|
|
25 |
SESSION_ID_DEFAULT = "abc123"
|
26 |
|
27 |
# Set environment variables
|
@@ -29,14 +39,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
|
33 |
-
app =
|
34 |
-
|
35 |
-
|
36 |
-
app.
|
37 |
-
|
38 |
-
|
39 |
-
|
|
|
|
|
|
|
|
|
|
|
40 |
|
41 |
# Function to initialize Pinecone connection
|
42 |
def initialize_pinecone(index_name: str):
|
@@ -47,7 +62,6 @@ def initialize_pinecone(index_name: str):
|
|
47 |
print(f"Error initializing Pinecone: {e}")
|
48 |
raise
|
49 |
|
50 |
-
|
51 |
##################################################
|
52 |
## Change down here
|
53 |
##################################################
|
@@ -56,39 +70,32 @@ def initialize_pinecone(index_name: str):
|
|
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="
|
82 |
retriever = PineconeHybridSearchRetriever(
|
83 |
embeddings=embed_model,
|
84 |
sparse_encoder=bm25,
|
85 |
index=pinecone_index,
|
86 |
-
top_k=
|
87 |
-
alpha=0.5
|
88 |
)
|
89 |
|
|
|
|
|
|
|
90 |
# Initialize LLM
|
91 |
-
llm =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
|
93 |
# Contextualization prompt and retriever
|
94 |
contextualize_q_system_prompt = """Given a chat history and the latest user question \
|
@@ -106,33 +113,27 @@ contextualize_q_prompt = ChatPromptTemplate.from_messages(
|
|
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 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
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 +143,9 @@ qa_prompt = ChatPromptTemplate.from_messages(
|
|
142 |
("human", "{input}")
|
143 |
]
|
144 |
)
|
145 |
-
|
|
|
|
|
146 |
|
147 |
# Retrieval and Generative (RAG) Chain
|
148 |
rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)
|
@@ -150,9 +153,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,46 +168,69 @@ 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 |
-
|
197 |
-
|
198 |
-
|
199 |
-
)
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
205 |
|
206 |
# Home route
|
207 |
-
@app.
|
208 |
-
def
|
209 |
-
return
|
210 |
|
211 |
-
# Main function to run the app
|
212 |
-
if __name__ == '__main__':
|
213 |
-
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")
|
|
|
31 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
32 |
SECRET_KEY = os.getenv("SECRET_KEY")
|
33 |
PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")
|
34 |
+
HUGGINGFACE_TOKEN = os.getenv("huggingface_api_key")
|
35 |
SESSION_ID_DEFAULT = "abc123"
|
36 |
|
37 |
# Set environment variables
|
|
|
39 |
os.environ["GROQ_API_KEY"] = GROQ_API_KEY
|
40 |
os.environ["TOKENIZERS_PARALLELISM"] = 'true'
|
41 |
|
42 |
+
# Initialize FastAPI app and CORS
|
43 |
+
app = FastAPI()
|
44 |
+
origins = ["*"] # Adjust as needed
|
45 |
+
|
46 |
+
app.add_middleware(
|
47 |
+
CORSMiddleware,
|
48 |
+
allow_origins=origins,
|
49 |
+
allow_credentials=True,
|
50 |
+
allow_methods=["*"],
|
51 |
+
allow_headers=["*"],
|
52 |
+
)
|
53 |
+
|
54 |
+
templates = Jinja2Templates(directory="templates")
|
55 |
|
56 |
# Function to initialize Pinecone connection
|
57 |
def initialize_pinecone(index_name: str):
|
|
|
62 |
print(f"Error initializing Pinecone: {e}")
|
63 |
raise
|
64 |
|
|
|
65 |
##################################################
|
66 |
## Change down here
|
67 |
##################################################
|
|
|
70 |
pinecone_index = initialize_pinecone("uae-national-library-and-archives-vectorstore")
|
71 |
bm25 = BM25Encoder().load("./UAE-NLA.json")
|
72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
##################################################
|
74 |
##################################################
|
75 |
|
|
|
|
|
76 |
# Initialize models and retriever
|
77 |
+
embed_model = HuggingFaceEmbeddings(model_name="jinaai/jina-embeddings-v3", model_kwargs={"trust_remote_code":True})
|
78 |
retriever = PineconeHybridSearchRetriever(
|
79 |
embeddings=embed_model,
|
80 |
sparse_encoder=bm25,
|
81 |
index=pinecone_index,
|
82 |
+
top_k=10,
|
83 |
+
alpha=0.5,
|
84 |
)
|
85 |
|
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 |
+
|
89 |
# Initialize LLM
|
90 |
+
# llm = ChatPerplexity(temperature=0, pplx_api_key=GROQ_API_KEY, model="llama-3.1-sonar-large-128k-chat", max_tokens=512, max_retries=2)
|
91 |
+
|
92 |
+
# Initialize Reranker
|
93 |
+
# model = HuggingFaceCrossEncoder(model_name="BAAI/bge-reranker-base")
|
94 |
+
# compressor = CrossEncoderReranker(model=model, top_n=10)
|
95 |
+
|
96 |
+
# compression_retriever = ContextualCompressionRetriever(
|
97 |
+
# base_compressor=compressor, base_retriever=retriever
|
98 |
+
# )
|
99 |
|
100 |
# Contextualization prompt and retriever
|
101 |
contextualize_q_system_prompt = """Given a chat history and the latest user question \
|
|
|
113 |
history_aware_retriever = create_history_aware_retriever(llm, retriever, contextualize_q_prompt)
|
114 |
|
115 |
# QA system prompt and chain
|
116 |
+
qa_system_prompt = """ You are a highly skilled information retrieval assistant. Use the following context to answer questions effectively.
|
117 |
+
If you don't know the answer, simply state that you don't know.
|
118 |
+
YOUR ANSWER SHOULD BE IN '{language}' LANGUAGE.
|
119 |
+
When responding to queries, follow these guidelines:
|
120 |
+
1. Provide Clear Answers:
|
121 |
+
- 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.
|
122 |
+
- Ensure the response directly addresses the query with accurate and relevant information.
|
123 |
+
- Do not give long answers. Provide detailed but concise responses.
|
124 |
+
|
125 |
+
2. Formatting for Readability:
|
126 |
+
- Provide the entire response in proper markdown format.
|
127 |
+
- Use structured Markdown elements such as headings, subheadings, lists, tables, and links.
|
128 |
+
- Use emphasis on headings, important texts, and phrases.
|
129 |
+
|
130 |
+
3. Proper Citations:
|
131 |
+
- Always use inline citations with embedded source URLs.
|
132 |
+
- The inline citations should be in the format [1], [2], etc.
|
133 |
+
- DO NOT INCLUDE THE 'References' SECTION IN THE RESPONSE.
|
134 |
+
|
135 |
+
FOLLOW ALL THE GIVEN INSTRUCTIONS, FAILURE TO DO SO WILL RESULT IN THE TERMINATION OF THE CHAT.
|
136 |
+
== CONTEXT ==
|
|
|
|
|
|
|
|
|
|
|
|
|
137 |
{context}
|
138 |
"""
|
139 |
qa_prompt = ChatPromptTemplate.from_messages(
|
|
|
143 |
("human", "{input}")
|
144 |
]
|
145 |
)
|
146 |
+
|
147 |
+
document_prompt = PromptTemplate(input_variables=["page_content", "source"], template="{page_content} \n\n Source: {source}")
|
148 |
+
question_answer_chain = create_stuff_documents_chain(llm, qa_prompt, document_prompt=document_prompt)
|
149 |
|
150 |
# Retrieval and Generative (RAG) Chain
|
151 |
rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)
|
|
|
153 |
# Chat message history storage
|
154 |
store = {}
|
155 |
|
|
|
|
|
|
|
156 |
def get_session_history(session_id: str) -> BaseChatMessageHistory:
|
157 |
if session_id not in store:
|
158 |
store[session_id] = ChatMessageHistory()
|
|
|
168 |
output_messages_key="answer",
|
169 |
)
|
170 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
171 |
|
172 |
+
# WebSocket endpoint with streaming
|
173 |
+
@app.websocket("/ws")
|
174 |
+
async def websocket_endpoint(websocket: WebSocket):
|
175 |
+
await websocket.accept()
|
176 |
+
print(f"Client connected: {websocket.client}")
|
177 |
+
session_id = None
|
178 |
try:
|
179 |
+
while True:
|
180 |
+
data = await websocket.receive_json()
|
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 |
+
# Process the question
|
189 |
+
try:
|
190 |
+
# Define an async generator for streaming
|
191 |
+
async def stream_response():
|
192 |
+
complete_response = ""
|
193 |
+
context = {}
|
194 |
+
async for chunk in conversational_rag_chain.astream(
|
195 |
+
{"input": question, 'language': language},
|
196 |
+
config={"configurable": {"session_id": session_id}}
|
197 |
+
):
|
198 |
+
if "context" in chunk:
|
199 |
+
context = chunk['context']
|
200 |
+
# Send each chunk to the client
|
201 |
+
if "answer" in chunk:
|
202 |
+
complete_response += chunk['answer']
|
203 |
+
await websocket.send_json({'response': chunk['answer']})
|
204 |
+
|
205 |
+
if context:
|
206 |
+
citations = re.findall(r'\[(\d+)\]', complete_response)
|
207 |
+
citation_numbers = list(map(int, citations))
|
208 |
+
sources = dict()
|
209 |
+
backup = dict()
|
210 |
+
i=1
|
211 |
+
for index, doc in enumerate(context):
|
212 |
+
if (index+1) in citation_numbers:
|
213 |
+
sources[f"[{index+1}]"] = doc.metadata["source"]
|
214 |
+
else:
|
215 |
+
if doc.metadata["source"] not in backup.values():
|
216 |
+
backup[f"[{i}]"] = doc.metadata["source"]
|
217 |
+
i += 1
|
218 |
+
if sources:
|
219 |
+
await websocket.send_json({'sources': sources})
|
220 |
+
else:
|
221 |
+
await websocket.send_json({'sources': backup})
|
222 |
+
|
223 |
+
await stream_response()
|
224 |
+
except Exception as e:
|
225 |
+
print(f"Error during message handling: {e}")
|
226 |
+
await websocket.send_json({'response': "Something went wrong, Please try again." + str(e)})
|
227 |
+
except WebSocketDisconnect:
|
228 |
+
print(f"Client disconnected: {websocket.client}")
|
229 |
+
if session_id:
|
230 |
+
store.pop(session_id, None)
|
231 |
|
232 |
# Home route
|
233 |
+
@app.get("/", response_class=HTMLResponse)
|
234 |
+
async def read_index(request: Request):
|
235 |
+
return templates.TemplateResponse("chat.html", {"request": request})
|
236 |
|
|
|
|
|
|