Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -313,7 +313,7 @@ class ProductionRAGSystem:
|
|
| 313 |
return content[:200] + "..."
|
| 314 |
|
| 315 |
def generate_answer(self, query, search_results):
|
| 316 |
-
"""Generate both AI and extracted answers"""
|
| 317 |
if not search_results:
|
| 318 |
return {
|
| 319 |
'ai_answer': "No information found in documents.",
|
|
@@ -330,7 +330,7 @@ class ProductionRAGSystem:
|
|
| 330 |
# Always generate extracted answer
|
| 331 |
extracted_answer = self.extract_direct_answer(query, best_result['content'])
|
| 332 |
|
| 333 |
-
# Try AI answer
|
| 334 |
ai_answer = None
|
| 335 |
openrouter_key = os.environ.get("OPENROUTER_API_KEY")
|
| 336 |
|
|
@@ -339,11 +339,14 @@ class ProductionRAGSystem:
|
|
| 339 |
prompt = f"Answer briefly: {query}\n\nContext: {context}\n\nAnswer (1 sentence):"
|
| 340 |
|
| 341 |
try:
|
|
|
|
| 342 |
response = requests.post(
|
| 343 |
"https://openrouter.ai/api/v1/chat/completions",
|
| 344 |
headers={
|
| 345 |
"Authorization": f"Bearer {openrouter_key}",
|
| 346 |
-
"Content-Type": "application/json"
|
|
|
|
|
|
|
| 347 |
},
|
| 348 |
json={
|
| 349 |
"model": "openai/gpt-3.5-turbo",
|
|
@@ -354,10 +357,19 @@ class ProductionRAGSystem:
|
|
| 354 |
timeout=10
|
| 355 |
)
|
| 356 |
|
|
|
|
|
|
|
| 357 |
if response.status_code == 200:
|
| 358 |
ai_answer = response.json()['choices'][0]['message']['content'].strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 359 |
except Exception as e:
|
| 360 |
-
st.
|
|
|
|
|
|
|
| 361 |
|
| 362 |
return {
|
| 363 |
'ai_answer': ai_answer,
|
|
@@ -367,7 +379,41 @@ class ProductionRAGSystem:
|
|
| 367 |
'has_both': ai_answer is not None
|
| 368 |
}
|
| 369 |
|
| 370 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 371 |
|
| 372 |
def get_user_id():
|
| 373 |
"""Get unique ID for this user session"""
|
|
@@ -527,12 +573,35 @@ with st.sidebar:
|
|
| 527 |
# Settings
|
| 528 |
st.header("βοΈ Settings")
|
| 529 |
|
| 530 |
-
# API Status
|
| 531 |
openrouter_key = os.environ.get("OPENROUTER_API_KEY")
|
| 532 |
if openrouter_key:
|
| 533 |
-
st.success("π’
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 534 |
else:
|
| 535 |
-
st.
|
|
|
|
| 536 |
|
| 537 |
# RAG Settings
|
| 538 |
use_ai_enhancement = st.checkbox("Use AI Enhancement", value=bool(openrouter_key))
|
|
@@ -602,11 +671,12 @@ if prompt := st.chat_input("Ask questions about your documents..."):
|
|
| 602 |
# Get RAG response
|
| 603 |
with st.chat_message("assistant"):
|
| 604 |
if rag_system and rag_system.model and rag_system.get_collection_count() > 0:
|
| 605 |
-
# Search documents
|
| 606 |
search_results = rag_system.search(prompt, n_results=3)
|
| 607 |
|
| 608 |
-
if
|
| 609 |
-
|
|
|
|
| 610 |
result = rag_system.generate_answer(prompt, search_results)
|
| 611 |
|
| 612 |
# Display AI answer or extracted answer
|
|
@@ -615,7 +685,7 @@ if prompt := st.chat_input("Ask questions about your documents..."):
|
|
| 615 |
st.markdown(f"π€ **AI Answer:** {answer_text}")
|
| 616 |
else:
|
| 617 |
answer_text = result['extracted_answer']
|
| 618 |
-
st.markdown(f"π **Answer:** {answer_text}")
|
| 619 |
|
| 620 |
# Show RAG info
|
| 621 |
if show_sources and result['sources']:
|
|
@@ -640,25 +710,31 @@ if prompt := st.chat_input("Ask questions about your documents..."):
|
|
| 640 |
}
|
| 641 |
|
| 642 |
else:
|
| 643 |
-
# No relevant documents found
|
| 644 |
-
|
| 645 |
-
|
|
|
|
| 646 |
|
| 647 |
assistant_message = {
|
| 648 |
"role": "assistant",
|
| 649 |
-
"content":
|
| 650 |
-
"rag_info": {"sources": [], "confidence": 0}
|
| 651 |
}
|
| 652 |
|
| 653 |
else:
|
| 654 |
-
# RAG system not ready
|
| 655 |
-
|
| 656 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 657 |
|
| 658 |
assistant_message = {
|
| 659 |
"role": "assistant",
|
| 660 |
-
"content":
|
| 661 |
-
"rag_info": {"sources": [], "confidence": 0}
|
| 662 |
}
|
| 663 |
|
| 664 |
# Add assistant message to history
|
|
|
|
| 313 |
return content[:200] + "..."
|
| 314 |
|
| 315 |
def generate_answer(self, query, search_results):
|
| 316 |
+
"""Generate both AI and extracted answers with better error handling"""
|
| 317 |
if not search_results:
|
| 318 |
return {
|
| 319 |
'ai_answer': "No information found in documents.",
|
|
|
|
| 330 |
# Always generate extracted answer
|
| 331 |
extracted_answer = self.extract_direct_answer(query, best_result['content'])
|
| 332 |
|
| 333 |
+
# Try AI answer with better error handling
|
| 334 |
ai_answer = None
|
| 335 |
openrouter_key = os.environ.get("OPENROUTER_API_KEY")
|
| 336 |
|
|
|
|
| 339 |
prompt = f"Answer briefly: {query}\n\nContext: {context}\n\nAnswer (1 sentence):"
|
| 340 |
|
| 341 |
try:
|
| 342 |
+
st.write("DEBUG: Calling OpenRouter API...")
|
| 343 |
response = requests.post(
|
| 344 |
"https://openrouter.ai/api/v1/chat/completions",
|
| 345 |
headers={
|
| 346 |
"Authorization": f"Bearer {openrouter_key}",
|
| 347 |
+
"Content-Type": "application/json",
|
| 348 |
+
"HTTP-Referer": "https://huggingface.co/spaces",
|
| 349 |
+
"X-Title": "RAG Chatbot"
|
| 350 |
},
|
| 351 |
json={
|
| 352 |
"model": "openai/gpt-3.5-turbo",
|
|
|
|
| 357 |
timeout=10
|
| 358 |
)
|
| 359 |
|
| 360 |
+
st.write(f"DEBUG: API Status Code: {response.status_code}")
|
| 361 |
+
|
| 362 |
if response.status_code == 200:
|
| 363 |
ai_answer = response.json()['choices'][0]['message']['content'].strip()
|
| 364 |
+
st.write("DEBUG: AI answer received successfully")
|
| 365 |
+
else:
|
| 366 |
+
error_text = response.text
|
| 367 |
+
st.error(f"API Error {response.status_code}: {error_text}")
|
| 368 |
+
|
| 369 |
except Exception as e:
|
| 370 |
+
st.error(f"API Exception: {str(e)}")
|
| 371 |
+
else:
|
| 372 |
+
st.warning("No OpenRouter API key found in environment variables")
|
| 373 |
|
| 374 |
return {
|
| 375 |
'ai_answer': ai_answer,
|
|
|
|
| 379 |
'has_both': ai_answer is not None
|
| 380 |
}
|
| 381 |
|
| 382 |
+
def get_general_ai_response(query):
|
| 383 |
+
"""Get AI response for general questions not related to documents"""
|
| 384 |
+
openrouter_key = os.environ.get("OPENROUTER_API_KEY")
|
| 385 |
+
|
| 386 |
+
if not openrouter_key:
|
| 387 |
+
return "I can only answer questions about your uploaded documents. Please add an OpenRouter API key for general conversations."
|
| 388 |
+
|
| 389 |
+
try:
|
| 390 |
+
response = requests.post(
|
| 391 |
+
"https://openrouter.ai/api/v1/chat/completions",
|
| 392 |
+
headers={
|
| 393 |
+
"Authorization": f"Bearer {openrouter_key}",
|
| 394 |
+
"Content-Type": "application/json",
|
| 395 |
+
"HTTP-Referer": "https://huggingface.co/spaces",
|
| 396 |
+
"X-Title": "RAG Chatbot"
|
| 397 |
+
},
|
| 398 |
+
json={
|
| 399 |
+
"model": "openai/gpt-3.5-turbo",
|
| 400 |
+
"messages": [
|
| 401 |
+
{"role": "system", "content": "You are a helpful AI assistant. Be concise and friendly."},
|
| 402 |
+
{"role": "user", "content": query}
|
| 403 |
+
],
|
| 404 |
+
"max_tokens": 150,
|
| 405 |
+
"temperature": 0.7
|
| 406 |
+
},
|
| 407 |
+
timeout=15
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
if response.status_code == 200:
|
| 411 |
+
return response.json()['choices'][0]['message']['content'].strip()
|
| 412 |
+
else:
|
| 413 |
+
return f"Sorry, I encountered an error (Status: {response.status_code}). Please try again."
|
| 414 |
+
|
| 415 |
+
except Exception as e:
|
| 416 |
+
return f"Sorry, I encountered an error: {str(e)}"
|
| 417 |
|
| 418 |
def get_user_id():
|
| 419 |
"""Get unique ID for this user session"""
|
|
|
|
| 573 |
# Settings
|
| 574 |
st.header("βοΈ Settings")
|
| 575 |
|
| 576 |
+
# API Status with better checking
|
| 577 |
openrouter_key = os.environ.get("OPENROUTER_API_KEY")
|
| 578 |
if openrouter_key:
|
| 579 |
+
st.success("π’ OpenRouter API Connected")
|
| 580 |
+
# Quick API test
|
| 581 |
+
if st.button("Test API Connection", use_container_width=True):
|
| 582 |
+
try:
|
| 583 |
+
test_response = requests.post(
|
| 584 |
+
"https://openrouter.ai/api/v1/chat/completions",
|
| 585 |
+
headers={
|
| 586 |
+
"Authorization": f"Bearer {openrouter_key}",
|
| 587 |
+
"Content-Type": "application/json"
|
| 588 |
+
},
|
| 589 |
+
json={
|
| 590 |
+
"model": "openai/gpt-3.5-turbo",
|
| 591 |
+
"messages": [{"role": "user", "content": "test"}],
|
| 592 |
+
"max_tokens": 5
|
| 593 |
+
},
|
| 594 |
+
timeout=5
|
| 595 |
+
)
|
| 596 |
+
if test_response.status_code == 200:
|
| 597 |
+
st.success("β
API working correctly!")
|
| 598 |
+
else:
|
| 599 |
+
st.error(f"β API Error: {test_response.status_code}")
|
| 600 |
+
except Exception as e:
|
| 601 |
+
st.error(f"β API Test Failed: {str(e)}")
|
| 602 |
else:
|
| 603 |
+
st.error("β No OpenRouter API Key")
|
| 604 |
+
st.info("Add OPENROUTER_API_KEY in Hugging Face Space settings β Variables and secrets")
|
| 605 |
|
| 606 |
# RAG Settings
|
| 607 |
use_ai_enhancement = st.checkbox("Use AI Enhancement", value=bool(openrouter_key))
|
|
|
|
| 671 |
# Get RAG response
|
| 672 |
with st.chat_message("assistant"):
|
| 673 |
if rag_system and rag_system.model and rag_system.get_collection_count() > 0:
|
| 674 |
+
# Search documents first
|
| 675 |
search_results = rag_system.search(prompt, n_results=3)
|
| 676 |
|
| 677 |
+
# Check if we found relevant documents (confidence > 0.05)
|
| 678 |
+
if search_results and search_results[0]['similarity'] > 0.05:
|
| 679 |
+
# Generate document-based answer
|
| 680 |
result = rag_system.generate_answer(prompt, search_results)
|
| 681 |
|
| 682 |
# Display AI answer or extracted answer
|
|
|
|
| 685 |
st.markdown(f"π€ **AI Answer:** {answer_text}")
|
| 686 |
else:
|
| 687 |
answer_text = result['extracted_answer']
|
| 688 |
+
st.markdown(f"π **Document Answer:** {answer_text}")
|
| 689 |
|
| 690 |
# Show RAG info
|
| 691 |
if show_sources and result['sources']:
|
|
|
|
| 710 |
}
|
| 711 |
|
| 712 |
else:
|
| 713 |
+
# No relevant documents found - use general AI
|
| 714 |
+
st.info("No relevant documents found. Switching to general AI mode...")
|
| 715 |
+
general_response = get_general_ai_response(prompt)
|
| 716 |
+
st.markdown(f"π¬ **General AI:** {general_response}")
|
| 717 |
|
| 718 |
assistant_message = {
|
| 719 |
"role": "assistant",
|
| 720 |
+
"content": general_response,
|
| 721 |
+
"rag_info": {"sources": [], "confidence": 0, "mode": "general"}
|
| 722 |
}
|
| 723 |
|
| 724 |
else:
|
| 725 |
+
# RAG system not ready - use general AI
|
| 726 |
+
if rag_system and rag_system.get_collection_count() == 0:
|
| 727 |
+
st.warning("No documents indexed. Using general AI mode...")
|
| 728 |
+
else:
|
| 729 |
+
st.error("RAG system not ready. Using general AI mode...")
|
| 730 |
+
|
| 731 |
+
general_response = get_general_ai_response(prompt)
|
| 732 |
+
st.markdown(f"π¬ **General AI:** {general_response}")
|
| 733 |
|
| 734 |
assistant_message = {
|
| 735 |
"role": "assistant",
|
| 736 |
+
"content": general_response,
|
| 737 |
+
"rag_info": {"sources": [], "confidence": 0, "mode": "general"}
|
| 738 |
}
|
| 739 |
|
| 740 |
# Add assistant message to history
|