Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
import subprocess
|
| 2 |
import os
|
| 3 |
import torch
|
| 4 |
from dotenv import load_dotenv
|
|
@@ -72,20 +72,6 @@ Chat History:
|
|
| 72 |
|
| 73 |
Current Question: {question}
|
| 74 |
|
| 75 |
-
Let's analyze this systematically:
|
| 76 |
-
|
| 77 |
-
1. First, let's identify the core elements of the question:
|
| 78 |
-
- What is the main topic or action being asked about?
|
| 79 |
-
- What specific Mawared HR features or functions are relevant?
|
| 80 |
-
- What contextual information from chat history might be important?
|
| 81 |
-
|
| 82 |
-
2. Then, consider any implicit context from the chat history:
|
| 83 |
-
- Are there any previous questions that provide relevant context?
|
| 84 |
-
- Has the user mentioned specific scenarios or requirements before?
|
| 85 |
-
- Are there any unresolved points from previous interactions?
|
| 86 |
-
|
| 87 |
-
3. Based on this analysis, let's rewrite the question to be more specific and contextual.
|
| 88 |
-
|
| 89 |
Rewritten question:
|
| 90 |
"""
|
| 91 |
|
|
@@ -96,24 +82,7 @@ Question: {question}
|
|
| 96 |
Retrieved Context: {context}
|
| 97 |
Chat History: {chat_history}
|
| 98 |
|
| 99 |
-
|
| 100 |
-
- Core Request: What is the user trying to achieve?
|
| 101 |
-
- System Components: Which Mawared HR modules are involved?
|
| 102 |
-
- User Context: What do we know about the user's situation?
|
| 103 |
-
|
| 104 |
-
2. Analyzing Available Information:
|
| 105 |
-
- Relevant Context: What specific information from our knowledge base applies?
|
| 106 |
-
- Historical Context: How does the chat history inform this query?
|
| 107 |
-
- Information Gaps: What additional details might we need?
|
| 108 |
-
|
| 109 |
-
3. Solution Formulation:
|
| 110 |
-
- Key Steps: What actions are needed to address this query?
|
| 111 |
-
- Potential Challenges: What issues should we anticipate?
|
| 112 |
-
- Additional Considerations: What else should the user know?
|
| 113 |
-
|
| 114 |
-
Based on this analysis, let's structure our response to be clear, accurate, and helpful.
|
| 115 |
-
|
| 116 |
-
Reasoning: {reasoning}
|
| 117 |
"""
|
| 118 |
|
| 119 |
response_template = """
|
|
@@ -131,12 +100,6 @@ Chat History:
|
|
| 131 |
Current Question:
|
| 132 |
{question}
|
| 133 |
|
| 134 |
-
Please provide a clear, structured response that:
|
| 135 |
-
1. Directly addresses the user's question
|
| 136 |
-
2. Includes specific steps or instructions where relevant
|
| 137 |
-
3. Maintains a professional yet friendly tone
|
| 138 |
-
4. References only information from the provided context
|
| 139 |
-
|
| 140 |
Response:
|
| 141 |
"""
|
| 142 |
|
|
@@ -197,16 +160,18 @@ retriever = db.as_retriever(
|
|
| 197 |
)
|
| 198 |
|
| 199 |
# Initialize LLM
|
| 200 |
-
|
| 201 |
-
|
|
|
|
|
|
|
| 202 |
temperature=0,
|
| 203 |
max_tokens=None,
|
| 204 |
timeout=None,
|
| 205 |
max_retries=2,
|
| 206 |
-
api_key=
|
|
|
|
| 207 |
stream=True,
|
| 208 |
)
|
| 209 |
-
|
| 210 |
# Initialize chains
|
| 211 |
query_rewrite_chain = LLMChain(
|
| 212 |
llm=llm,
|
|
@@ -242,23 +207,17 @@ async def astream_processor(chain, inputs: dict) -> AsyncGenerator[str, None]:
|
|
| 242 |
async def process_stream_async(stream_queue: asyncio.Queue, history: List[List[str]]) -> AsyncGenerator[List[List[str]], None]:
|
| 243 |
"""Handle streaming response processing"""
|
| 244 |
current_response = ""
|
| 245 |
-
|
| 246 |
try:
|
| 247 |
while True:
|
| 248 |
chunk = await stream_queue.get()
|
| 249 |
if chunk is None:
|
| 250 |
break
|
| 251 |
|
| 252 |
-
if isinstance(chunk, dict)
|
| 253 |
-
chunk_text = chunk.get('content', '')
|
| 254 |
-
else:
|
| 255 |
-
chunk_text = str(chunk)
|
| 256 |
-
|
| 257 |
current_response += chunk_text
|
| 258 |
new_history = history.copy()
|
| 259 |
new_history[-1][1] = current_response
|
| 260 |
yield new_history
|
| 261 |
-
|
| 262 |
stream_queue.task_done()
|
| 263 |
except asyncio.CancelledError:
|
| 264 |
logger.info("Stream processing cancelled")
|
|
@@ -272,8 +231,6 @@ async def rewrite_query(question: str, formatted_history: str) -> str:
|
|
| 272 |
question=question,
|
| 273 |
chat_history=formatted_history
|
| 274 |
)
|
| 275 |
-
logger.info(f"Original question: {question}")
|
| 276 |
-
logger.info(f"Rewritten question: {rewritten_question}")
|
| 277 |
return rewritten_question.strip()
|
| 278 |
except Exception as e:
|
| 279 |
logger.error(f"Error in query rewriting: {e}")
|
|
@@ -282,119 +239,21 @@ async def rewrite_query(question: str, formatted_history: str) -> str:
|
|
| 282 |
async def perform_chain_of_thought(question: str, context: str, chat_history: str) -> Dict[str, str]:
|
| 283 |
"""Execute chain of thought reasoning"""
|
| 284 |
try:
|
| 285 |
-
reasoning =
|
| 286 |
-
f"""
|
| 287 |
-
Let's think through this Mawared HR query:
|
| 288 |
-
|
| 289 |
-
Question: {question}
|
| 290 |
-
Context: {context}
|
| 291 |
-
|
| 292 |
-
1. Core Request Analysis:
|
| 293 |
-
- What specifically is the user asking about?
|
| 294 |
-
- What Mawared HR components are involved?
|
| 295 |
-
|
| 296 |
-
2. Context Relevance:
|
| 297 |
-
- How does the provided context relate to the question?
|
| 298 |
-
- What specific information can we use?
|
| 299 |
-
|
| 300 |
-
3. Solution Formation:
|
| 301 |
-
- What are the key points we need to address?
|
| 302 |
-
- What specific steps or information should we provide?
|
| 303 |
-
|
| 304 |
-
Reasoning:
|
| 305 |
-
"""
|
| 306 |
-
)
|
| 307 |
-
|
| 308 |
cot_analysis = await cot_chain.arun(
|
| 309 |
question=question,
|
| 310 |
context=context,
|
| 311 |
chat_history=chat_history,
|
| 312 |
reasoning=reasoning
|
| 313 |
)
|
| 314 |
-
|
| 315 |
-
return {
|
| 316 |
-
"reasoning": reasoning,
|
| 317 |
-
"cot_analysis": cot_analysis
|
| 318 |
-
}
|
| 319 |
except Exception as e:
|
| 320 |
logger.error(f"Error in chain of thought reasoning: {e}")
|
| 321 |
-
return {
|
| 322 |
-
"reasoning": "Error in reasoning process",
|
| 323 |
-
"cot_analysis": "Error in chain of thought process"
|
| 324 |
-
}
|
| 325 |
-
|
| 326 |
-
async def generate_streaming_response(question: str, context: str, chat_history: str, cot_analysis: str) -> AsyncGenerator[str, None]:
|
| 327 |
-
"""Generate streaming response using all available context"""
|
| 328 |
-
try:
|
| 329 |
-
inputs = {
|
| 330 |
-
"question": question,
|
| 331 |
-
"context": context,
|
| 332 |
-
"chat_history": chat_history,
|
| 333 |
-
"cot_analysis": cot_analysis
|
| 334 |
-
}
|
| 335 |
-
|
| 336 |
-
async for chunk in astream_processor(response_chain, inputs):
|
| 337 |
-
if chunk:
|
| 338 |
-
yield chunk
|
| 339 |
-
except Exception as e:
|
| 340 |
-
logger.error(f"Error in response generation: {e}")
|
| 341 |
-
yield "I apologize, but I encountered an error while generating the response."
|
| 342 |
|
| 343 |
chat_history = ChatHistory()
|
| 344 |
|
| 345 |
-
|
| 346 |
-
"""Main function to handle questions and generate responses"""
|
| 347 |
-
try:
|
| 348 |
-
if history is None:
|
| 349 |
-
history = []
|
| 350 |
-
|
| 351 |
-
chat_history.add_message("user", question)
|
| 352 |
-
formatted_history = chat_history.get_formatted_history()
|
| 353 |
-
|
| 354 |
-
rewritten_question = await rewrite_query(question, formatted_history)
|
| 355 |
-
context_docs = await asyncio.to_thread(retriever.get_relevant_documents, rewritten_question)
|
| 356 |
-
context = "\n".join([doc.page_content for doc in context_docs])
|
| 357 |
-
|
| 358 |
-
cot_results = await perform_chain_of_thought(rewritten_question, context, formatted_history)
|
| 359 |
-
|
| 360 |
-
history.append([question, ""])
|
| 361 |
-
stream_queue = asyncio.Queue()
|
| 362 |
-
|
| 363 |
-
async def stream_manager():
|
| 364 |
-
try:
|
| 365 |
-
async for chunk in generate_streaming_response(
|
| 366 |
-
rewritten_question,
|
| 367 |
-
context,
|
| 368 |
-
formatted_history,
|
| 369 |
-
cot_results["cot_analysis"]
|
| 370 |
-
):
|
| 371 |
-
if chunk:
|
| 372 |
-
await stream_queue.put(chunk)
|
| 373 |
-
await stream_queue.put(None)
|
| 374 |
-
except Exception as e:
|
| 375 |
-
logger.error(f"Streaming error: {e}")
|
| 376 |
-
await stream_queue.put(None)
|
| 377 |
-
|
| 378 |
-
asyncio.create_task(stream_manager())
|
| 379 |
-
|
| 380 |
-
async for updated_history in process_stream_async(stream_queue, history):
|
| 381 |
-
response = updated_history[-1][1]
|
| 382 |
-
yield "", updated_history
|
| 383 |
-
|
| 384 |
-
chat_history.add_message("assistant", response)
|
| 385 |
-
|
| 386 |
-
except Exception as e:
|
| 387 |
-
logger.error(f"Error during question processing: {e}")
|
| 388 |
-
logger.exception("Detailed error:")
|
| 389 |
-
if not history:
|
| 390 |
-
history = []
|
| 391 |
-
history.append([question, "An error occurred. Please try again later."])
|
| 392 |
-
yield "", history
|
| 393 |
-
|
| 394 |
-
def clear_chat():
|
| 395 |
-
"""Clear chat history"""
|
| 396 |
-
chat_history.clear()
|
| 397 |
-
return [], ""
|
| 398 |
|
| 399 |
# Gradio Interface
|
| 400 |
with gr.Blocks(theme='Hev832/Applio') as iface:
|
|
|
|
| 1 |
+
import subprocess
|
| 2 |
import os
|
| 3 |
import torch
|
| 4 |
from dotenv import load_dotenv
|
|
|
|
| 72 |
|
| 73 |
Current Question: {question}
|
| 74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
Rewritten question:
|
| 76 |
"""
|
| 77 |
|
|
|
|
| 82 |
Retrieved Context: {context}
|
| 83 |
Chat History: {chat_history}
|
| 84 |
|
| 85 |
+
Reasoning:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
"""
|
| 87 |
|
| 88 |
response_template = """
|
|
|
|
| 100 |
Current Question:
|
| 101 |
{question}
|
| 102 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
Response:
|
| 104 |
"""
|
| 105 |
|
|
|
|
| 160 |
)
|
| 161 |
|
| 162 |
# Initialize LLM
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
llm = ChatOpenAI(
|
| 166 |
+
model="Qwen/Qwen2.5-72B-Instruct",
|
| 167 |
temperature=0,
|
| 168 |
max_tokens=None,
|
| 169 |
timeout=None,
|
| 170 |
max_retries=2,
|
| 171 |
+
api_key=HF_TOKEN,
|
| 172 |
+
base_url="https://api-inference.huggingface.co/v1/",
|
| 173 |
stream=True,
|
| 174 |
)
|
|
|
|
| 175 |
# Initialize chains
|
| 176 |
query_rewrite_chain = LLMChain(
|
| 177 |
llm=llm,
|
|
|
|
| 207 |
async def process_stream_async(stream_queue: asyncio.Queue, history: List[List[str]]) -> AsyncGenerator[List[List[str]], None]:
|
| 208 |
"""Handle streaming response processing"""
|
| 209 |
current_response = ""
|
|
|
|
| 210 |
try:
|
| 211 |
while True:
|
| 212 |
chunk = await stream_queue.get()
|
| 213 |
if chunk is None:
|
| 214 |
break
|
| 215 |
|
| 216 |
+
chunk_text = chunk.get('content', '') if isinstance(chunk, dict) else str(chunk)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
current_response += chunk_text
|
| 218 |
new_history = history.copy()
|
| 219 |
new_history[-1][1] = current_response
|
| 220 |
yield new_history
|
|
|
|
| 221 |
stream_queue.task_done()
|
| 222 |
except asyncio.CancelledError:
|
| 223 |
logger.info("Stream processing cancelled")
|
|
|
|
| 231 |
question=question,
|
| 232 |
chat_history=formatted_history
|
| 233 |
)
|
|
|
|
|
|
|
| 234 |
return rewritten_question.strip()
|
| 235 |
except Exception as e:
|
| 236 |
logger.error(f"Error in query rewriting: {e}")
|
|
|
|
| 239 |
async def perform_chain_of_thought(question: str, context: str, chat_history: str) -> Dict[str, str]:
|
| 240 |
"""Execute chain of thought reasoning"""
|
| 241 |
try:
|
| 242 |
+
reasoning = "..."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
cot_analysis = await cot_chain.arun(
|
| 244 |
question=question,
|
| 245 |
context=context,
|
| 246 |
chat_history=chat_history,
|
| 247 |
reasoning=reasoning
|
| 248 |
)
|
| 249 |
+
return {"reasoning": reasoning, "cot_analysis": cot_analysis}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
except Exception as e:
|
| 251 |
logger.error(f"Error in chain of thought reasoning: {e}")
|
| 252 |
+
return {"reasoning": "", "cot_analysis": ""}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
|
| 254 |
chat_history = ChatHistory()
|
| 255 |
|
| 256 |
+
# The rest remains the same for Gradio components.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
# Gradio Interface
|
| 259 |
with gr.Blocks(theme='Hev832/Applio') as iface:
|