Spaces:
Sleeping
Sleeping
Download backend/src/controllers/chatController.js from edichat/edi.chat.test: direct link, hf CLI and curl.
- Browser
- Download file 32.9 kB
-
https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/controllers/chatController.js
- Command line
-
hf download hf://spaces/edichat/edi.chat.test/backend/src/controllers/chatController.js
-
curl -L -o chatController.js https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/controllers/chatController.js
32.9 kB
const { validationResult } = require('express-validator');
const { v4: uuidv4 } = require('uuid');
const mongoose = require('mongoose');
const Conversation = require('../models/Conversation');
const User = require('../models/User');
const aiService = require('../services/aiService');
const ugaService = require('../services/ugaService');
const agenticService = require('../services/agenticService');
const knowledgeBaseService = require('../services/knowledgeBaseService');
const logger = require('../utils/logger');
class ChatController {
async sendMessage(req, res) {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
success: false,
errors: errors.array()
});
}
const { message, sessionId, category } = req.body;
// Get user ID - require authenticated user
if (!req.user || !req.user.id) {
return res.status(401).json({
success: false,
error: 'Authentication required'
});
}
const userId = req.user.id || req.user._id;
// Find or create conversation
let conversation;
if (sessionId) {
conversation = await Conversation.findOne({
sessionId,
userId,
isActive: true
});
}
if (!conversation) {
conversation = new Conversation({
userId,
sessionId: sessionId || uuidv4(),
category: category || 'general'
});
await conversation.save();
}
// Add user message
await conversation.addMessage('user', message);
// Prepare user context for AI
let user = await User.findById(userId);
// Handle missing user data
if (!user) {
return res.status(404).json({
success: false,
error: 'User not found'
});
}
const userContext = {
userId: userId,
role: user.role,
college: user.college,
major: user.major,
classification: user.classification
};
// First, check if this is an agentic request (requires actions)
const agenticResult = await agenticService.processAgenticRequest(
message,
user,
conversation.messages.map(msg => ({ role: msg.role, content: msg.content }))
);
let aiResponse;
if (agenticResult.requiresAction) {
// This is an agentic request - actions were planned and executed
aiResponse = {
content: agenticResult.response,
metadata: {
agentic: true,
actionsExecuted: agenticResult.executionResults.map(r => r.action),
executionResults: agenticResult.executionResults,
responseTime: agenticResult.executionResults.reduce((total, r) => total + (r.executionTime || 0), 0),
tokens: 0
}
};
} else {
// Check if this is a knowledge base query
const knowledgeResults = await knowledgeBaseService.queryKnowledgeBase(message);
if (knowledgeResults.length > 0) {
// Enhanced AI response with knowledge base context
const knowledgeContext = knowledgeResults.map(r =>
`${r.section}: ${r.content}`
).join('\n');
const enhancedMessages = [
{
role: 'system',
content: `Here is relevant UGA/Athens information to help answer the user's question:\n\n${knowledgeContext}`
},
...conversation.messages.map(msg => ({
role: msg.role,
content: msg.content
}))
];
aiResponse = await aiService.generateResponse(enhancedMessages, userContext);
aiResponse.metadata.knowledgeBaseUsed = true;
aiResponse.metadata.knowledgeResults = knowledgeResults.length;
} else {
// Check if this is a UGA system-specific query
// TEMPORARY: Disable UGA specific queries for testing
const ugaResponse = null;
if (ugaResponse) {
aiResponse = {
content: ugaResponse,
metadata: {
ugaSystemUsed: this.detectUgaSystem(message),
responseTime: 100,
tokens: 0
}
};
} else {
// Standard AI response
const messages = conversation.messages.map(msg => ({
role: msg.role,
content: msg.content
}));
aiResponse = await aiService.generateResponse(messages, userContext);
}
}
}
// Add AI response to conversation
await conversation.addMessage('assistant', aiResponse.content, aiResponse.metadata);
// Update user statistics
await user.incrementChatStats(conversation.category);
// Update conversation statistics
await conversation.updateStats(
aiResponse.metadata.tokens || 0,
aiResponse.metadata.responseTime || 0
);
logger.info('Chat message processed', {
userId,
sessionId: conversation.sessionId,
messageLength: message.length,
responseTime: aiResponse.metadata.responseTime
});
res.json({
success: true,
data: {
response: aiResponse.content,
sessionId: conversation.sessionId,
conversationId: conversation._id,
metadata: {
intent: aiResponse.metadata.intent,
ugaSystemUsed: aiResponse.metadata.ugaSystemUsed,
confidence: aiResponse.metadata.confidence
}
}
});
} catch (error) {
logger.error('Chat message error:', error);
res.status(500).json({
success: false,
error: 'Failed to process message'
});
}
}
async getConversations(req, res) {
try {
// Get user ID - require authenticated user
if (!req.user || !req.user.id) {
return res.status(401).json({
success: false,
error: 'Authentication required'
});
}
const userId = req.user.id || req.user._id;
const { page = 1, limit = 20, category } = req.query;
const query = {
userId,
isActive: true
};
if (category && category !== 'all') {
query.category = category;
}
const conversations = await Conversation.find(query)
.sort({ lastActivity: -1 })
.limit(limit * 1)
.skip((page - 1) * limit)
.select('sessionId title category lastActivity stats.messageCount');
const total = await Conversation.countDocuments(query);
// Transform conversations to match frontend expectations
const transformedConversations = conversations.map(conv => ({
id: conv._id.toString(),
sessionId: conv.sessionId,
title: conv.title,
category: conv.category,
lastActivity: conv.lastActivity,
stats: conv.stats
}));
res.json({
success: true,
data: {
conversations: transformedConversations,
pagination: {
page: parseInt(page),
limit: parseInt(limit),
total,
pages: Math.ceil(total / limit)
}
}
});
} catch (error) {
logger.error('Get conversations error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch conversations'
});
}
}
async getConversation(req, res) {
try {
const { conversationId } = req.params;
// Get user ID - require authenticated user
if (!req.user || !req.user.id) {
return res.status(401).json({
success: false,
error: 'Authentication required'
});
}
const userId = req.user.id || req.user._id;
// Validate conversation ID
if (!conversationId || conversationId === 'undefined' || conversationId === 'null') {
return res.status(400).json({
success: false,
error: 'Invalid conversation ID'
});
}
const conversation = await Conversation.findOne({
_id: conversationId,
userId,
isActive: true
});
if (!conversation) {
return res.status(404).json({
success: false,
error: 'Conversation not found'
});
}
// Transform conversation to match frontend expectations
const transformedConversation = {
id: conversation._id.toString(),
sessionId: conversation.sessionId,
title: conversation.title,
category: conversation.category,
messages: conversation.messages.map(msg => ({
id: msg._id.toString(),
role: msg.role,
content: msg.content,
timestamp: msg.timestamp,
metadata: msg.metadata
})),
ugaContext: conversation.ugaContext,
isActive: conversation.isActive,
lastActivity: conversation.lastActivity,
stats: conversation.stats,
retentionDate: conversation.retentionDate,
createdAt: conversation.createdAt,
updatedAt: conversation.updatedAt
};
res.json({
success: true,
data: transformedConversation
});
} catch (error) {
logger.error('Get conversation error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch conversation'
});
}
}
async deleteConversation(req, res) {
try {
const { conversationId } = req.params;
// Get user ID - require authenticated user
if (!req.user || !req.user.id) {
return res.status(401).json({
success: false,
error: 'Authentication required'
});
}
const userId = req.user.id || req.user._id;
const conversation = await Conversation.findOneAndUpdate(
{ _id: conversationId, userId },
{ isActive: false },
{ new: true }
);
if (!conversation) {
return res.status(404).json({
success: false,
error: 'Conversation not found'
});
}
logger.info('Conversation deleted', { userId, conversationId });
res.json({
success: true,
message: 'Conversation deleted successfully'
});
} catch (error) {
logger.error('Delete conversation error:', error);
res.status(500).json({
success: false,
error: 'Failed to delete conversation'
});
}
}
async rateConversation(req, res) {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
success: false,
errors: errors.array()
});
}
const { conversationId } = req.params;
const { rating, feedback } = req.body;
// Get user ID - require authenticated user
if (!req.user || !req.user.id) {
return res.status(401).json({
success: false,
error: 'Authentication required'
});
}
const userId = req.user.id || req.user._id;
const conversation = await Conversation.findOne({
_id: conversationId,
userId,
isActive: true
});
if (!conversation) {
return res.status(404).json({
success: false,
error: 'Conversation not found'
});
}
await conversation.setSatisfaction(rating, feedback);
logger.info('Conversation rated', { userId, conversationId, rating });
res.json({
success: true,
message: 'Rating submitted successfully'
});
} catch (error) {
logger.error('Rate conversation error:', error);
res.status(500).json({
success: false,
error: 'Failed to submit rating'
});
}
}
// Student-specific endpoints
async getStudentCourses(req, res) {
try {
// TEMPORARY: Use mock user when auth is disabled
const user = req.user || { id: '507f1f77bcf86cd799439011', role: 'student' };
if (user.role !== 'student') {
return res.status(403).json({
success: false,
error: 'Access restricted to students'
});
}
const courses = await ugaService.getElcCourses(user.id, req.token);
if (!courses.success) {
return res.status(503).json({
success: false,
error: courses.error,
fallback: courses.fallback
});
}
res.json({
success: true,
data: courses.data
});
} catch (error) {
logger.error('Get student courses error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch courses'
});
}
}
async getStudentGrades(req, res) {
try {
// TEMPORARY: Use mock user when auth is disabled
const user = req.user || { id: '507f1f77bcf86cd799439011', role: 'student' };
const { semester } = req.query;
if (user.role !== 'student') {
return res.status(403).json({
success: false,
error: 'Access restricted to students'
});
}
const grades = await ugaService.getAthenaGrades(user.id, semester, req.token);
if (!grades.success) {
return res.status(503).json({
success: false,
error: grades.error
});
}
res.json({
success: true,
data: grades.data
});
} catch (error) {
logger.error('Get student grades error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch grades'
});
}
}
async getStudentAssignments(req, res) {
try {
// TEMPORARY: Use mock user when auth is disabled
const user = req.user || { id: '507f1f77bcf86cd799439011', role: 'student' };
const { courseId } = req.query;
if (user.role !== 'student') {
return res.status(403).json({
success: false,
error: 'Access restricted to students'
});
}
const assignments = await ugaService.getElcAssignments(user.id, courseId, req.token);
if (!assignments.success) {
return res.status(503).json({
success: false,
error: assignments.error
});
}
res.json({
success: true,
data: assignments.data
});
} catch (error) {
logger.error('Get student assignments error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch assignments'
});
}
}
async getStudentSchedule(req, res) {
try {
// TEMPORARY: Use mock user when auth is disabled
const user = req.user || { id: '507f1f77bcf86cd799439011', role: 'student' };
if (user.role !== 'student') {
return res.status(403).json({
success: false,
error: 'Access restricted to students'
});
}
const studentInfo = await ugaService.getAthenaStudentInfo(user.id, req.token);
if (!studentInfo.success) {
return res.status(503).json({
success: false,
error: studentInfo.error,
fallback: studentInfo.fallback
});
}
res.json({
success: true,
data: studentInfo.data.schedule || []
});
} catch (error) {
logger.error('Get student schedule error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch schedule'
});
}
}
async getAnalytics(req, res) {
try {
// TEMPORARY: Use mock user when auth is disabled
const user = req.user || { id: '507f1f77bcf86cd799439011', role: 'admin' };
if (user.role !== 'admin') {
return res.status(403).json({
success: false,
error: 'Access restricted to administrators'
});
}
const { startDate, endDate } = req.query;
const start = startDate ? new Date(startDate) : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
const end = endDate ? new Date(endDate) : new Date();
const analytics = await Conversation.getAnalytics(start, end);
res.json({
success: true,
data: analytics
});
} catch (error) {
logger.error('Get analytics error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch analytics'
});
}
}
// Enhanced Student Services
async getRegistrationInfo(req, res) {
try {
// TEMPORARY: Use mock user when auth is disabled
const user = req.user || { id: '507f1f77bcf86cd799439011', role: 'student' };
if (user.role !== 'student') {
return res.status(403).json({
success: false,
error: 'Access restricted to students'
});
}
const registrationInfo = await ugaService.getRegistrationInfo(user.id, req.token);
if (!registrationInfo.success) {
return res.status(503).json({
success: false,
error: registrationInfo.error
});
}
res.json({
success: true,
data: registrationInfo.data
});
} catch (error) {
logger.error('Get registration info error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch registration information'
});
}
}
async getFinancialAidInfo(req, res) {
try {
// TEMPORARY: Use mock user when auth is disabled
const user = req.user || { id: '507f1f77bcf86cd799439011', role: 'student' };
if (user.role !== 'student') {
return res.status(403).json({
success: false,
error: 'Access restricted to students'
});
}
const financialAid = await ugaService.getFinancialAidInfo(user.id, req.token);
if (!financialAid.success) {
return res.status(503).json({
success: false,
error: financialAid.error
});
}
res.json({
success: true,
data: financialAid.data
});
} catch (error) {
logger.error('Get financial aid info error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch financial aid information'
});
}
}
async getHousingInfo(req, res) {
try {
// TEMPORARY: Use mock user when auth is disabled
const user = req.user || { id: '507f1f77bcf86cd799439011', role: 'student' };
if (user.role !== 'student') {
return res.status(403).json({
success: false,
error: 'Access restricted to students'
});
}
const housing = await ugaService.getHousingInfo(user.id, req.token);
if (!housing.success) {
return res.status(503).json({
success: false,
error: housing.error
});
}
res.json({
success: true,
data: housing.data
});
} catch (error) {
logger.error('Get housing info error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch housing information'
});
}
}
async getMealPlanInfo(req, res) {
try {
// TEMPORARY: Use mock user when auth is disabled
const user = req.user || { id: '507f1f77bcf86cd799439011', role: 'student' };
if (user.role !== 'student') {
return res.status(403).json({
success: false,
error: 'Access restricted to students'
});
}
const mealPlans = await ugaService.getMealPlanInfo(user.id, req.token);
if (!mealPlans.success) {
return res.status(503).json({
success: false,
error: mealPlans.error
});
}
res.json({
success: true,
data: mealPlans.data
});
} catch (error) {
logger.error('Get meal plan info error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch meal plan information'
});
}
}
async getBillingInfo(req, res) {
try {
// TEMPORARY: Use mock user when auth is disabled
const user = req.user || { id: '507f1f77bcf86cd799439011', role: 'student' };
if (user.role !== 'student') {
return res.status(403).json({
success: false,
error: 'Access restricted to students'
});
}
const billing = await ugaService.getBillingInfo(user.id, req.token);
if (!billing.success) {
return res.status(503).json({
success: false,
error: billing.error
});
}
res.json({
success: true,
data: billing.data
});
} catch (error) {
logger.error('Get billing info error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch billing information'
});
}
}
async getAcademicCalendar(req, res) {
try {
const { year } = req.query;
const currentYear = new Date().getFullYear();
const targetYear = year || currentYear;
const calendar = await ugaService.getAcademicCalendar(targetYear);
if (!calendar.success) {
return res.status(503).json({
success: false,
error: calendar.error
});
}
res.json({
success: true,
data: calendar.data
});
} catch (error) {
logger.error('Get academic calendar error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch academic calendar'
});
}
}
async getQuickResponses(req, res) {
try {
const quickResponses = [
{
category: 'eLC',
questions: [
{ q: 'How do I access eLC?', a: 'Visit elc.uga.edu and log in with your MyID credentials.' },
{ q: 'Why can\'t I see my courses in eLC?', a: 'Make sure you\'re enrolled and the instructor has published the course.' },
{ q: 'How do I submit an assignment in eLC?', a: 'Go to your course, find the assignment, and click "Submit Assignment".' }
]
},
{
category: 'Registration',
questions: [
{ q: 'When does registration open?', a: 'Registration dates vary by classification. Check Athena for your specific time.' },
{ q: 'How do I add/drop classes?', a: 'Use Athena during the add/drop period for your semester.' },
{ q: 'What if a class is full?', a: 'You can join the waitlist if available, or look for alternative sections.' }
]
},
{
category: 'Financial Aid',
questions: [
{ q: 'When is the FAFSA deadline?', a: 'The priority deadline is March 1. Use UGA school code 001598.' },
{ q: 'How do I apply for scholarships?', a: 'Visit scholarships.uga.edu to apply for UGA scholarships by January 1.' },
{ q: 'What is the HOPE Scholarship?', a: 'Merit-based scholarship for Georgia residents with 3.0+ GPA.' }
]
},
{
category: 'Housing & Dining',
questions: [
{ q: 'How do I apply for housing?', a: 'Submit your housing application online with a $300 deposit by May 1.' },
{ q: 'What meal plans are available?', a: 'Four plans: Bulldog (unlimited), Dawg (200 meals), Pup (150 meals), Commuter (50 meals).' },
{ q: 'Where can I eat on campus?', a: 'The Niche, ECV Dining Commons, Village Summit Food Court, and Bulldog Cafe.' }
]
},
{
category: 'Technical Support',
questions: [
{ q: 'I forgot my MyID password', a: 'Visit myid.uga.edu to reset your password or call EITS at 706-542-3106.' },
{ q: 'How do I set up ArchPass?', a: 'Download Duo Mobile and follow the setup instructions when prompted.' },
{ q: 'WiFi not working', a: 'Forget and reconnect to UGA-WiFi network, or contact EITS for help.' }
]
}
];
res.json({
success: true,
data: quickResponses
});
} catch (error) {
logger.error('Get quick responses error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch quick responses'
});
}
}
// Helper methods
async handleUgaSpecificQuery(message, user) {
const lowerMessage = message.toLowerCase();
// Handle system status queries
if (lowerMessage.includes('system status') || lowerMessage.includes('is elc down')) {
const status = await ugaService.getSystemStatus();
return this.formatSystemStatus(status);
}
// Handle IT support queries
if (lowerMessage.includes('it support') || lowerMessage.includes('help desk')) {
const support = await ugaService.getITSupport();
return this.formatITSupport(support.data);
}
// Handle registration queries
if (lowerMessage.includes('registration') || lowerMessage.includes('register for classes') || lowerMessage.includes('how to enroll')) {
const registration = await ugaService.getRegistrationInfo(user.id, null);
return this.formatRegistrationInfo(registration.data);
}
// Handle financial aid queries
if (lowerMessage.includes('financial aid') || lowerMessage.includes('fafsa') || lowerMessage.includes('scholarship') || lowerMessage.includes('hope')) {
const financialAid = await ugaService.getFinancialAidInfo(user.id, null);
return this.formatFinancialAidInfo(financialAid.data);
}
// Handle housing queries
if (lowerMessage.includes('housing') || lowerMessage.includes('dorm') || lowerMessage.includes('residence hall')) {
const housing = await ugaService.getHousingInfo(user.id, null);
return this.formatHousingInfo(housing.data);
}
// Handle meal plan queries
if (lowerMessage.includes('meal plan') || lowerMessage.includes('dining') || lowerMessage.includes('bulldog bucks')) {
const mealPlans = await ugaService.getMealPlanInfo(user.id, null);
return this.formatMealPlanInfo(mealPlans.data);
}
// Handle billing queries
if (lowerMessage.includes('tuition') || lowerMessage.includes('billing') || lowerMessage.includes('payment')) {
const billing = await ugaService.getBillingInfo(user.id, null);
return this.formatBillingInfo(billing.data);
}
// Handle campus services
if (lowerMessage.includes('library') || lowerMessage.includes('gym') || lowerMessage.includes('recreation')) {
const services = await ugaService.getCampusServices();
return this.formatCampusServices(services.data, lowerMessage);
}
return null;
}
detectUgaSystem(message) {
const lowerMessage = message.toLowerCase();
if (lowerMessage.includes('elc') || lowerMessage.includes('elearning')) {
return 'eLC';
} else if (lowerMessage.includes('athena')) {
return 'Athena';
} else if (lowerMessage.includes('myid') || lowerMessage.includes('archpass')) {
return 'MyID';
}
return null;
}
formatSystemStatus(status) {
let response = 'UGA System Status:\n\n';
for (const [system, systemStatus] of Object.entries(status)) {
const statusIndicator = systemStatus === 'operational' ? '[ONLINE]' : '[OFFLINE]';
response += `${statusIndicator} ${system.toUpperCase()}: ${systemStatus}\n`;
}
response += '\nIf you\'re experiencing issues, contact EITS at 706-542-3106.';
return response;
}
formatITSupport(support) {
return `**EITS Help Desk**
π Phone: ${support.eits.phone}
π§ Email: ${support.eits.email}
π Hours: ${support.eits.hours}
π Location: ${support.eits.location}
**Common Solutions:**
${Object.entries(support.commonIssues).map(([issue, solution]) =>
`β’ **${issue}:** ${solution}`
).join('\n')}`;
}
formatRegistrationInfo(registration) {
return `**UGA Course Registration**
**Registration Window:**
β’ Opens: ${registration.registrationWindow.opens}
β’ Priority: ${registration.registrationWindow.priority}
β’ System: ${registration.registrationWindow.location}
**Registration Process:**
${registration.process.steps.map((step, index) => `${index + 1}. ${step}`).join('\n')}
**Important Tips:**
${registration.tips.map(tip => `β’ ${tip}`).join('\n')}
**Key Dates:**
β’ Advising: ${registration.importantDates.advising}
β’ Registration: ${registration.importantDates.registration}
β’ Add/Drop: ${registration.importantDates.addDrop}
β’ Withdrawal Deadline: ${registration.importantDates.withdrawalDeadline}`;
}
formatFinancialAidInfo(aid) {
return `**UGA Financial Aid Information**
**Financial Aid Office:**
π ${aid.office.location}
π ${aid.office.phone}
π§ ${aid.office.email}
π ${aid.office.hours}
**Applications:**
β’ **FAFSA:** Due ${aid.applications.fafsa.deadline} (UGA code: ${aid.applications.fafsa.schoolCode})
β’ **UGA Scholarships:** Due ${aid.applications.ugaScholarships.deadline}
**Available Aid Types:**
${aid.aidTypes.map(type =>
`β’ **${type.type}:** ${type.description}${type.requirements ? `\n Requirements: ${type.requirements}` : ''}`
).join('\n')}
**Important Deadlines:**
β’ FAFSA Priority: ${aid.deadlines.fafsa}
β’ Verification: ${aid.deadlines.verification}
β’ Response: ${aid.deadlines.acceptanceResponse}`;
}
formatHousingInfo(housing) {
return `**UGA Housing Information**
**Housing Office:**
π ${housing.office.phone}
π§ ${housing.office.email}
π ${housing.office.website}
**Application Process:**
β’ Deadline: ${housing.application.deadline}
β’ Deposit: ${housing.application.deposit}
β’ Portal: ${housing.application.portal}
**Process Steps:**
${housing.application.process.map((step, index) => `${index + 1}. ${step}`).join('\n')}
**Residence Halls:**
${housing.dormitories.map(dorm =>
`β’ **${dorm.name}** (${dorm.type})\n Occupancy: ${dorm.occupancy}\n Amenities: ${dorm.amenities.join(', ')}`
).join('\n\n')}
**Annual Costs:**
β’ Traditional: ${housing.costs.traditional}
β’ Suite-style: ${housing.costs.suite}
β’ Apartment-style: ${housing.costs.apartment}`;
}
formatMealPlanInfo(mealPlans) {
return `**UGA Meal Plans**
**Dining Services:**
π ${mealPlans.office.phone}
π§ ${mealPlans.office.email}
π ${mealPlans.office.website}
**Available Plans:**
${mealPlans.plans.map(plan =>
`β’ **${plan.name}** - ${plan.cost}\n ${plan.meals} + ${plan.flex}\n Best for: ${plan.bestFor}`
).join('\n\n')}
**Dining Locations:**
${mealPlans.locations.map(location =>
`β’ **${location.name}** (${location.type})\n Location: ${location.location}\n Hours: ${location.hours}`
).join('\n\n')}
**Bulldog Bucks:**
${mealPlans.bullDogBucks.description}
β’ Use at: ${mealPlans.bullDogBucks.locations}
β’ Rollover: ${mealPlans.bullDogBucks.rollover}
β’ Refundable: ${mealPlans.bullDogBucks.refundable}`;
}
formatBillingInfo(billing) {
return `**UGA Student Accounts & Billing**
**Student Accounts Office:**
π ${billing.office.location}
π ${billing.office.phone}
π§ ${billing.office.email}
π ${billing.office.hours}
**Payment Methods:**
${billing.paymentMethods.map(method => `β’ ${method}`).join('\n')}
**Payment Plans:**
β’ **Semester Plan:** ${billing.paymentPlans.semesterPlan.description} (${billing.paymentPlans.semesterPlan.discount})
β’ **Monthly Plan:** ${billing.paymentPlans.monthlyPlan.description} (${billing.paymentPlans.monthlyPlan.fee})
**2024-25 Tuition & Fees:**
β’ **In-State Undergraduate:** ${billing.tuitionFees.inState.undergraduate}
β’ **Out-of-State Undergraduate:** ${billing.tuitionFees.outOfState.undergraduate}
β’ **Additional Fees:** ${billing.tuitionFees.additionalFees}
**Important Dates:**
β’ Fall Bill Available: ${billing.importantDates.fall2024.billAvailable}
β’ Fall Payment Due: ${billing.importantDates.fall2024.paymentDue}`;
}
formatCampusServices(services, query) {
if (query.includes('dining')) {
return `**UGA Dining Locations:**
${services.dining.locations.map(location =>
`β’ **${location.name}** - ${location.location}\n Hours: ${location.hours}`
).join('\n\n')}`;
}
if (query.includes('library')) {
return `**UGA Libraries:**
${services.libraries.map(lib =>
`β’ **${lib.name}**\n Hours: ${lib.hours}\n Services: ${lib.services.join(', ')}`
).join('\n\n')}`;
}
if (query.includes('gym') || query.includes('fitness')) {
return `**${services.recreation.ramsey.name}**
Hours: ${services.recreation.ramsey.hours}
Facilities:
${services.recreation.ramsey.facilities.map(facility => `β’ ${facility}`).join('\n')}`;
}
return null;
}
}
module.exports = new ChatController();
const { validationResult } = require('express-validator');
const { v4: uuidv4 } = require('uuid');
const mongoose = require('mongoose');
const Conversation = require('../models/Conversation');
const User = require('../models/User');
const aiService = require('../services/aiService');
const ugaService = require('../services/ugaService');
const agenticService = require('../services/agenticService');
const knowledgeBaseService = require('../services/knowledgeBaseService');
const logger = require('../utils/logger');
class ChatController {
async sendMessage(req, res) {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
success: false,
errors: errors.array()
});
}
const { message, sessionId, category } = req.body;
// Get user ID - require authenticated user
if (!req.user || !req.user.id) {
return res.status(401).json({
success: false,
error: 'Authentication required'
});
}
const userId = req.user.id || req.user._id;
// Find or create conversation
let conversation;
if (sessionId) {
conversation = await Conversation.findOne({
sessionId,
userId,
isActive: true
});
}
if (!conversation) {
conversation = new Conversation({
userId,
sessionId: sessionId || uuidv4(),
category: category || 'general'
});
await conversation.save();
}
// Add user message
await conversation.addMessage('user', message);
// Prepare user context for AI
let user = await User.findById(userId);
// Handle missing user data
if (!user) {
return res.status(404).json({
success: false,
error: 'User not found'
});
}
const userContext = {
userId: userId,
role: user.role,
college: user.college,
major: user.major,
classification: user.classification
};
// First, check if this is an agentic request (requires actions)
const agenticResult = await agenticService.processAgenticRequest(
message,
user,
conversation.messages.map(msg => ({ role: msg.role, content: msg.content }))
);
let aiResponse;
if (agenticResult.requiresAction) {
// This is an agentic request - actions were planned and executed
aiResponse = {
content: agenticResult.response,
metadata: {
agentic: true,
actionsExecuted: agenticResult.executionResults.map(r => r.action),
executionResults: agenticResult.executionResults,
responseTime: agenticResult.executionResults.reduce((total, r) => total + (r.executionTime || 0), 0),
tokens: 0
}
};
} else {
// Check if this is a knowledge base query
const knowledgeResults = await knowledgeBaseService.queryKnowledgeBase(message);
if (knowledgeResults.length > 0) {
// Enhanced AI response with knowledge base context
const knowledgeContext = knowledgeResults.map(r =>
`${r.section}: ${r.content}`