Spaces:
Sleeping

edi.chat.test / app.js
Claude Code Bot
Claude
Upgrade to real AI responses using local Ollama
8ad2676
Raw History Blame Contribute Delete
9.65 kB
const express = require('express');
// Optional dependencies - graceful fallback if not installed
let mongoose = null;
let createClient = null;
try {
mongoose = require('mongoose');
} catch (e) {
console.log('MongoDB not available - running without database');
}
try {
const redis = require('redis');
createClient = redis.createClient;
} catch (e) {
console.log('Redis not available - running without cache');
}
const app = express();
const PORT = process.env.PORT || 7860;
// Performance optimizations
app.set('trust proxy', 1);
app.disable('x-powered-by');
// Database connections
let dbConnected = false;
let redisClient = null;
// MongoDB connection with graceful fallback
async function connectDB() {
try {
if (mongoose && process.env.MONGODB_URI && !process.env.NO_DATABASE_BLOCKING) {
await mongoose.connect(process.env.MONGODB_URI, {
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 10000,
maxPoolSize: 5,
minPoolSize: 1,
});
dbConnected = true;
}
} catch (error) {
// Silent fail - continue without database
}
}
// Redis connection with graceful fallback
async function connectRedis() {
try {
if (createClient && process.env.REDIS_URL && !process.env.NO_DATABASE_BLOCKING) {
redisClient = createClient({
url: process.env.REDIS_URL,
socket: {
connectTimeout: 5000,
lazyConnect: true
}
});
await redisClient.connect();
}
} catch (error) {
redisClient = null;
}
}
// Optional connection initialization
connectDB().catch(() => {});
connectRedis().catch(() => {});
// Middleware
app.use(express.json({ limit: '1mb' }));
app.use(express.static('.'));
// Optimized request monitoring with memory management
let requestCount = 0;
const requestTimes = new Map();
app.use((req, res, next) => {
requestCount++;
const now = Date.now();
const clientIP = req.ip || 'unknown';
// Track requests per IP
if (!requestTimes.has(clientIP)) {
requestTimes.set(clientIP, []);
}
const clientRequests = requestTimes.get(clientIP);
clientRequests.push(now);
// Keep only last 20 requests per IP and cleanup old entries
if (clientRequests.length > 20) {
clientRequests.shift();
}
// Cleanup old entries (older than 5 minutes)
const cutoff = now - 300000;
for (const [ip, times] of requestTimes.entries()) {
const filtered = times.filter(time => time > cutoff);
if (filtered.length === 0) {
requestTimes.delete(ip);
} else {
requestTimes.set(ip, filtered);
}
}
// Check for rapid requests (more than 15 requests per IP in 10 seconds)
const recentRequests = clientRequests.filter(time => now - time < 10000);
if (recentRequests.length > 15) {
console.log(`⚠️ RAPID REQUESTS from ${clientIP}: ${recentRequests.length} requests in 10 seconds`);
}
next();
});
// Optimized AI response generation with timeout and retry
async function generateAIResponse(message) {
try {
const ollamaUrl = process.env.LOCAL_AI_URL || 'http://localhost:11434';
const ollamaModel = process.env.LOCAL_AI_MODEL || 'llama3:8b';
// Add timeout to prevent hanging requests
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 15000); // 15 second timeout
const response = await fetch(`${ollamaUrl}/api/generate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: ollamaModel,
prompt: `You are UGA Assistant, an AI chatbot for the University of Georgia. Be helpful, friendly, and knowledgeable about UGA. Keep responses concise and focused on UGA-related topics.
User: ${message}
Assistant:`,
stream: false
}),
signal: controller.signal
});
clearTimeout(timeoutId);
if (response.ok) {
const data = await response.json();
return `πŸŽ“ ${data.response}`;
}
} catch (error) {
// Ollama failed, use fallback responses
}
// Fallback UGA-specific responses
const ugaResponses = {
'hello': 'Hello! Welcome to edi.chat, your UGA AI Assistant! How can I help you with UGA today?',
'courses': 'I can help you with UGA course information! What specific courses or majors are you interested in?',
'dining': 'UGA has many great dining options! Are you looking for information about meal plans, dining halls, or specific restaurants on campus?',
'housing': 'UGA offers various housing options for students. Are you interested in residence halls, apartments, or Greek life housing?',
'schedule': 'I can help with class schedules and registration! What do you need to know about UGA course scheduling?',
'campus': 'The UGA campus in Athens is beautiful! Are you looking for directions, campus tours, or information about specific buildings?',
'athletics': 'Go Dawgs! Are you interested in UGA football, basketball, or other Bulldogs athletics?',
'library': 'UGA has excellent library resources! The Main Library and Miller Learning Center are great places to study.',
'parking': 'UGA parking can be tricky! Are you looking for information about parking passes, zones, or alternative transportation?',
'help': 'I\'m here to help with all things UGA! You can ask me about courses, dining, housing, campus life, athletics, and more.'
};
const lowerMessage = message.toLowerCase();
for (const [keyword, response] of Object.entries(ugaResponses)) {
if (lowerMessage.includes(keyword)) {
return `πŸŽ“ ${response}`;
}
}
return `πŸŽ“ Thanks for your question about UGA! I'm your local AI assistant and I'm here to help with university information, course guidance, campus resources, and more. Could you be more specific about what you'd like to know?`;
}
// Optimized rate limiting with sliding window
const rateLimit = new Map();
// Chat API with optimized AI
app.post('/api/chat', async (req, res) => {
const { message } = req.body;
const clientIP = req.ip || req.connection.remoteAddress || 'unknown';
// Optimized rate limiting - sliding window (3 requests per 10 seconds)
const now = Date.now();
if (!rateLimit.has(clientIP)) {
rateLimit.set(clientIP, []);
}
const requests = rateLimit.get(clientIP);
// Remove requests older than 10 seconds
const filtered = requests.filter(time => now - time < 10000);
if (filtered.length >= 3) {
return res.status(429).json({
error: 'Rate limit exceeded',
retryAfter: Math.ceil((filtered[0] + 10000 - now) / 1000)
});
}
filtered.push(now);
rateLimit.set(clientIP, filtered);
// Enhanced input validation
if (!message || typeof message !== 'string' || message.length > 500 || message.trim().length === 0) {
return res.status(400).json({ error: 'Invalid message format or length' });
}
try {
// Generate AI response
const aiResponse = await generateAIResponse(message);
// Store in MongoDB if connected
if (dbConnected && mongoose) {
const Chat = mongoose.model('Chat', {
message: String,
response: String,
timestamp: { type: Date, default: Date.now }
});
await new Chat({ message, response: aiResponse }).save();
}
// Cache in Redis if connected
if (redisClient) {
await redisClient.setEx(`chat:${Date.now()}`, 3600, JSON.stringify({ message, response: aiResponse }));
}
res.json({
success: true,
response: aiResponse,
aiType: 'ollama',
dbStatus: dbConnected ? 'connected' : 'disconnected',
cacheStatus: redisClient ? 'connected' : 'disconnected'
});
} catch (error) {
res.json({
success: true,
response: `πŸŽ“ I'm your UGA Assistant! I'm experiencing a technical issue but I'm still here to help with your UGA questions.`,
dbStatus: 'error'
});
}
});
// Health endpoint
app.get('/health', (req, res) => {
res.json({
status: 'OK',
database: dbConnected ? 'connected' : 'disconnected',
cache: redisClient ? 'connected' : 'disconnected',
ai: 'ollama'
});
});
// Debug endpoint to check request patterns
app.get('/debug/requests', (req, res) => {
const now = Date.now();
let total10Sec = 0;
let total60Sec = 0;
const ipStats = {};
// Aggregate statistics from all IPs
for (const [ip, times] of requestTimes.entries()) {
const recent10 = times.filter(time => now - time < 10000).length;
const recent60 = times.filter(time => now - time < 60000).length;
total10Sec += recent10;
total60Sec += recent60;
if (recent10 > 0 || recent60 > 0) {
ipStats[ip] = { last10Sec: recent10, last60Sec: recent60 };
}
}
res.json({
serverUptime: Math.floor(process.uptime()),
totalRequests: requestCount,
requestsLast10Sec: total10Sec,
requestsLast60Sec: total60Sec,
averagePerSecond: Math.round(total60Sec / 60 * 10) / 10,
activeIPs: Object.keys(ipStats).length,
topActiveIPs: Object.entries(ipStats)
.sort(([,a], [,b]) => b.last60Sec - a.last60Sec)
.slice(0, 5)
.map(([ip, stats]) => ({ ip: ip === '::1' ? 'localhost' : ip, ...stats }))
});
});
// Serve main page
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// Start server with logging
app.listen(PORT, '0.0.0.0', () => {
console.log(`πŸŽ“ UGA AI Assistant running on port ${PORT}`);
console.log(` Dashboard: http://localhost:${PORT}`);
console.log(` Health Check: http://localhost:${PORT}/health`);
console.log(` Using Ollama at: ${process.env.LOCAL_AI_URL || 'http://localhost:11434'}`);
});
module.exports = app;