Spaces:
Sleeping
Sleeping
File size: 5,004 Bytes
7851df6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | 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; |