Update app.py
Browse files
app.py
CHANGED
@@ -12,31 +12,195 @@ import logging
|
|
12 |
from typing import List, Tuple
|
13 |
from dataclasses import dataclass
|
14 |
from datetime import datetime
|
15 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM,
|
16 |
from langchain_huggingface.llms import HuggingFacePipeline
|
17 |
import spaces
|
18 |
|
19 |
-
# [Previous imports and configurations remain the same]
|
20 |
|
21 |
-
#
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
-
|
28 |
-
|
|
|
29 |
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
|
37 |
-
|
38 |
-
|
39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
|
41 |
with gr.Row():
|
42 |
question_input = gr.Textbox(
|
@@ -46,48 +210,6 @@ with gr.Blocks(theme=gr.themes.Soft()) as iface:
|
|
46 |
)
|
47 |
clear_button = gr.Button("Clear Chat", scale=1)
|
48 |
|
49 |
-
def copy_last_response(history):
|
50 |
-
if history:
|
51 |
-
# Find the last assistant message
|
52 |
-
for message in reversed(history):
|
53 |
-
if message["role"] == "assistant":
|
54 |
-
return message["content"]
|
55 |
-
return ""
|
56 |
-
|
57 |
-
# Modified ask_question_gradio function to update the latest response
|
58 |
-
def ask_question_gradio(question, history):
|
59 |
-
try:
|
60 |
-
# Add user question to chat history
|
61 |
-
chat_history.add_message("user", question)
|
62 |
-
|
63 |
-
# Get formatted history
|
64 |
-
formatted_history = chat_history.get_formatted_history()
|
65 |
-
|
66 |
-
# Create chain with current chat history
|
67 |
-
rag_chain = create_rag_chain(formatted_history)
|
68 |
-
|
69 |
-
# Generate response
|
70 |
-
response = ""
|
71 |
-
for chunk in rag_chain.stream(question):
|
72 |
-
response += chunk
|
73 |
-
|
74 |
-
# Add assistant response to chat history
|
75 |
-
chat_history.add_message("assistant", response)
|
76 |
-
|
77 |
-
# Update Gradio chat history
|
78 |
-
history.append({"role": "user", "content": question})
|
79 |
-
history.append({"role": "assistant", "content": response})
|
80 |
-
|
81 |
-
return "", history
|
82 |
-
except Exception as e:
|
83 |
-
logger.error(f"Error during question processing: {e}")
|
84 |
-
return "", history + [{"role": "assistant", "content": "An error occurred. Please try again later."}]
|
85 |
-
|
86 |
-
def clear_chat():
|
87 |
-
chat_history.clear()
|
88 |
-
return [], ""
|
89 |
-
|
90 |
-
# Connect the components
|
91 |
question_input.submit(
|
92 |
ask_question_gradio,
|
93 |
inputs=[question_input, chatbot],
|
@@ -98,31 +220,6 @@ with gr.Blocks(theme=gr.themes.Soft()) as iface:
|
|
98 |
clear_chat,
|
99 |
outputs=[chatbot, question_input]
|
100 |
)
|
101 |
-
|
102 |
-
# Add copy button functionality
|
103 |
-
copy_button.click(
|
104 |
-
copy_last_response,
|
105 |
-
inputs=[chatbot],
|
106 |
-
outputs=[],
|
107 |
-
_js="""
|
108 |
-
async (response) => {
|
109 |
-
await navigator.clipboard.writeText(response);
|
110 |
-
// Optional: Show a toast notification
|
111 |
-
const toast = document.createElement('div');
|
112 |
-
toast.textContent = 'Response copied to clipboard!';
|
113 |
-
toast.style.position = 'fixed';
|
114 |
-
toast.style.bottom = '20px';
|
115 |
-
toast.style.right = '20px';
|
116 |
-
toast.style.backgroundColor = '#4CAF50';
|
117 |
-
toast.style.color = 'white';
|
118 |
-
toast.style.padding = '15px';
|
119 |
-
toast.style.borderRadius = '5px';
|
120 |
-
toast.style.zIndex = '1000';
|
121 |
-
document.body.appendChild(toast);
|
122 |
-
setTimeout(() => toast.remove(), 2000);
|
123 |
-
}
|
124 |
-
"""
|
125 |
-
)
|
126 |
|
127 |
# Launch the Gradio App
|
128 |
if __name__ == "__main__":
|
|
|
12 |
from typing import List, Tuple
|
13 |
from dataclasses import dataclass
|
14 |
from datetime import datetime
|
15 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM ,pipeline
|
16 |
from langchain_huggingface.llms import HuggingFacePipeline
|
17 |
import spaces
|
18 |
|
|
|
19 |
|
20 |
+
# Configure logging
|
21 |
+
logging.basicConfig(level=logging.INFO)
|
22 |
+
logger = logging.getLogger(__name__)
|
23 |
+
|
24 |
+
@dataclass
|
25 |
+
class Message:
|
26 |
+
role: str
|
27 |
+
content: str
|
28 |
+
timestamp: str
|
29 |
+
|
30 |
+
class ChatHistory:
|
31 |
+
def __init__(self):
|
32 |
+
self.messages: List[Message] = []
|
33 |
|
34 |
+
def add_message(self, role: str, content: str):
|
35 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
36 |
+
self.messages.append(Message(role=role, content=content, timestamp=timestamp))
|
37 |
|
38 |
+
def get_formatted_history(self, max_messages: int = 5) -> str:
|
39 |
+
"""Returns the most recent conversation history formatted as a string"""
|
40 |
+
recent_messages = self.messages[-max_messages:] if len(self.messages) > max_messages else self.messages
|
41 |
+
formatted_history = "\n".join([
|
42 |
+
f"{msg.role}: {msg.content}" for msg in recent_messages
|
43 |
+
])
|
44 |
+
return formatted_history
|
45 |
+
|
46 |
+
def clear(self):
|
47 |
+
self.messages = []
|
48 |
+
|
49 |
+
# Load environment variables
|
50 |
+
load_dotenv()
|
51 |
+
|
52 |
+
# HuggingFace API Token
|
53 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
54 |
+
if not HF_TOKEN:
|
55 |
+
logger.error("HF_TOKEN is not set in the environment variables.")
|
56 |
+
exit(1)
|
57 |
+
|
58 |
+
# HuggingFace Embeddings
|
59 |
+
embeddings = HuggingFaceEmbeddings(model_name="BAAI/bge-large-en-v1.5")
|
60 |
+
|
61 |
+
# Qdrant Client Setup
|
62 |
+
try:
|
63 |
+
client = QdrantClient(
|
64 |
+
url=os.getenv("QDRANT_URL"),
|
65 |
+
api_key=os.getenv("QDRANT_API_KEY"),
|
66 |
+
prefer_grpc=True
|
67 |
+
)
|
68 |
+
except Exception as e:
|
69 |
+
logger.error("Failed to connect to Qdrant. Ensure QDRANT_URL and QDRANT_API_KEY are correctly set.")
|
70 |
+
exit(1)
|
71 |
+
|
72 |
+
# Define collection name
|
73 |
+
collection_name = "mawared"
|
74 |
+
|
75 |
+
# Try to create collection
|
76 |
+
try:
|
77 |
+
client.create_collection(
|
78 |
+
collection_name=collection_name,
|
79 |
+
vectors_config=models.VectorParams(
|
80 |
+
size=768, # GTE-large embedding size
|
81 |
+
distance=models.Distance.COSINE
|
82 |
)
|
83 |
+
)
|
84 |
+
logger.info(f"Created new collection: {collection_name}")
|
85 |
+
except Exception as e:
|
86 |
+
if "already exists" in str(e):
|
87 |
+
logger.info(f"Collection {collection_name} already exists, continuing...")
|
88 |
+
else:
|
89 |
+
logger.error(f"Error creating collection: {e}")
|
90 |
+
exit(1)
|
91 |
+
|
92 |
+
# Create Qdrant vector store
|
93 |
+
db = Qdrant(
|
94 |
+
client=client,
|
95 |
+
collection_name=collection_name,
|
96 |
+
embeddings=embeddings,
|
97 |
+
)
|
98 |
+
|
99 |
+
# Create retriever
|
100 |
+
retriever = db.as_retriever(
|
101 |
+
search_type="similarity",
|
102 |
+
search_kwargs={"k": 5}
|
103 |
+
)
|
104 |
+
|
105 |
+
|
106 |
+
# Load model directly
|
107 |
+
|
108 |
+
|
109 |
+
|
110 |
+
# Set up the LLM
|
111 |
+
llm = ChatOpenAI(
|
112 |
+
base_url="https://api-inference.huggingface.co/v1/",
|
113 |
+
temperature=0,
|
114 |
+
api_key=HF_TOKEN,
|
115 |
+
model="meta-llama/Llama-3.3-70B-Instruct",
|
116 |
+
max_tokens=None,
|
117 |
+
timeout=None
|
118 |
|
119 |
+
)
|
120 |
+
|
121 |
+
# Create prompt template with chat history
|
122 |
+
template = """
|
123 |
+
You are an expert assistant specializing in the Mawared HR System.
|
124 |
+
Your task is to provide accurate and contextually relevant answers based on the provided context and chat history.
|
125 |
+
If you need more information, ask targeted clarifying questions.
|
126 |
+
Ensure you provide detailed Numbered step by step to the user and be very accurate.
|
127 |
+
Previous Conversation:
|
128 |
+
{chat_history}
|
129 |
+
Current Context:
|
130 |
+
{context}
|
131 |
+
Current Question:
|
132 |
+
{question}
|
133 |
+
Ask followup questions based on your provided asnwer to create a conversational flow, Only answer form the provided context and chat history , dont make up any information.
|
134 |
+
answer only and only from the given context and knowledgebase.
|
135 |
+
Answer:
|
136 |
+
"""
|
137 |
+
|
138 |
+
prompt = ChatPromptTemplate.from_template(template)
|
139 |
+
|
140 |
+
# Create the RAG chain with chat history
|
141 |
+
def create_rag_chain(chat_history: str):
|
142 |
+
chain = (
|
143 |
+
{
|
144 |
+
"context": retriever,
|
145 |
+
"question": RunnablePassthrough(),
|
146 |
+
"chat_history": lambda x: chat_history
|
147 |
+
}
|
148 |
+
| prompt
|
149 |
+
| llm
|
150 |
+
| StrOutputParser()
|
151 |
+
)
|
152 |
+
return chain
|
153 |
+
|
154 |
+
# Initialize chat history
|
155 |
+
chat_history = ChatHistory()
|
156 |
+
|
157 |
+
# Gradio Function
|
158 |
+
|
159 |
+
def ask_question_gradio(question, history):
|
160 |
+
try:
|
161 |
+
# Add user question to chat history
|
162 |
+
chat_history.add_message("user", question)
|
163 |
+
|
164 |
+
# Get formatted history
|
165 |
+
formatted_history = chat_history.get_formatted_history()
|
166 |
+
|
167 |
+
# Create chain with current chat history
|
168 |
+
rag_chain = create_rag_chain(formatted_history)
|
169 |
+
|
170 |
+
# Generate response
|
171 |
+
response = ""
|
172 |
+
for chunk in rag_chain.stream(question):
|
173 |
+
response += chunk
|
174 |
+
|
175 |
+
# Add assistant response to chat history
|
176 |
+
chat_history.add_message("assistant", response)
|
177 |
+
|
178 |
+
# Update Gradio chat history
|
179 |
+
history.append({"role": "user", "content": question})
|
180 |
+
history.append({"role": "assistant", "content": response})
|
181 |
+
|
182 |
+
return "", history
|
183 |
+
except Exception as e:
|
184 |
+
logger.error(f"Error during question processing: {e}")
|
185 |
+
return "", history + [{"role": "assistant", "content": "An error occurred. Please try again later."}]
|
186 |
+
|
187 |
+
def clear_chat():
|
188 |
+
chat_history.clear()
|
189 |
+
return [], ""
|
190 |
+
|
191 |
+
# Gradio Interface
|
192 |
+
with gr.Blocks(theme=gr.themes.Soft()) as iface:
|
193 |
+
gr.Image("Image.jpg" , width=1200 , height=300 ,show_label=False, show_download_button=False)
|
194 |
+
gr.Markdown("# Mawared HR Assistant")
|
195 |
+
gr.Markdown("Ask questions about the Mawared HR system, and this assistant will provide answers based on the available context and conversation history.")
|
196 |
+
|
197 |
+
|
198 |
+
|
199 |
+
chatbot = gr.Chatbot(
|
200 |
+
height=400,
|
201 |
+
show_label=False,
|
202 |
+
type="messages" # Using the new messages format
|
203 |
+
)
|
204 |
|
205 |
with gr.Row():
|
206 |
question_input = gr.Textbox(
|
|
|
210 |
)
|
211 |
clear_button = gr.Button("Clear Chat", scale=1)
|
212 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
213 |
question_input.submit(
|
214 |
ask_question_gradio,
|
215 |
inputs=[question_input, chatbot],
|
|
|
220 |
clear_chat,
|
221 |
outputs=[chatbot, question_input]
|
222 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
223 |
|
224 |
# Launch the Gradio App
|
225 |
if __name__ == "__main__":
|