Spaces:
Sleeping

File size: 4,128 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
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!');
});