Spaces:
Sleeping

edi.chat.test / server-clean.js
Claude Code Bot
Fix AI responses - implement direct Ollama integration with no fallbacks
7851df6
Raw History Blame Contribute Delete
5 kB
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;