#!/usr/bin/env python3 import gradio as gr import subprocess import threading import time import os import signal import sys import requests import json # UGA edi.chat AI System - Enhanced Hugging Face Spaces Deployment print("🎓 Starting UGA edi.chat - Enhanced AI Assistant with Real-Time Search") # Global variable to track server node_process = None def start_node_server(): """Start enhanced Node.js server with all improvements""" global node_process try: print("🚀 Starting enhanced UGA edi.chat AI server...") # Set environment variables for enhanced UGA configuration env = os.environ.copy() env.update({ 'PORT': '3001', # Use different port to avoid conflicts 'NODE_ENV': 'production', 'USE_HUGGINGFACE': 'true', 'HUGGINGFACE_API_KEY': os.environ.get('HUGGINGFACE_API_KEY', ''), 'HUGGINGFACE_MODEL': 'meta-llama/Llama-3.1-8B-Instruct', 'HUGGINGFACE_MAX_TOKENS': '1024', # Increased for better responses 'HUGGINGFACE_TEMPERATURE': '0.7', 'HUGGINGFACE_TOP_P': '0.9', 'ENABLE_WEB_SEARCH': 'true', 'GOOGLE_SEARCH_API_KEY': os.environ.get('GOOGLE_SEARCH_API_KEY', ''), 'GOOGLE_SEARCH_ENGINE_ID': os.environ.get('GOOGLE_SEARCH_ENGINE_ID', ''), 'WEB_SEARCH_CACHE_TTL': '1800', 'CORS_ORIGIN': '*' }) node_process = subprocess.Popen( ["node", "server.js"], cwd="/app" if os.path.exists("/app") else ".", env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, universal_newlines=True ) # Give server time to start time.sleep(8) # Increased startup time print("✅ Enhanced UGA edi.chat AI server started with:") print(" 🔍 Enhanced Google Search Integration") print(" đŸŽ¯ Improved Agent Routing") print(" 📊 Detailed Information Extraction") print(" 🎓 Comprehensive UGA Knowledge Base") except Exception as e: print(f"❌ Error starting enhanced UGA server: {e}") def create_chat_interface(): """Create enhanced UGA AI chat interface with improved features""" def respond(message, history, agent_type): if not message.strip(): return history, "" try: # Call the enhanced Node.js backend API response = requests.post( "http://localhost:3001/api/chat", json={ "message": message, "agentType": agent_type }, timeout=45 # Increased timeout for search operations ) if response.status_code == 200: data = response.json() bot_response = data['response']['content'] metadata = data['response']['metadata'] # Enhanced response formatting with search info agent_info = f"🎓 **{metadata['agentName']}** {metadata['agentEmoji']}" # Add search indicator if search was used search_indicator = "" if metadata.get('searchUsed'): search_provider = metadata.get('searchProvider', 'web') cache_status = "cached" if metadata.get('searchFromCache') else "live" search_indicator = f" 🔍 *({search_provider} search - {cache_status})*" full_response = f"{agent_info}{search_indicator}\n\n{bot_response}" # Add response time info if metadata.get('responseTime'): response_time = metadata['responseTime'] / 1000 # Convert to seconds full_response += f"\n\n*Response time: {response_time:.1f}s*" else: full_response = f"❌ Error: Unable to get AI response (Status: {response.status_code})" except requests.exceptions.Timeout: full_response = "âąī¸ Request timed out. The enhanced AI is processing your request, please try again." except requests.exceptions.ConnectionError: full_response = "🔌 Connection error. The enhanced AI service is starting up, please wait a moment and try again." except Exception as e: full_response = f"❌ Error connecting to enhanced AI service: {str(e)}" history = history or [] history.append((message, full_response)) return history, "" with gr.Blocks( title="edi.chat - Enhanced UGA AI Assistant", theme=gr.themes.Soft(primary_hue="red"), css=""" .gradio-container { max-width: 900px; margin: auto; } .chat-message { padding: 12px; margin: 8px 0; border-radius: 8px; } .search-indicator { font-size: 0.9em; color: #666; font-style: italic; } .agent-info { font-weight: bold; color: #d32f2f; } .response-stats { font-size: 0.8em; color: #888; margin-top: 8px; } """ ) as demo: gr.Markdown(""" # 🎓 edi.chat - Enhanced UGA AI Assistant **University of Georgia Multi-Agent AI System with Real-Time Search** ✨ *Now with Enhanced Google Search Integration & Detailed Information Extraction* 🔍 **New Features**: Specific dining hours, real-time campus information, and improved agent routing """) with gr.Tab("đŸ’Ŧ Enhanced Chat"): # Enhanced agent selector with more detailed descriptions agent_selector = gr.Dropdown( choices=[ ("🎓 Academic Advisor - Courses, Degrees, Registration", "academic"), ("đŸ›ī¸ Student Life Guide - Dining, Housing, Events, Organizations", "student_life"), ("🐕 Athletics Assistant - Sports, Games, Tickets, Team Info", "athletics"), ("đŸŽ¯ General Helper - Campus Info, Admissions, Directions", "general"), ("🤖 Auto-Select Agent - AI Chooses Best Agent", "auto") ], value="auto", label="đŸŽ¯ Select UGA AI Agent", info="Choose specialized agent or let AI auto-select based on your question" ) # Enhanced chatbot with better styling chatbot = gr.Chatbot( [], elem_id="enhanced-chatbot", height=550, show_label=False, avatar_images=("👤", "🎓"), bubble_full_width=False, show_copy_button=True ) # Enhanced input section with gr.Row(): msg = gr.Textbox( placeholder="Ask me anything about UGA (dining hours, course info, game schedules, etc.)...", container=False, scale=4 ) submit_btn = gr.Button("🚀 Send", variant="primary", scale=1) clear_btn = gr.Button("đŸ—‘ī¸ Clear", scale=1) # Sample questions for easy testing with gr.Row(): gr.Examples( examples=[ "What are the dining hours at UGA?", "When is the next football game?", "What courses do I need for computer science?", "How do I apply to UGA?", "What student organizations are available?" ], inputs=msg, label="🔍 Try these sample questions:" ) # Event handlers with enhanced features msg.submit(respond, [msg, chatbot, agent_selector], [chatbot, msg]) submit_btn.click(respond, [msg, chatbot, agent_selector], [chatbot, msg]) clear_btn.click(lambda: ([], ""), outputs=[chatbot, msg]) with gr.Tab("â„šī¸ Enhanced Features"): gr.Markdown(""" ### 🚀 Enhanced UGA edi.chat Features **Latest Improvements:** - ✅ **Enhanced Search Integration**: Now provides specific dining hours, locations, and detailed information - ✅ **Improved Agent Routing**: Fixed routing issues for better question handling - ✅ **Real-Time Information**: Live Google Search with intelligent result analysis - ✅ **Detailed Responses**: Extracts specific times, dates, contact info, and actionable details **🎓 Specialized UGA Agents:** - **🎓 Academic Advisor**: Course planning, degree requirements, registration, graduation requirements, GPA info - **đŸ›ī¸ Student Life Guide**: **Enhanced with specific dining hours**, housing info, organizations, campus events, UGA traditions - **🐕 Athletics Assistant**: Bulldogs sports schedules, game tickets, team information, SEC standings - **đŸŽ¯ General Helper**: Campus directions, admissions guidance, contact information, general UGA questions **🔍 Enhanced Search Capabilities:** - **Specific Information Extraction**: Gets exact hours, locations, phone numbers, dates - **Multiple Search Providers**: Google Custom Search, Bing, SearXNG fallback - **Intelligent Query Enhancement**: Adds targeted keywords for better results - **Real-time Cache Management**: Fresh information with performance optimization - **Source Verification**: Prioritizes official UGA websites (uga.edu, georgiadogs.com) **🧠 Advanced AI Technology:** - **Enhanced Prompting**: Detailed instructions for extracting specific information - **Hugging Face Inference API**: Llama 3.1 8B Instruct with optimized settings - **Search Result Analysis**: AI analyzes and synthesizes multiple sources - **Response Time Tracking**: Performance monitoring and optimization **📊 Enhanced Knowledge Base:** - **Comprehensive UGA Information**: All 17 colleges, 170+ academic programs - **Real-Time Campus Data**: Current dining hours, event schedules, contact information - **Athens Community Info**: Local attractions, transportation, area services - **Student Resources**: Financial aid, housing options, Greek life, student organizations **đŸŽ¯ New Response Features:** - **Search Indicators**: Shows when real-time search was used (live vs cached) - **Response Time Display**: Transparency in processing time - **Source Attribution**: Links to official UGA sources - **Actionable Information**: Phone numbers, websites, specific next steps Built with â¤ī¸ for the UGA community. **Go Dawgs!** 🐕 """) with gr.Tab("🔧 Enhanced System Status"): gr.Markdown("### 🚀 Enhanced System Health Monitor") status_btn = gr.Button("🔍 Check Enhanced System Status", variant="primary") status_output = gr.Textbox( value="Click 'Check Enhanced System Status' to verify all enhanced features", lines=15, label="Enhanced Server Status", interactive=False ) def check_enhanced_status(): try: # Try to ping the enhanced backend backend_status = "đŸŸĸ Online" search_status = "đŸŸĸ Google Search API Configured" ai_status = "đŸŸĸ Hugging Face Llama 3.1 8B" try: response = requests.get("http://localhost:3001/health", timeout=5) if response.status_code == 200: backend_status = "đŸŸĸ Enhanced Backend Online" except: backend_status = "🟡 Backend Starting..." status_info = f""" 🚀 Enhanced UGA edi.chat System Status ═════════════════════════════════════════ đŸ–Ĩī¸ Frontend: Enhanced Gradio Interface (Stable) 📡 Backend: {backend_status} 🔍 Search: {search_status} 🤖 AI Engine: {ai_status} 🔧 Environment: {os.environ.get('NODE_ENV', 'production')} đŸŽ¯ Enhanced Features Status: ✅ Smart Agent Routing ✅ Enhanced Search Query Processing ✅ Detailed Information Extraction ✅ Real-time Google Search Integration ✅ UGA Knowledge Base Integration ✅ Response Time Optimization 🎓 UGA Agents Status: 🎓 Academic Advisor: Ready đŸ›ī¸ Student Life Guide: Enhanced with dining hours 🐕 Athletics Assistant: Ready with game schedules đŸŽ¯ General Helper: Ready with campus info ⏰ Status Check: {time.strftime('%Y-%m-%d %H:%M:%S UTC')} 📍 Platform: Hugging Face Spaces (Enhanced) 🔗 API Endpoints: /api/chat, /api/search 💾 Cache: Performance optimized ✅ Enhanced system operational and ready for detailed UGA queries! 🐕 Go Dawgs! Your enhanced UGA AI assistant is ready to help with: â€ĸ Specific dining hours and locations â€ĸ Real-time campus information â€ĸ Course and academic guidance â€ĸ Athletics schedules and tickets â€ĸ Student life and events """ return status_info.strip() except Exception as e: return f"❌ Error checking enhanced status: {str(e)}" status_btn.click(check_enhanced_status, outputs=status_output) return demo # Cleanup function def cleanup(): global node_process if node_process: try: node_process.terminate() node_process.wait(timeout=5) except: try: node_process.kill() except: pass print("🛑 Node.js server stopped") # Signal handlers for graceful shutdown def signal_handler(signum, frame): print("🛑 Received shutdown signal") cleanup() sys.exit(0) signal.signal(signal.SIGTERM, signal_handler) signal.signal(signal.SIGINT, signal_handler) # Start background server threading.Thread(target=start_node_server, daemon=True).start() # Create and launch enhanced app if __name__ == "__main__": demo = create_chat_interface() try: print("🎓 Launching Enhanced UGA edi.chat Interface...") demo.launch( server_name="0.0.0.0", server_port=7860, share=True, # Enable sharing for Hugging Face Spaces show_error=True, quiet=False, favicon_path=None, ssl_verify=False ) except KeyboardInterrupt: print("🛑 Shutting down Enhanced UGA edi.chat...") cleanup() except Exception as e: print(f"❌ Enhanced launch error: {e}") cleanup()