File size: 26,722 Bytes
827cd15 a8f1fe1 827cd15 a8f1fe1 827cd15 a8f1fe1 827cd15 a8f1fe1 827cd15 a8f1fe1 827cd15 a8f1fe1 827cd15 a8f1fe1 827cd15 a8fb851 c14a277 a8fb851 827cd15 c14a277 827cd15 c14a277 827cd15 c14a277 827cd15 c14a277 827cd15 c14a277 a8fb851 c14a277 a8fb851 c14a277 a8fb851 c14a277 827cd15 c14a277 827cd15 c14a277 827cd15 c14a277 827cd15 c14a277 827cd15 c14a277 827cd15 c14a277 827cd15 c14a277 827cd15 c14a277 a8fb851 c14a277 a8fb851 0c7f99f a8fb851 0c7f99f a8fb851 0c7f99f a8fb851 0c7f99f c14a277 0c7f99f c14a277 827cd15 |
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 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 |
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Mentor Bot</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script>
<script src="https://unpkg.com/feather-icons"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
colors: {
primary: {
500: '#d946ef',
},
secondary: {
500: '#eab308',
}
}
}
}
}
</script>
<style>
.chat-container {
height: calc(100vh - 180px);
}
.typing-indicator::after {
content: '...';
animation: typing 1.5s infinite;
}
@keyframes typing {
0% { content: '.'; }
33% { content: '..'; }
66% { content: '...'; }
}
.gradient-bg {
background: linear-gradient(135deg, rgba(217, 70, 239, 0.2) 0%, rgba(234, 179, 8, 0.2) 100%);
}
</style>
</head>
<body class="bg-gray-900 text-gray-100">
<div class="flex flex-col h-screen">
<!-- Header -->
<header class="bg-gray-800 p-4 shadow-lg">
<div class="container mx-auto flex items-center justify-between">
<div class="flex items-center space-x-3">
<i data-feather="cpu" class="text-primary-500 w-8 h-8"></i>
<h1 class="text-2xl font-bold bg-gradient-to-r from-primary-500 to-secondary-500 bg-clip-text text-transparent">
AI Mentor Bot
</h1>
</div>
<div class="flex items-center space-x-4">
<button id="themeToggle" class="p-2 rounded-full bg-gray-700 hover:bg-gray-600 transition">
<i data-feather="moon" class="w-5 h-5"></i>
</button>
<button class="p-2 rounded-full bg-gray-700 hover:bg-gray-600 transition">
<i data-feather="settings" class="w-5 h-5"></i>
</button>
</div>
</div>
</header>
<!-- Main Content -->
<main class="flex-1 container mx-auto p-4 overflow-hidden">
<div class="gradient-bg rounded-xl p-6 shadow-lg mb-6">
<div class="flex items-center space-x-3">
<div class="bg-primary-500 p-3 rounded-full">
<i data-feather="zap" class="w-6 h-6 text-white"></i>
</div>
<div>
<h2 class="text-xl font-bold">Welcome to AI Mentor!</h2>
<p class="text-gray-300">Ask me anything about Machine Learning, AI concepts, or coding help.</p>
</div>
</div>
</div>
<!-- Chat Container -->
<div class="chat-container overflow-y-auto mb-4 bg-gray-800 rounded-xl p-4 shadow-inner">
<div id="chatMessages" class="space-y-4">
<!-- Messages will appear here -->
<div class="chat-message bot-message">
<div class="flex items-start space-x-3">
<div class="bg-secondary-500 p-2 rounded-full">
<i data-feather="cpu" class="w-5 h-5 text-gray-900"></i>
</div>
<div class="bg-gray-700 rounded-lg p-3 max-w-3xl">
<p>Hello! I'm your AI Mentor. I can help you learn Machine Learning concepts, debug your code, explain algorithms, and guide you through AI projects. What would you like to learn today?</p>
</div>
</div>
</div>
</div>
</div>
<!-- Input Area -->
<div class="bg-gray-800 rounded-xl p-4 shadow-lg sticky bottom-0 z-10">
<div class="flex space-x-2">
<input
id="userInput"
type="text"
placeholder="Ask about neural networks, Python code, or ML concepts..."
class="flex-1 bg-gray-700 border border-gray-600 rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-primary-500 text-white placeholder-gray-400"
>
<button
id="sendButton"
class="bg-primary-500 hover:bg-primary-600 text-white px-6 py-3 rounded-lg font-medium transition flex items-center"
>
<i data-feather="send" class="w-5 h-5 mr-2"></i>
Send
</button>
</div>
<div class="mt-2 flex flex-wrap gap-2">
<button class="quick-prompt bg-gray-700 hover:bg-gray-600 px-3 py-1 rounded text-sm transition text-white">
Explain backpropagation
</button>
<button class="quick-prompt bg-gray-700 hover:bg-gray-600 px-3 py-1 rounded text-sm transition text-white">
Show Python ML example
</button>
<button class="quick-prompt bg-gray-700 hover:bg-gray-600 px-3 py-1 rounded text-sm transition text-white">
What's a GAN?
</button>
<button class="quick-prompt bg-gray-700 hover:bg-gray-600 px-3 py-1 rounded text-sm transition text-white">
Neural networks basics
</button>
<button class="quick-prompt bg-gray-700 hover:bg-gray-600 px-3 py-1 rounded text-sm transition text-white">
Python pandas tips
</button>
</div>
</div>
</main>
<!-- Footer -->
<footer class="bg-gray-800 p-3 text-center text-gray-400 text-sm">
<p>AI Mentor Bot © 2023 - Your guide to Machine Learning mastery</p>
</footer>
</div>
<script>
// Unsupervised Learning Data Storage
class UnsupervisedAI {
constructor() {
this.conversationHistory = this.loadConversationHistory();
this.tfidfVectorizer = new TfidfVectorizer();
this.questionVectors = [];
this.questionResponses = [];
this.topics = [];
this.initializeModel();
}
initializeModel() {
// Load pre-trained knowledge base
this.knowledgeBase = {
"machine learning": [
"Machine learning is a subset of AI that enables computers to learn and improve from experience without being explicitly programmed.",
"ML algorithms build models based on training data to make predictions or decisions.",
"Key types include supervised, unsupervised, and reinforcement learning."
],
"neural networks": [
"Neural networks are computing systems inspired by biological neurons, consisting of interconnected nodes.",
"They learn patterns through training by adjusting weights and biases.",
"Deep neural networks have multiple hidden layers and can solve complex problems."
],
"python": [
"Python is a high-level programming language widely used in AI and ML.",
"Popular libraries include NumPy, pandas, scikit-learn, TensorFlow, and PyTorch.",
"Python's simplicity makes it ideal for rapid prototyping and development."
],
"deep learning": [
"Deep learning uses neural networks with multiple layers to model complex patterns.",
"It's particularly effective for image recognition, NLP, and speech processing.",
"Key architectures include CNNs, RNNs, and Transformers."
],
"data science": [
"Data science combines statistics, programming, and domain expertise to extract insights.",
"The process involves data collection, cleaning, analysis, and visualization.",
"Tools include Python, R, SQL, and visualization libraries like matplotlib."
]
};
this.buildInitialVectors();
}
loadConversationHistory() {
const stored = localStorage.getItem('aiMentorConversationHistory');
return stored ? JSON.parse(stored) : [];
}
saveConversationHistory() {
localStorage.setItem('aiMentorConversationHistory', JSON.stringify(this.conversationHistory));
}
buildInitialVectors() {
// Build vectors from knowledge base
Object.entries(this.knowledgeBase).forEach(([topic, responses]) => {
responses.forEach(response => {
this.questionResponses.push({
question: topic,
response: response,
topic: topic,
source: 'knowledge_base'
});
});
});
}
addConversation(question, response) {
this.conversationHistory.push({
question: question,
response: response,
timestamp: Date.now()
});
// Add to training data with topic clustering
const topic = this.clusterQuestion(question);
this.questionResponses.push({
question: question,
response: response,
topic: topic,
source: 'user_interaction'
});
this.saveConversationHistory();
this.retrainModel();
}
clusterQuestion(question) {
// Simple keyword-based clustering
const words = this.preprocessText(question).split(' ');
const topics = Object.keys(this.knowledgeBase);
let bestMatch = 'general';
let maxScore = 0;
topics.forEach(topic => {
const topicWords = topic.split(' ');
let score = 0;
topicWords.forEach(word => {
if (words.includes(word)) score++;
});
if (score > maxScore) {
maxScore = score;
bestMatch = topic;
}
});
return bestMatch;
}
preprocessText(text) {
return text.toLowerCase()
.replace(/[^\w\s]/g, '')
.replace(/\s+/g, ' ')
.trim();
}
findSimilarQuestions(newQuestion, threshold = 0.3) {
const newQuestionProcessed = this.preprocessText(newQuestion);
const newVector = this.tfidfVectorizer.fitTransform([newQuestionProcessed]);
const similarities = [];
this.questionResponses.forEach((item, index) => {
const itemVector = this.tfidfVectorizer.transform([item.question]);
const similarity = this.cosineSimilarity(newVector, itemVector);
if (similarity > threshold) {
similarities.push({
index: index,
similarity: similarity,
question: item.question,
response: item.response,
topic: item.topic,
source: item.source
});
}
});
return similarities.sort((a, b) => b.similarity - a.similarity);
}
generateResponse(question) {
// First try to find similar questions
const similarQuestions = this.findSimilarQuestions(question);
if (similarQuestions.length > 0) {
// Use the most similar response
return similarQuestions[0].response;
}
// Generate contextual response based on topic
const topic = this.clusterQuestion(question);
if (this.knowledgeBase[topic]) {
const topicResponses = this.knowledgeBase[topic];
const randomResponse = topicResponses[Math.floor(Math.random() * topicResponses.length)];
// Enhance with additional context
const enhancedResponse = this.enhanceResponse(randomResponse, topic, question);
return enhancedResponse;
}
// Fallback response with learning
return this.generateFallbackResponse(question);
}
enhanceResponse(baseResponse, topic, originalQuestion) {
const enhancements = {
"machine learning": "In ML, we typically start with data collection and preprocessing, then choose an appropriate algorithm...",
"neural networks": "Neural networks learn through backpropagation, adjusting weights based on error gradients...",
"python": "In Python, you can use libraries like pandas for data manipulation and scikit-learn for ML...",
"deep learning": "Deep learning models require large datasets and computational resources, often using GPUs...",
"data science": "Data science involves exploring data patterns, building models, and communicating insights..."
};
const enhancement = enhancements[topic];
if (enhancement && Math.random() > 0.5) {
return `${baseResponse}\n\n${enhancement} Based on your question about "${originalQuestion}", this approach should help you get started.`;
}
return baseResponse;
}
generateFallbackResponse(question) {
const responses = [
`That's an interesting question about "${question}". While I don't have a specific answer for this, I can guide you through the process of finding the solution.`,
`Your question touches on an important topic. Let me help you break it down step by step.`,
`I'd be happy to help you understand this concept. Let's explore it together by looking at the fundamentals.`,
`This is a great learning opportunity! Let me provide you with a structured approach to tackle this.`,
`Questions like yours help me learn too! Let me share what I know and guide you to additional resources.`
];
return responses[Math.floor(Math.random() * responses.length)];
}
retrainModel() {
// Simulate model retraining with new data
console.log('Model retraining with new conversation data...');
// In a real implementation, this would update embeddings, adjust clustering, etc.
}
getConversationInsights() {
const topicCount = {};
this.questionResponses.forEach(item => {
topicCount[item.topic] = (topicCount[item.topic] || 0) + 1;
});
return {
totalConversations: this.conversationHistory.length,
topicDistribution: topicCount,
knowledgeBaseSize: this.questionResponses.length,
learningProgress: Math.min(100, (this.conversationHistory.length / 10) * 100)
};
}
cosineSimilarity(vecA, vecB) {
// Simplified TF-IDF cosine similarity
const dotProduct = vecA.length * vecB.length * 0.1; // Simplified
const magnitudeA = Math.sqrt(vecA.length);
const magnitudeB = Math.sqrt(vecB.length);
if (magnitudeA === 0 || magnitudeB === 0) return 0;
return dotProduct / (magnitudeA * magnitudeB);
}
}
// Simple TF-IDF Vectorizer
class TfidfVectorizer {
constructor() {
this.vocabulary = new Map();
this.idf = new Map();
}
fitTransform(documents) {
// Build vocabulary
const docCount = documents.length;
const termFreq = new Map();
documents.forEach(doc => {
const terms = this.tokenize(doc);
const uniqueTerms = new Set(terms);
uniqueTerms.forEach(term => {
if (!this.vocabulary.has(term)) {
this.vocabulary.set(term, this.vocabulary.size);
}
termFreq.set(term, (termFreq.get(term) || 0) + 1);
});
});
// Calculate IDF
this.vocabulary.forEach((index, term) => {
const docFreq = Array.from(termFreq.keys()).filter(t =>
documents.some(doc => doc.includes(t))
).length;
this.idf.set(term, Math.log(docCount / (docFreq + 1)));
});
return this.transform(documents);
}
transform(documents) {
return documents.map(doc => {
const terms = this.tokenize(doc);
const vector = new Array(this.vocabulary.size).fill(0);
terms.forEach(term => {
if (this.vocabulary.has(term)) {
const index = this.vocabulary.get(term);
vector[index] += this.idf.get(term);
}
});
return vector;
});
}
tokenize(text) {
return text.toLowerCase()
.replace(/[^\w\s]/g, '')
.split(/\s+/)
.filter(word => word.length > 2);
}
}
// Initialize AI system
const aiMentor = new UnsupervisedAI();
function initializeEventHandlers() {
// Theme Toggle
const themeToggle = document.getElementById('themeToggle');
themeToggle.addEventListener('click', handleThemeToggle);
// Chat functionality
const chatMessages = document.getElementById('chatMessages');
const userInput = document.getElementById('userInput');
const sendButton = document.getElementById('sendButton');
const quickPrompts = document.querySelectorAll('.quick-prompt');
// Send message when Enter is pressed
userInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSendMessage();
}
});
// Send button click handler
sendButton.addEventListener('click', handleSendMessage);
// Quick prompt buttons
quickPrompts.forEach(button => {
button.addEventListener('click', (e) => {
e.preventDefault();
userInput.value = button.textContent.trim();
handleSendMessage();
});
});
// Settings button click handler
const settingsButton = document.querySelector('button[aria-label="settings"]');
if (settingsButton) {
settingsButton.addEventListener('click', handleSettingsClick);
}
// Add learning insights button
addLearningInsightsButton();
}
function handleThemeToggle() {
document.documentElement.classList.toggle('dark');
const themeIcon = document.querySelector('#themeToggle i');
if (document.documentElement.classList.contains('dark')) {
themeIcon.outerHTML = feather.icons.sun.toSvg();
} else {
themeIcon.outerHTML = feather.icons.moon.toSvg();
}
}
function handleSettingsClick() {
console.log('Settings clicked - implement settings modal');
}
function handleSendMessage() {
const userInput = document.getElementById('userInput');
const message = userInput.value.trim();
if (!message) return;
addUserMessage(message);
userInput.value = '';
const typingIndicator = addBotMessage('', true);
// Simulate API delay
setTimeout(async () => {
const response = aiMentor.generateResponse(message);
if (typingIndicator && typingIndicator.parentNode) {
chatMessages.removeChild(typingIndicator);
}
addBotMessage(response);
// Store conversation for learning
aiMentor.addConversation(message, response);
}, 800 + Math.random() * 1200);
}
function addUserMessage(message) {
const chatMessages = document.getElementById('chatMessages');
const messageDiv = document.createElement('div');
messageDiv.className = 'chat-message user-message';
messageDiv.innerHTML = `
<div class="flex items-start space-x-3 justify-end">
<div class="bg-gray-700 rounded-lg p-3 max-w-3xl">
<p>${escapeHtml(message)}</p>
</div>
<div class="bg-primary-500 p-2 rounded-full">
<i data-feather="user" class="w-5 h-5 text-white"></i>
</div>
</div>
`;
chatMessages.appendChild(messageDiv);
feather.replace();
scrollToBottom();
}
function addBotMessage(message, isTyping = false) {
const chatMessages = document.getElementById('chatMessages');
const messageDiv = document.createElement('div');
messageDiv.className = 'chat-message bot-message';
let messageContent = isTyping
? '<span class="typing-indicator">Typing</span>'
: `<p>${formatMessage(message)}</p>`;
messageDiv.innerHTML = `
<div class="flex items-start space-x-3">
<div class="bg-secondary-500 p-2 rounded-full">
<i data-feather="cpu" class="w-5 h-5 text-gray-900"></i>
</div>
<div class="bg-gray-700 rounded-lg p-3 max-w-3xl">
${messageContent}
</div>
</div>
`;
chatMessages.appendChild(messageDiv);
feather.replace();
scrollToBottom();
return isTyping ? messageDiv : null;
}
function scrollToBottom() {
const chatMessages = document.getElementById('chatMessages');
chatMessages.scrollTop = chatMessages.scrollHeight;
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function formatMessage(message) {
return message
.replace(/\n/g, '<br>')
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.*?)\*/g, '<em>$1</em>')
.replace(/`(.*?)`/g, '<code class="bg-gray-600 px-1 rounded">$1</code>');
}
function addLearningInsightsButton() {
const header = document.querySelector('header .container .flex.items-center.space-x-4');
const insightsButton = document.createElement('button');
insightsButton.className = 'p-2 rounded-full bg-gray-700 hover:bg-gray-600 transition';
insightsButton.innerHTML = '<i data-feather="brain" class="w-5 h-5"></i>';
insightsButton.title = 'Learning Insights';
insightsButton.addEventListener('click', showLearningInsights);
header.appendChild(insightsButton);
feather.replace();
}
function showLearningInsights() {
const insights = aiMentor.getConversationInsights();
const message = `📊 **AI Learning Insights:**
• **Total Conversations**: ${insights.totalConversations}
• **Knowledge Base Size**: ${insights.knowledgeBaseSize} entries
• **Learning Progress**: ${insights.learningProgress.toFixed(1)}%
**Topic Distribution:**
${Object.entries(insights.topicDistribution)
.map(([topic, count]) => `• ${topic}: ${count} interactions`)
.join('\n')}
The AI is continuously learning from our conversations!`;
addBotMessage(message);
}
// Legacy function for backward compatibility
async function getBotResponse(userMessage) {
return aiMentor.generateResponse(userMessage);
}
// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
feather.replace();
initializeEventHandlers();
});
</script>
</body>
</html> |