Spaces:
Sleeping

edi.chat.test / app.py
edichat's picture
Upload 6 files
ec5955b verified
Raw History Blame Contribute Delete
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()