Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -3,9 +3,11 @@ nltk.download('punkt_tab')
|
|
3 |
|
4 |
import os
|
5 |
from dotenv import load_dotenv
|
6 |
-
|
7 |
-
from
|
8 |
-
from
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
# Load environment variables
|
22 |
-
|
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
|
35 |
-
app =
|
36 |
-
|
37 |
-
|
38 |
-
app.
|
39 |
-
|
40 |
-
|
41 |
-
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
59 |
-
|
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":
|
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 |
# 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 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
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 |
-
|
|
|
|
|
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 |
-
|
185 |
-
|
186 |
-
|
187 |
-
)
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
193 |
|
194 |
# Home route
|
195 |
-
@app.
|
196 |
-
def
|
197 |
-
return
|
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})
|
|
|
|
|
|
|
|