Spaces:
Sleeping
Sleeping
Download app.py from edichat/edi.chat.test: direct link, hf CLI and curl.
- Browser
- Download file 15.1 kB
-
https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/app.py
- Command line
-
hf download hf://spaces/edichat/edi.chat.test/app.py
-
curl -L -o app.py https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/app.py
15.1 kB
| #!/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() |