File size: 11,770 Bytes
81b66b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import { Response, NextFunction } from 'express';
import ChatMessage from '../models/ChatMessage';
import { AuthRequest } from '../types';

// Hugging Face Inference API configuration
const HF_API_KEY = process.env.HF_API_KEY || '';
const HF_MODEL = 'mistralai/Mistral-7B-Instruct-v0.3';
const HF_API_URL = `https://api-inference.huggingface.co/models/${HF_MODEL}`;

// System prompt for the learning assistant
const SYSTEM_PROMPT = `You are an expert AI Learning Tutor for a web development learning platform. Your role:

1. Help students learn JavaScript, React, TypeScript, Node.js, CSS, APIs, and MongoDB
2. Provide clear, concise explanations with code examples when relevant
3. Use markdown formatting: **bold**, \`inline code\`, and fenced code blocks
4. Break complex topics into digestible steps
5. Encourage the student and suggest next steps
6. If you don't know something, say so honestly
7. Keep responses focused and under 500 words unless the topic requires more detail

Always be helpful, patient, and encouraging.`;

// Call Hugging Face Inference API
const callHuggingFace = async (
  userMessage: string,
  conversationHistory: { role: string; content: string }[]
): Promise<string> => {
  if (!HF_API_KEY || HF_API_KEY === 'your-huggingface-api-key-here') {
    throw new Error('HF_API_KEY_NOT_SET');
  }

  // Build the prompt in Mistral instruction format
  const messages = [
    { role: 'system', content: SYSTEM_PROMPT },
    ...conversationHistory.slice(-6), // Last 6 messages for context
    { role: 'user', content: userMessage },
  ];

  // Format for Mistral instruct
  let prompt = '';
  for (const msg of messages) {
    if (msg.role === 'system') {
      prompt += `<s>[INST] ${msg.content} [/INST]</s>`;
    } else if (msg.role === 'user') {
      prompt += `[INST] ${msg.content} [/INST]`;
    } else {
      prompt += `${msg.content}</s>`;
    }
  }

  const response = await fetch(HF_API_URL, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${HF_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      inputs: prompt,
      parameters: {
        max_new_tokens: 1024,
        temperature: 0.7,
        top_p: 0.95,
        repetition_penalty: 1.15,
        return_full_text: false,
      },
    }),
  });

  if (!response.ok) {
    const errorBody = await response.text();
    console.error(`HuggingFace API error (${response.status}):`, errorBody);

    if (response.status === 503) {
      throw new Error('MODEL_LOADING');
    }
    throw new Error(`HF_API_ERROR_${response.status}`);
  }

  const data = await response.json();

  if (Array.isArray(data) && data.length > 0 && data[0].generated_text) {
    return data[0].generated_text.trim();
  }

  throw new Error('UNEXPECTED_RESPONSE');
};

// Fallback responses when HF API is unavailable
const generateFallbackResponse = (userInput: string): string => {
  const lower = userInput.toLowerCase();

  if (lower.includes('react') || lower.includes('hook') || lower.includes('component')) {
    return `Great question about React! Here's a quick overview:

**React** is a JavaScript library for building user interfaces using components.

**Key Concepts:**
- **Components** – Reusable UI building blocks
- **Props** – Data passed from parent to child
- **State** – Local data that triggers re-renders
- **Hooks** – \`useState\`, \`useEffect\`, \`useContext\` for functional components

\`\`\`javascript
function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}
\`\`\`

πŸ’‘ *For deeper AI-powered answers, add your Hugging Face API key in the server settings.*`;
  }

  if (lower.includes('javascript') || lower.includes('js') || lower.includes('async') || lower.includes('promise')) {
    return `Here's a quick JavaScript overview:

**Modern JavaScript (ES6+) essentials:**
- \`const\`/\`let\` for variable declarations
- Arrow functions: \`const fn = (x) => x * 2\`
- Destructuring: \`const { name, age } = user\`
- Spread operator: \`[...arr1, ...arr2]\`
- Template literals: \`\`Hello \${name}\`\`

**Async/Await:**
\`\`\`javascript
async function fetchData() {
  try {
    const res = await fetch('/api/data');
    const data = await res.json();
    return data;
  } catch (error) {
    console.error('Failed:', error);
  }
}
\`\`\`

πŸ’‘ *For deeper AI-powered answers, add your Hugging Face API key in the server settings.*`;
  }

  if (lower.includes('typescript') || lower.includes('type') || lower.includes('interface')) {
    return `Here's a TypeScript primer:

**TypeScript** adds static types to JavaScript for better developer experience.

\`\`\`typescript
interface User {
  name: string;
  age: number;
  email?: string; // optional
}

function greet(user: User): string {
  return \`Hello, \${user.name}!\`;
}
\`\`\`

**Key Features:**
- **Interfaces** – Define object shapes
- **Generics** – Reusable typed functions: \`Array<T>\`
- **Union types** – \`string | number\`
- **Type guards** – Runtime type checking

πŸ’‘ *For deeper AI-powered answers, add your Hugging Face API key in the server settings.*`;
  }

  if (lower.includes('node') || lower.includes('express') || lower.includes('api') || lower.includes('backend')) {
    return `Here's a Node.js & Express overview:

**Express.js** is the most popular Node.js web framework.

\`\`\`javascript
const express = require('express');
const app = express();

app.use(express.json());

app.get('/api/users', async (req, res) => {
  const users = await User.find();
  res.json({ success: true, data: users });
});

app.listen(3000, () => console.log('Server running on port 3000'));
\`\`\`

**Key Concepts:**
- **Routing** – Define endpoints (GET, POST, PUT, DELETE)
- **Middleware** – Functions that process requests
- **Error handling** – Centralized error middleware

πŸ’‘ *For deeper AI-powered answers, add your Hugging Face API key in the server settings.*`;
  }

  if (lower.includes('css') || lower.includes('flex') || lower.includes('grid') || lower.includes('style')) {
    return `Here's a CSS layout guide:

**Flexbox** – 1D layouts (row or column):
\`\`\`css
.container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
}
\`\`\`

**CSS Grid** – 2D layouts (rows AND columns):
\`\`\`css
.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1.5rem;
}
\`\`\`

**Pro Tips:**
- Use \`rem\` for spacing, \`em\` for component-local sizing
- Mobile-first: write base styles, then \`@media (min-width: ...)\`
- CSS variables: \`--color-primary: #135bec\`

πŸ’‘ *For deeper AI-powered answers, add your Hugging Face API key in the server settings.*`;
  }

  return `I'd be happy to help you learn! Here are topics I can assist with:

- **React** – Components, hooks, state management, routing
- **JavaScript** – ES6+, async/await, closures, DOM
- **TypeScript** – Types, interfaces, generics
- **Node.js** – Express, REST APIs, middleware
- **CSS** – Flexbox, Grid, responsive design
- **MongoDB** – Schema design, queries, aggregation

Try asking something specific like:
> "Explain useEffect in React"
> "How do async/await work?"
> "What is TypeScript generics?"

πŸ’‘ *For deeper AI-powered answers, add your Hugging Face API key in the server settings.*`;
};

