const express = require('express'); const cors = require('cors'); const path = require('path'); require('dotenv').config(); const app = express(); const PORT = process.env.PORT || 7860; // Basic middleware app.use(cors({ origin: process.env.CORS_ORIGIN || '*', credentials: true })); app.use(express.json({ limit: '10mb' })); app.use(express.static('.')); // Health check endpoint app.get('/health', async (req, res) => { const health = { status: 'healthy', timestamp: new Date().toISOString(), uptime: process.uptime(), services: { ollama: 'checking...' } }; // Check Ollama health try { const ollamaUrl = process.env.LOCAL_AI_URL || 'http://localhost:11434'; const response = await fetch(`${ollamaUrl}/api/tags`, { method: 'GET', timeout: 3000 }); health.services.ollama = response.ok ? 'connected' : 'error'; } catch (error) { health.services.ollama = 'disconnected'; } res.json(health); }); // Simple chat API endpoint app.post('/api/chat', async (req, res) => { try { const { message } = req.body; if (!message || typeof message !== 'string' || message.trim().length === 0) { return res.status(400).json({ success: false, error: 'Valid message is required' }); } console.log(`๐Ÿ“ Chat request: "${message.substring(0, 100)}${message.length > 100 ? '...' : ''}"`); // Import AI service here to avoid loading issues const AIService = require('./backend/src/services/aiService'); // Generate AI response using Ollama const result = await AIService.generateLocalResponse([ { role: 'user', content: message.trim() } ]); console.log(`โœ… AI response generated: ${result.content.length} chars, ${result.metadata.responseTime}ms`); res.json({ success: true, response: result.content, metadata: result.metadata }); } catch (error) { console.error('โŒ Chat API error:', error.message); res.status(500).json({ success: false, error: 'Internal server error', fallback: '๐ŸŽ“ I apologize, but I\'m experiencing technical difficulties. Please ensure Ollama is running with a UGA-compatible model.', details: error.message }); } }); // Serve main chat interface app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'index.html')); }); // Test endpoint for multiple AI responses app.post('/api/test', async (req, res) => { try { const testQuestions = [ 'What is UGA?', 'Tell me about UGA traditions', 'How do I register for classes at UGA?', 'What are UGA\'s colors and mascot?' ]; console.log('๐Ÿงช Running AI test suite...'); const results = []; const AIService = require('./backend/src/services/aiService'); for (const question of testQuestions) { console.log(` Testing: "${question}"`); const startTime = Date.now(); try { const result = await AIService.generateLocalResponse([ { role: 'user', content: question } ]); results.push({ question, success: true, responseLength: result.content.length, responseTime: Date.now() - startTime, preview: result.content.substring(0, 100) + '...', metadata: result.metadata }); } catch (error) { results.push({ question, success: false, error: error.message, responseTime: Date.now() - startTime }); } } console.log(`โœ… Test suite completed: ${results.filter(r => r.success).length}/${results.length} passed`); res.json({ success: true, totalTests: results.length, passed: results.filter(r => r.success).length, results }); } catch (error) { console.error('โŒ Test suite error:', error); res.status(500).json({ success: false, error: error.message }); } }); // Error handling middleware app.use((err, req, res, next) => { console.error('โŒ Unhandled error:', err); res.status(500).json({ success: false, error: 'Internal server error' }); }); // 404 handler app.use((req, res) => { res.status(404).json({ success: false, error: 'Endpoint not found' }); }); // Start server app.listen(PORT, '0.0.0.0', () => { console.log(`๐Ÿš€ edi.chat Clean Server running on port ${PORT}`); console.log(`๐Ÿค– Using Ollama at ${process.env.LOCAL_AI_URL || 'http://localhost:11434'}`); console.log(`๐Ÿ“ฆ Model: ${process.env.LOCAL_AI_MODEL || 'llama3.2:latest'}`); console.log(`๐ŸŒ Environment: ${process.env.NODE_ENV || 'development'}`); console.log(`\n๐Ÿ“ Available endpoints:`); console.log(` ๐Ÿ  Main: http://localhost:${PORT}/`); console.log(` ๐Ÿ’ฌ Chat: POST http://localhost:${PORT}/api/chat`); console.log(` ๐Ÿงช Test: POST http://localhost:${PORT}/api/test`); console.log(` โค๏ธ Health: GET http://localhost:${PORT}/health`); }); module.exports = app;