Spaces:
Sleeping
Sleeping
Download backend/src/services/agenticService.js from edichat/edi.chat.test: direct link, hf CLI and curl.
- Browser
- Download file 20.3 kB
-
https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/services/agenticService.js
- Command line
-
hf download hf://spaces/edichat/edi.chat.test/backend/src/services/agenticService.js
-
curl -L -o agenticService.js https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/services/agenticService.js
20.3 kB
| const axios = require('axios'); | |
| const logger = require('../utils/logger'); | |
| const ugaService = require('./ugaService'); | |
| const aiService = require('./aiService'); | |
| const { redisUtils } = require('../utils/redis'); | |
| class AgenticService { | |
| constructor() { | |
| // Define available actions the agent can perform | |
| this.availableActions = { | |
| 'register_for_course': this.registerForCourse.bind(this), | |
| 'drop_course': this.dropCourse.bind(this), | |
| 'check_prerequisites': this.checkPrerequisites.bind(this), | |
| 'join_waitlist': this.joinWaitlist.bind(this), | |
| 'submit_assignment': this.submitAssignment.bind(this), | |
| 'schedule_advising': this.scheduleAdvising.bind(this), | |
| 'apply_financial_aid': this.applyFinancialAid.bind(this), | |
| 'pay_tuition': this.payTuition.bind(this), | |
| 'apply_housing': this.applyHousing.bind(this), | |
| 'select_meal_plan': this.selectMealPlan.bind(this), | |
| 'book_study_room': this.bookStudyRoom.bind(this), | |
| 'order_transcript': this.orderTranscript.bind(this), | |
| 'update_address': this.updateAddress.bind(this), | |
| 'reset_password': this.resetPassword.bind(this), | |
| 'check_grades': this.checkGrades.bind(this), | |
| 'find_textbooks': this.findTextbooks.bind(this), | |
| 'check_bus_schedule': this.checkBusSchedule.bind(this), | |
| 'find_parking': this.findParking.bind(this), | |
| 'make_appointment': this.makeAppointment.bind(this) | |
| }; | |
| } | |
| async processAgenticRequest(message, user, conversationHistory = []) { | |
| try { | |
| // Analyze the message to determine if it requires actions | |
| const actionAnalysis = await this.analyzeForActions(message, user); | |
| if (!actionAnalysis.requiresAction) { | |
| return { | |
| requiresAction: false, | |
| message: 'This request doesn\'t require any actions to be taken.' | |
| }; | |
| } | |
| // Plan the actions needed | |
| const actionPlan = await this.planActions(actionAnalysis, user, conversationHistory); | |
| // Execute the planned actions | |
| const executionResults = await this.executeActions(actionPlan, user); | |
| // Generate a comprehensive response | |
| const response = await this.generateAgenticResponse( | |
| message, | |
| actionPlan, | |
| executionResults, | |
| user | |
| ); | |
| return { | |
| requiresAction: true, | |
| actionsPlan: actionPlan, | |
| executionResults, | |
| response: response.content, | |
| metadata: response.metadata | |
| }; | |
| } catch (error) { | |
| logger.error('Agentic processing error:', error); | |
| return { | |
| requiresAction: false, | |
| error: 'Failed to process agentic request', | |
| fallbackMessage: 'I encountered an issue while trying to help you. Please try again or contact support.' | |
| }; | |
| } | |
| } | |
| async analyzeForActions(message, user) { | |
| try { | |
| const actionKeywords = { | |
| 'register_for_course': ['register for', 'enroll in', 'add course', 'sign up for'], | |
| 'drop_course': ['drop', 'withdraw from', 'remove course'], | |
| 'check_prerequisites': ['prereq', 'prerequisite', 'requirements for'], | |
| 'join_waitlist': ['waitlist', 'wait list', 'join waiting'], | |
| 'submit_assignment': ['submit', 'turn in', 'upload assignment'], | |
| 'schedule_advising': ['schedule', 'book', 'advising appointment'], | |
| 'apply_financial_aid': ['apply for aid', 'fafsa', 'submit financial'], | |
| 'pay_tuition': ['pay tuition', 'make payment', 'pay bill'], | |
| 'apply_housing': ['apply for housing', 'housing application'], | |
| 'select_meal_plan': ['choose meal plan', 'select dining'], | |
| 'book_study_room': ['book room', 'reserve study'], | |
| 'order_transcript': ['transcript', 'official transcript'], | |
| 'update_address': ['change address', 'update address'], | |
| 'reset_password': ['reset password', 'forgot password'], | |
| 'check_grades': ['check grades', 'view grades', 'my gpa'], | |
| 'find_textbooks': ['textbook', 'book list', 'course materials'], | |
| 'check_bus_schedule': ['bus schedule', 'transit'], | |
| 'find_parking': ['parking', 'parking spot'], | |
| 'make_appointment': ['appointment', 'schedule meeting'] | |
| }; | |
| const lowerMessage = message.toLowerCase(); | |
| const detectedActions = []; | |
| for (const [action, keywords] of Object.entries(actionKeywords)) { | |
| for (const keyword of keywords) { | |
| if (lowerMessage.includes(keyword)) { | |
| detectedActions.push(action); | |
| break; | |
| } | |
| } | |
| } | |
| return { | |
| requiresAction: detectedActions.length > 0, | |
| detectedActions, | |
| confidence: detectedActions.length > 0 ? 0.8 : 0, | |
| extractedEntities: this.extractEntities(message) | |
| }; | |
| } catch (error) { | |
| logger.error('Action analysis error:', error); | |
| return { requiresAction: false, detectedActions: [], confidence: 0 }; | |
| } | |
| } | |
| extractEntities(message) { | |
| const entities = { | |
| courses: [], | |
| times: [], | |
| locations: [], | |
| amounts: [], | |
| dates: [] | |
| }; | |
| // Extract course codes (e.g., CSCI 1301, MATH 2250) | |
| const coursePattern = /\b[A-Z]{3,4}\s*\d{4}\b/g; | |
| const courses = message.match(coursePattern); | |
| if (courses) { | |
| entities.courses = courses; | |
| } | |
| // Extract times (e.g., 10:00 AM, 2:30 PM) | |
| const timePattern = /\b\d{1,2}:\d{2}\s*(AM|PM|am|pm)\b/g; | |
| const times = message.match(timePattern); | |
| if (times) { | |
| entities.times = times; | |
| } | |
| // Extract dollar amounts | |
| const amountPattern = /\$\d+(?:,\d{3})*(?:\.\d{2})?/g; | |
| const amounts = message.match(amountPattern); | |
| if (amounts) { | |
| entities.amounts = amounts; | |
| } | |
| // Extract dates | |
| const datePattern = /\b(?:\d{1,2}\/\d{1,2}\/\d{4}|\w+\s+\d{1,2},?\s+\d{4})\b/g; | |
| const dates = message.match(datePattern); | |
| if (dates) { | |
| entities.dates = dates; | |
| } | |
| return entities; | |
| } | |
| async planActions(actionAnalysis, user, conversationHistory) { | |
| const actionPlan = { | |
| actions: [], | |
| estimatedTime: 0, | |
| requiresConfirmation: false, | |
| prerequisites: [], | |
| risks: [] | |
| }; | |
| for (const actionType of actionAnalysis.detectedActions) { | |
| const actionDetails = await this.getActionDetails(actionType, actionAnalysis.extractedEntities, user); | |
| actionPlan.actions.push(actionDetails); | |
| actionPlan.estimatedTime += actionDetails.estimatedTime || 30; // seconds | |
| // Check if action requires confirmation | |
| if (actionDetails.requiresConfirmation) { | |
| actionPlan.requiresConfirmation = true; | |
| } | |
| // Add prerequisites | |
| if (actionDetails.prerequisites) { | |
| actionPlan.prerequisites.push(...actionDetails.prerequisites); | |
| } | |
| // Add risks | |
| if (actionDetails.risks) { | |
| actionPlan.risks.push(...actionDetails.risks); | |
| } | |
| } | |
| return actionPlan; | |
| } | |
| async getActionDetails(actionType, entities, user) { | |
| const actionDetails = { | |
| type: actionType, | |
| status: 'planned', | |
| parameters: {}, | |
| estimatedTime: 30, | |
| requiresConfirmation: false, | |
| prerequisites: [], | |
| risks: [] | |
| }; | |
| switch (actionType) { | |
| case 'register_for_course': | |
| actionDetails.parameters.courses = entities.courses; | |
| actionDetails.requiresConfirmation = true; | |
| actionDetails.estimatedTime = 60; | |
| actionDetails.prerequisites = ['Valid registration window', 'Prerequisites met', 'No time conflicts']; | |
| actionDetails.risks = ['Course may fill up', 'Schedule conflicts possible']; | |
| break; | |
| case 'pay_tuition': | |
| actionDetails.parameters.amounts = entities.amounts; | |
| actionDetails.requiresConfirmation = true; | |
| actionDetails.estimatedTime = 120; | |
| actionDetails.prerequisites = ['Valid payment method', 'Outstanding balance']; | |
| actionDetails.risks = ['Payment processing fees may apply']; | |
| break; | |
| case 'drop_course': | |
| actionDetails.parameters.courses = entities.courses; | |
| actionDetails.requiresConfirmation = true; | |
| actionDetails.estimatedTime = 45; | |
| actionDetails.prerequisites = ['Within drop period']; | |
| actionDetails.risks = ['May affect full-time status', 'Financial aid implications']; | |
| break; | |
| case 'apply_housing': | |
| actionDetails.requiresConfirmation = true; | |
| actionDetails.estimatedTime = 300; // 5 minutes | |
| actionDetails.prerequisites = ['Housing application period open', 'Deposit payment ready']; | |
| actionDetails.risks = ['Limited availability', 'Preference not guaranteed']; | |
| break; | |
| case 'book_study_room': | |
| actionDetails.parameters.times = entities.times; | |
| actionDetails.parameters.dates = entities.dates; | |
| actionDetails.estimatedTime = 30; | |
| break; | |
| default: | |
| actionDetails.estimatedTime = 60; | |
| break; | |
| } | |
| return actionDetails; | |
| } | |
| async executeActions(actionPlan, user) { | |
| const results = []; | |
| for (const action of actionPlan.actions) { | |
| try { | |
| logger.info(`Executing action: ${action.type}`, { userId: user.id, action: action.type }); | |
| action.status = 'executing'; | |
| const result = await this.availableActions[action.type](action, user); | |
| action.status = result.success ? 'completed' : 'failed'; | |
| results.push({ | |
| action: action.type, | |
| success: result.success, | |
| message: result.message, | |
| data: result.data, | |
| executionTime: result.executionTime | |
| }); | |
| } catch (error) { | |
| logger.error(`Action execution failed: ${action.type}`, error); | |
| action.status = 'failed'; | |
| results.push({ | |
| action: action.type, | |
| success: false, | |
| message: `Failed to execute ${action.type}: ${error.message}`, | |
| error: error.message | |
| }); | |
| } | |
| } | |
| return results; | |
| } | |
| // Action implementations | |
| async registerForCourse(action, user) { | |
| const startTime = Date.now(); | |
| try { | |
| const courses = action.parameters.courses || []; | |
| if (courses.length === 0) { | |
| return { | |
| success: false, | |
| message: 'No courses specified for registration', | |
| executionTime: Date.now() - startTime | |
| }; | |
| } | |
| // Check registration window | |
| const registrationInfo = await ugaService.getRegistrationInfo(user.id, user.token); | |
| if (!registrationInfo.success) { | |
| return { | |
| success: false, | |
| message: 'Unable to verify registration eligibility', | |
| executionTime: Date.now() - startTime | |
| }; | |
| } | |
| const results = []; | |
| for (const courseCode of courses) { | |
| // Simulate course registration via Athena API | |
| const registrationResult = await this.simulateAthenaRegistration(courseCode, user); | |
| results.push({ | |
| course: courseCode, | |
| success: registrationResult.success, | |
| message: registrationResult.message | |
| }); | |
| } | |
| return { | |
| success: results.every(r => r.success), | |
| message: `Registration attempt completed for ${courses.length} course(s)`, | |
| data: results, | |
| executionTime: Date.now() - startTime | |
| }; | |
| } catch (error) { | |
| return { | |
| success: false, | |
| message: `Registration failed: ${error.message}`, | |
| executionTime: Date.now() - startTime | |
| }; | |
| } | |
| } | |
| async simulateAthenaRegistration(courseCode, user) { | |
| // In a real implementation, this would connect to Athena API | |
| // For demo purposes, we'll simulate the registration process | |
| // Random success/failure for demo | |
| const success = Math.random() > 0.3; // 70% success rate | |
| if (success) { | |
| return { | |
| success: true, | |
| message: `Successfully registered for ${courseCode}` | |
| }; | |
| } else { | |
| const reasons = [ | |
| 'Course is full', | |
| 'Prerequisites not met', | |
| 'Time conflict detected', | |
| 'Registration window closed', | |
| 'Course not found' | |
| ]; | |
| const reason = reasons[Math.floor(Math.random() * reasons.length)]; | |
| return { | |
| success: false, | |
| message: `Failed to register for ${courseCode}: ${reason}` | |
| }; | |
| } | |
| } | |
| async payTuition(action, user) { | |
| const startTime = Date.now(); | |
| try { | |
| const amounts = action.parameters.amounts || []; | |
| const paymentAmount = amounts[0] || 'full balance'; | |
| // Get billing information | |
| const billing = await ugaService.getBillingInfo(user.id, user.token); | |
| if (!billing.success) { | |
| return { | |
| success: false, | |
| message: 'Unable to access billing information', | |
| executionTime: Date.now() - startTime | |
| }; | |
| } | |
| // Simulate payment processing | |
| const paymentResult = await this.simulatePaymentProcessing(paymentAmount, user); | |
| return { | |
| success: paymentResult.success, | |
| message: paymentResult.message, | |
| data: { | |
| amount: paymentAmount, | |
| transactionId: paymentResult.transactionId, | |
| confirmationNumber: paymentResult.confirmationNumber | |
| }, | |
| executionTime: Date.now() - startTime | |
| }; | |
| } catch (error) { | |
| return { | |
| success: false, | |
| message: `Payment failed: ${error.message}`, | |
| executionTime: Date.now() - startTime | |
| }; | |
| } | |
| } | |
| async simulatePaymentProcessing(amount, user) { | |
| // Simulate payment processing delay | |
| await new Promise(resolve => setTimeout(resolve, 2000)); | |
| // Random success/failure for demo | |
| const success = Math.random() > 0.1; // 90% success rate | |
| if (success) { | |
| return { | |
| success: true, | |
| message: `Payment of ${amount} processed successfully`, | |
| transactionId: `TXN${Date.now()}`, | |
| confirmationNumber: `UGA${Math.random().toString(36).substr(2, 9).toUpperCase()}` | |
| }; | |
| } else { | |
| return { | |
| success: false, | |
| message: 'Payment processing failed. Please verify your payment method and try again.' | |
| }; | |
| } | |
| } | |
| async bookStudyRoom(action, user) { | |
| const startTime = Date.now(); | |
| try { | |
| const times = action.parameters.times || ['next available']; | |
| const dates = action.parameters.dates || [new Date().toDateString()]; | |
| // Simulate room booking | |
| const bookingResult = await this.simulateRoomBooking(times[0], dates[0], user); | |
| return { | |
| success: bookingResult.success, | |
| message: bookingResult.message, | |
| data: { | |
| room: bookingResult.room, | |
| time: times[0], | |
| date: dates[0], | |
| confirmationCode: bookingResult.confirmationCode | |
| }, | |
| executionTime: Date.now() - startTime | |
| }; | |
| } catch (error) { | |
| return { | |
| success: false, | |
| message: `Room booking failed: ${error.message}`, | |
| executionTime: Date.now() - startTime | |
| }; | |
| } | |
| } | |
| async simulateRoomBooking(time, date, user) { | |
| const rooms = [ | |
| 'Miller Learning Center - Room 234', | |
| 'Main Library - Study Room 12', | |
| 'Science Library - Group Room A', | |
| 'Student Center - Conference Room 3' | |
| ]; | |
| const success = Math.random() > 0.2; // 80% success rate | |
| if (success) { | |
| return { | |
| success: true, | |
| message: `Study room booked successfully`, | |
| room: rooms[Math.floor(Math.random() * rooms.length)], | |
| confirmationCode: `ROOM${Math.random().toString(36).substr(2, 6).toUpperCase()}` | |
| }; | |
| } else { | |
| return { | |
| success: false, | |
| message: 'No rooms available at the requested time. Please try a different time slot.' | |
| }; | |
| } | |
| } | |
| // Implement other action methods similarly... | |
| async dropCourse(action, user) { | |
| // Implementation for dropping courses | |
| return { success: true, message: 'Course drop functionality would be implemented here', executionTime: 1000 }; | |
| } | |
| async checkPrerequisites(action, user) { | |
| // Implementation for checking prerequisites | |
| return { success: true, message: 'Prerequisite check functionality would be implemented here', executionTime: 500 }; | |
| } | |
| async joinWaitlist(action, user) { | |
| // Implementation for joining waitlists | |
| return { success: true, message: 'Waitlist functionality would be implemented here', executionTime: 750 }; | |
| } | |
| async submitAssignment(action, user) { | |
| // Implementation for submitting assignments | |
| return { success: true, message: 'Assignment submission functionality would be implemented here', executionTime: 2000 }; | |
| } | |
| async scheduleAdvising(action, user) { | |
| // Implementation for scheduling advising appointments | |
| return { success: true, message: 'Advising scheduling functionality would be implemented here', executionTime: 1500 }; | |
| } | |
| async applyFinancialAid(action, user) { | |
| // Implementation for financial aid applications | |
| return { success: true, message: 'Financial aid application functionality would be implemented here', executionTime: 3000 }; | |
| } | |
| async applyHousing(action, user) { | |
| // Implementation for housing applications | |
| return { success: true, message: 'Housing application functionality would be implemented here', executionTime: 2500 }; | |
| } | |
| async selectMealPlan(action, user) { | |
| // Implementation for meal plan selection | |
| return { success: true, message: 'Meal plan selection functionality would be implemented here', executionTime: 1000 }; | |
| } | |
| async orderTranscript(action, user) { | |
| // Implementation for transcript orders | |
| return { success: true, message: 'Transcript order functionality would be implemented here', executionTime: 1500 }; | |
| } | |
| async updateAddress(action, user) { | |
| // Implementation for address updates | |
| return { success: true, message: 'Address update functionality would be implemented here', executionTime: 800 }; | |
| } | |
| async resetPassword(action, user) { | |
| // Implementation for password resets | |
| return { success: true, message: 'Password reset functionality would be implemented here', executionTime: 600 }; | |
| } | |
| async checkGrades(action, user) { | |
| // Implementation for grade checking | |
| return { success: true, message: 'Grade check functionality would be implemented here', executionTime: 400 }; | |
| } | |
| async findTextbooks(action, user) { | |
| // Implementation for textbook finding | |
| return { success: true, message: 'Textbook search functionality would be implemented here', executionTime: 700 }; | |
| } | |
| async checkBusSchedule(action, user) { | |
| // Implementation for bus schedule checking | |
| return { success: true, message: 'Bus schedule functionality would be implemented here', executionTime: 300 }; | |
| } | |
| async findParking(action, user) { | |
| // Implementation for parking finding | |
| return { success: true, message: 'Parking finder functionality would be implemented here', executionTime: 400 }; | |
| } | |
| async makeAppointment(action, user) { | |
| // Implementation for general appointment making | |
| return { success: true, message: 'Appointment scheduling functionality would be implemented here', executionTime: 1200 }; | |
| } | |
| async generateAgenticResponse(message, actionPlan, executionResults, user) { | |
| try { | |
| const contextPrompt = ` | |
| You are UGA Assistant executing actions for a student. Here's what happened: | |
| ORIGINAL REQUEST: "${message}" | |
| ACTIONS PLANNED: | |
| ${actionPlan.actions.map(action => | |
| `- ${action.type}: ${action.status}` | |
| ).join('\n')} | |
| EXECUTION RESULTS: | |
| ${executionResults.map(result => | |
| `- ${result.action}: ${result.success ? 'SUCCESS' : 'FAILED'} - ${result.message}` | |
| ).join('\n')} | |
| Generate a helpful response that: | |
| 1. Confirms what actions were taken | |
| 2. Reports the results clearly | |
| 3. Provides next steps if needed | |
| 4. Maintains a helpful, professional tone | |
| `; | |
| const aiResponse = await aiService.generateResponse([ | |
| { role: 'system', content: contextPrompt }, | |
| { role: 'user', content: message } | |
| ], { userId: user.id }); | |
| return aiResponse; | |
| } catch (error) { | |
| logger.error('Agentic response generation error:', error); | |
| return { | |
| content: 'I attempted to help you with your request. Please check the results and let me know if you need further assistance.', | |
| metadata: { error: error.message } | |
| }; | |
| } | |
| } | |
| } | |
| module.exports = new AgenticService(); |