// @desc    Send message to AI assistant
// @route   POST /api/assistant/chat
// @access  Private
export const sendMessage = async (
  req: AuthRequest,
  res: Response,
  next: NextFunction
): Promise<void> => {
  try {
    const { content } = req.body;

    if (!content) {
      res.status(400).json({
        success: false,
        error: 'Message content is required',
      });
      return;
    }

    // Save user message
    const userMessage = await ChatMessage.create({
      userId: req.user?._id,
      type: 'user',
      content,
    });

    let aiContent: string;
    let source: 'huggingface' | 'fallback' = 'fallback';

    try {
      // Get recent conversation history for context
      const recentMessages = await ChatMessage.find({ userId: req.user?._id })
        .sort({ createdAt: -1 })
        .limit(6);

      const conversationHistory = recentMessages
        .reverse()
        .map(msg => ({
          role: msg.type === 'user' ? 'user' : 'assistant',
          content: msg.content,
        }));

      // Try Hugging Face API
      aiContent = await callHuggingFace(content, conversationHistory);
      source = 'huggingface';
    } catch (hfError: unknown) {
      const errorMessage = hfError instanceof Error ? hfError.message : 'Unknown error';
      console.warn(`HuggingFace API unavailable (${errorMessage}), using fallback`);

      if (errorMessage === 'MODEL_LOADING') {
        aiContent = `⏳ The AI model is currently loading (this can take 20-30 seconds on the first request). Please try again in a moment!\n\nIn the meantime, here's a quick answer:\n\n${generateFallbackResponse(content)}`;
      } else {
        aiContent = generateFallbackResponse(content);
      }
    }

    // Save AI response
    const aiMessage = await ChatMessage.create({
      userId: req.user?._id,
      type: 'ai',
      content: aiContent,
    });

    res.status(200).json({
      success: true,
      data: {
        userMessage,
        aiMessage,
        source,
      },
    });
  } catch (error) {
    next(error);
  }
};

// @desc    Get chat history
// @route   GET /api/assistant/history
// @access  Private
export const getChatHistory = async (
  req: AuthRequest,
  res: Response,
  next: NextFunction
): Promise<void> => {
  try {
    const messages = await ChatMessage.find({ userId: req.user?._id })
      .sort({ createdAt: 1 })
      .limit(50);

    // If no messages, return welcome message
    if (messages.length === 0) {
      res.status(200).json({
        success: true,
        data: [
          {
            id: 1,
            type: 'ai',
            content: "Hello! I'm your **AI Learning Tutor** powered by Hugging Face πŸ€—\n\nI can help you with:\n- 🟑 **JavaScript** & **TypeScript**\n- βš›οΈ **React** hooks, components & patterns\n- 🟒 **Node.js** & **Express** APIs\n- 🎨 **CSS** layouts & animations\n- πŸ—„οΈ **MongoDB** & database design\n\nAsk me anything! For example:\n> *\"Explain useEffect in React\"*\n> *\"How do I build a REST API?\"*",
          },
        ],
      });
      return;
    }

    res.status(200).json({
      success: true,
      data: messages,
    });
  } catch (error) {
    next(error);
  }
};

// @desc    Clear chat history
// @route   DELETE /api/assistant/history
// @access  Private
export const clearHistory = async (
  req: AuthRequest,
  res: Response,
  next: NextFunction
): Promise<void> => {
  try {
    await ChatMessage.deleteMany({ userId: req.user?._id });

    res.status(200).json({
      success: true,
      message: 'Chat history cleared',
    });
  } catch (error) {
    next(error);
  }
};

// @desc    Get suggested topics
// @route   GET /api/assistant/suggestions
// @access  Private
export const getSuggestions = async (
  _req: AuthRequest,
  res: Response,
  next: NextFunction
): Promise<void> => {
  try {
    const suggestions = [
      "Explain React hooks to me",
      "Help me with TypeScript generics",
      "What's the best way to structure APIs?",
      "How do I optimize database queries?",
      "Explain async/await in JavaScript",
      "What is the virtual DOM?",
      "How does useEffect work?",
      "Teach me about Next.js routing",
      "What are CSS Grid and Flexbox?",
      "How do I debug my code?",
    ];

    res.status(200).json({
      success: true,
      data: suggestions,
    });
  } catch (error) {
    next(error);
  }
};