""" Gradio UI for UPB RAG Career Exploration Assistant Optimized for HuggingFace Spaces with better error handling """ import os import gradio as gr from pathlib import Path import sys from dotenv import load_dotenv # Load environment variables from .env file (for local development) # HuggingFace Spaces will use Secrets instead load_dotenv() # Validate required environment variables REQUIRED_ENV_VARS = [ "AZURE_OPENAI_API_KEY", "AZURE_OPENAI_ENDPOINT", "AZURE_OPENAI_DEPLOYMENT_NAME", "AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME", ] missing_vars = [var for var in REQUIRED_ENV_VARS if not os.getenv(var)] if missing_vars: error_msg = f""" ❌ Missing required environment variables: {', '.join(missing_vars)} Please configure these in HuggingFace Space Settings → Secrets: - AZURE_OPENAI_API_KEY - AZURE_OPENAI_ENDPOINT - AZURE_OPENAI_DEPLOYMENT_NAME - AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME - AZURE_OPENAI_API_VERSION (optional, defaults to 2024-02-15-preview) """ print(error_msg) # Create a simple error UI def error_interface(): with gr.Blocks() as demo: gr.Markdown("# ⚠️ Configuration Error") gr.Markdown(error_msg) gr.Markdown(""" ## How to fix: 1. Go to your Space settings: https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE/settings 2. Click on "Secrets" in the left sidebar 3. Add each required environment variable as a new secret 4. The Space will automatically rebuild """) return demo demo = error_interface() else: # Add src to path sys.path.insert(0, str(Path(__file__).parent / "src")) try: from setup_retrieval import setup_retrieval_system from rag.chain import UPBRAGChain # Initialize RAG system print("🚀 Initializing UPB RAG System...") print(f"📁 Current directory: {os.getcwd()}") print(f"🔑 Azure Endpoint: {os.getenv('AZURE_OPENAI_ENDPOINT')[:30]}...") retriever, vectorstore_manager, chunks = setup_retrieval_system() rag_chain = UPBRAGChain(retriever, retrieval_method="hybrid") print(f"✅ System ready! Loaded {len(chunks)} chunks from {len(set(doc.metadata.get('source') for doc in chunks if hasattr(doc, 'metadata')))} documents") except Exception as e: import traceback error_msg = f""" ❌ Error initializing RAG system: {str(e)} Full traceback: {traceback.format_exc()} """ print(error_msg) def error_interface(): with gr.Blocks() as demo: gr.Markdown("# ⚠️ Initialization Error") gr.Markdown(f"```\n{error_msg}\n```") return demo demo = error_interface() raise # Custom CSS for better UI custom_css = """ .header { text-align: center; padding: 20px; background: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%); color: white; border-radius: 10px; margin-bottom: 20px; } .header h1 { margin: 0; font-size: 2.5em; font-weight: bold; } .header p { margin: 10px 0 0 0; font-size: 1.2em; opacity: 0.9; } .disclaimer { background-color: #fef3c7; border-left: 4px solid #f59e0b; padding: 15px; margin: 15px 0; border-radius: 5px; font-size: 0.9em; } .footer { text-align: center; padding: 20px; color: #6b7280; font-size: 0.9em; } .chat-message { padding: 10px; border-radius: 8px; margin: 5px 0; } .source-box { background-color: #f3f4f6; border-left: 3px solid #3b82f6; padding: 10px; margin: 10px 0; border-radius: 5px; font-size: 0.85em; } """ def format_sources(sources): """Format source citations nicely""" if not sources: return "" sources_text = "\n\n---\n\n### 📚 Fuentes consultadas:\n\n" seen = set() for source in sources: source_key = (source.get('category', ''), source.get('source', '')) if source_key not in seen: seen.add(source_key) category = source.get('category', 'general').title() source_name = source.get('source', 'N/A') sources_text += f"- **{category}**: `{source_name}`\n" return sources_text def chat_with_upb(message, history, include_sources): """ Main chat function for Gradio interface Args: message: User's message history: Chat history (list of [user_msg, bot_msg] pairs) include_sources: Boolean to show source citations Returns: Updated chat history """ if not message or not message.strip(): return history try: # Get response from RAG chain response = rag_chain.invoke(message, include_sources=include_sources) # Format answer answer = response['answer'] # Add sources if requested if include_sources and response.get('sources'): answer += format_sources(response['sources']) # Update history history.append([message, answer]) return history except Exception as e: import traceback error_msg = f"⚠️ Lo siento, ocurrió un error: {str(e)}\n\n```\n{traceback.format_exc()}\n```\n\nPor favor, intenta reformular tu pregunta." history.append([message, error_msg]) return history def clear_conversation(): """Clear chat history""" rag_chain.clear_history() return [] def get_example_questions(): """Return example questions for quick start""" return [ ["¿Qué ingenierías ofrece la UPB?"], ["¿Cuáles programas tienen acreditación ABET?"], ["Cuéntame sobre Ingeniería de Sistemas"], ["¿Qué becas están disponibles?"], ["¿Cómo puedo contactar a la UPB?"], ["¿Qué es la Ingeniería en Ciencia de Datos?"], ] # Create Gradio interface with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo: # Header gr.HTML("""
Asistente Virtual para Exploración de Carreras - Universidad Pontificia Bolivariana