Spaces:
Sleeping

edi.chat.test / server-fixed.js
Claude Code Bot
Fix AI responses - implement direct Ollama integration with no fallbacks
7851df6
Raw History Blame Contribute Delete
4.13 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;
// Middleware
app.use(cors({ origin: '*', credentials: true }));
app.use(express.json({ limit: '10mb' }));
app.use(express.static('.'));
// Direct Ollama integration - NO FALLBACKS
async function callOllama(message) {
const ollamaUrl = process.env.LOCAL_AI_URL || 'http://localhost:11434';
const model = process.env.LOCAL_AI_MODEL || 'tinyllama';
const startTime = Date.now();
console.log(`πŸ€– Calling Ollama: ${ollamaUrl}/api/generate with model: ${model}`);
const response = await fetch(`${ollamaUrl}/api/generate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: model,
prompt: `You are a helpful University of Georgia (UGA) AI assistant. Provide accurate information about UGA and academic topics.
Question: ${message}
Answer:`,
stream: false,
options: {
temperature: 0.7,
top_p: 0.9,
top_k: 40
}
}),
timeout: 30000 // 30 second timeout
});
if (!response.ok) {
throw new Error(`Ollama API error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
const responseTime = Date.now() - startTime;
console.log(`βœ… Ollama response: ${data.response.length} chars in ${responseTime}ms`);
return {
content: data.response,
metadata: {
model: model,
responseTime: responseTime,
tokens: data.eval_count || 0
}
};
}
// Health check
app.get('/health', async (req, res) => {
try {
const ollamaUrl = process.env.LOCAL_AI_URL || 'http://localhost:11434';
const response = await fetch(`${ollamaUrl}/api/tags`, { timeout: 5000 });
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
ollama: response.ok ? 'connected' : 'error',
model: process.env.LOCAL_AI_MODEL || 'tinyllama'
});
} catch (error) {
res.status(500).json({
status: 'error',
error: error.message,
ollama: 'disconnected'
});
}
});
// REAL AI Chat endpoint - NO FALLBACKS
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(`πŸ“ Processing: "${message.substring(0, 100)}${message.length > 100 ? '...' : ''}"`);
// Call Ollama directly - this WILL throw error if Ollama is not working
const result = await callOllama(message.trim());
res.json({
success: true,
response: result.content,
metadata: result.metadata,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error('❌ AI Error:', error.message);
// Return error instead of fallback to ensure real AI is working
res.status(500).json({
success: false,
error: 'AI service unavailable',
details: error.message,
message: 'Please ensure Ollama is running with the correct model'
});
}
});
// Serve files
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.get('/dashboard', (req, res) => {
res.sendFile(path.join(__dirname, 'dashboard.html'));
});
app.get('/landing.html', (req, res) => {
res.sendFile(path.join(__dirname, 'landing.html'));
});
// Start server
app.listen(PORT, '0.0.0.0', () => {
console.log(`πŸš€ edi.chat REAL AI Server running on port ${PORT}`);
console.log(`πŸ€– Ollama URL: ${process.env.LOCAL_AI_URL || 'http://localhost:11434'}`);
console.log(`πŸ“¦ Model: ${process.env.LOCAL_AI_MODEL || 'tinyllama'}`);
console.log(`🌐 Dashboard: http://localhost:${PORT}/dashboard`);
console.log(`🏠 Landing: http://localhost:${PORT}/landing.html`);
console.log(`❀️ Health: http://localhost:${PORT}/health`);
console.log('');
console.log('⚠️ NO FALLBACK RESPONSES - Real AI only!');
});