const OpenAI = require('openai'); const logger = require('../utils/logger'); const webSearchService = require('./webSearchService'); const searchCacheService = require('./searchCacheService'); const ugaSearchEnhancements = require('./ugaSearchEnhancements'); // Initialize OpenAI (only if API key is provided) let openai = null; if (process.env.OPENAI_API_KEY && process.env.OPENAI_API_KEY !== 'your-openai-api-key') { openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); } class AIService { constructor() { this.useLocal = process.env.USE_LOCAL_AI === 'true'; this.localModelUrl = process.env.LOCAL_AI_URL || 'http://localhost:11434'; this.localModel = process.env.LOCAL_AI_MODEL || 'llama2'; this.useHuggingFace = process.env.USE_HUGGINGFACE === 'true'; this.huggingFaceApiKey = process.env.HUGGINGFACE_API_KEY; this.huggingFaceModel = process.env.HUGGINGFACE_MODEL || 'microsoft/DialoGPT-large'; this.ugaSystemPrompt = ` You are UGA Assistant, an advanced AI chatbot specifically designed to help University of Georgia students, faculty, and staff. You embody the spirit of the Bulldog Nation with deep knowledge of UGA's history, traditions, and campus life. ESSENTIAL UGA KNOWLEDGE: • Founded: January 27, 1785 (America's first state-chartered university) • Campus: 767 acres in Athens, Georgia (Classic City) • Mascot: Uga (English Bulldog) - currently Uga XI "Boom" • Colors: Red (#BA0C2F) and Black (#000000) • Motto: "Et docere et rerum exquirere causas" (To teach and to inquire into the nature of things) • President: Jere W. Morehead • Student Population: ~40,000 (30,000+ undergrad, 10,000+ graduate) ACADEMIC EXCELLENCE: • 17 Schools and Colleges including Franklin College, Terry College of Business, Grady College, College of Engineering • Top Programs: Public Affairs (#4), Insurance/Risk Management (#2), Real Estate (#5), Veterinary Medicine (#10) • Honors Program: One of the nation's finest with 2,000+ students • SPIA (School of Public and International Affairs): Top-ranked programs • Research: R1 institution with $525M+ annual research expenditures TRADITIONS & CAMPUS LIFE: • The Arch: Only walk through after graduation (tradition) • Chapel Bell: Ring after victories and achievements • Sanford Stadium: "Between the Hedges" - capacity 93,033 • Fight Song: "Glory, Glory to Old Georgia" • The Dawg Walk: Pre-game tradition • Calling the Dawgs: Iconic cheer led by Hairy Dawg • North Campus: Historic heart with iconic buildings • Tate Student Center: Main student hub • MLC (Miller Learning Center): 24/7 study space KEY LOCATIONS: • Main Library: 3rd largest academic library in US • Ramsey Student Center: 420,000 sq ft fitness facility • Georgia Theatre: Historic music venue • Downtown Athens: Vibrant music and food scene • East Campus Village: Modern residential community • Science Learning Center: State-of-the-art facilities • Special Collections Building: Archives and rare books CAMPUS SERVICES: • UGA Bus System: Free campus transit with 20+ routes • UGACard: Student ID for dining, buildings, events • PAWS (Athena): Student information system • eLC: Online learning platform (Brightspace D2L) • Career Center: Top-tier career services • UHC (University Health Center): Comprehensive health services • CAPS: Counseling and Psychiatric Services DINING & HOUSING: • 5 Dining Commons: Bolton, Oglethorpe, Snelling, Village Summit, ECV • Bulldog Bucks: Campus currency system • 30+ Residence Halls across East, West, and South Campus • Learning Communities: Themed residential programs ACADEMIC CALENDAR (2024-2025): • Fall 2024: Aug 14 - Dec 11 • Spring 2025: Jan 8 - May 7 • Maymester: May 12 - May 30 • Summer 2025: Various sessions June-July QUICK FACTS: • Athens ranked #1 College Town in America multiple times • 300+ student organizations • 60+ Greek organizations • DAWGS acronym: Developing Accurate World-class Grads Successfully • The Red & Black: Independent student newspaper since 1893 Current focus: ${new Date().toLocaleDateString()} - Ready to assist with registration, campus resources, academic planning, and all things UGA! AGENTIC CAPABILITIES - YOU CAN EXECUTE ACTIONS: - Register students for courses through Athena - Process tuition payments - Submit assignments to eLC - Schedule advising appointments - Apply for financial aid, housing, and meal plans - Book study rooms and facilities - Update student information and addresses - Make appointments with various campus services - Check grades and academic progress - Find and recommend textbooks UGA SYSTEMS YOU CAN ACCESS AND CONTROL: - eLC (eLearning Commons): Course materials, assignments, grades, submissions - Athena: Student information system, registration, transcripts, payments - MyID/ArchPass: Authentication and account management - Housing System: Applications, room assignments, changes - Dining Services: Meal plan selection and management - Campus Services: Room booking, appointment scheduling COMPREHENSIVE KNOWLEDGE BASE: - Complete information about UGA academics, athletics, and student life - Detailed Athens, Georgia area knowledge including dining, entertainment, transportation - Campus facilities, resources, and services - Academic policies, procedures, and requirements - Student organizations, Greek life, and traditions KEY UGA INFORMATION: - Authentication uses MyID with ArchPass (Duo) two-step verification - eLC is the primary learning management system - Athena is the student information system - Campus operates on semester system (Fall, Spring, Summer) - Main campus in Athens, Georgia (Classic City) - SEC athletics with strong Bulldog traditions RESPONSE GUIDELINES: 1. Always be helpful and provide accurate UGA-specific information 2. When users need actions performed, execute them proactively while ensuring safety 3. Ask for confirmation before executing high-risk actions (payments, course changes) 4. Provide step-by-step updates when performing actions 5. For technical issues, direct to EITS but also try to resolve directly when possible 6. Be aware of academic calendar and important dates 7. Respect privacy and never ask for or display sensitive information like passwords or SSNs 8. Use your comprehensive knowledge of UGA, Athens, and student life to provide detailed, contextual responses 9. If you cannot access real-time data, explain this limitation and suggest alternative resources ATHENS, GEORGIA CONTEXT: - Classic City located 70 miles northeast of Atlanta - Vibrant college town with rich music history (R.E.M., B-52s) - Excellent dining scene including student favorites like Mama's Boy, The Grit, Mellow Mushroom - Multiple neighborhoods each with unique character (Five Points, Normaltown, Downtown) - Good public transportation and walkable areas - Strong local culture with festivals, live music, and community events Remember: You are an agentic assistant representing UGA - you can both inform AND act. Maintain professionalism while being proactive, helpful, and knowledgeable about all aspects of UGA and Athens life.`; } async generateLocalResponse(messages, userContext = {}) { try { const startTime = Date.now(); // Check if Ollama is accessible first try { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 5000); const healthCheck = await fetch(`${this.localModelUrl}/api/tags`, { method: 'GET', headers: { 'Content-Type': 'application/json' }, signal: controller.signal }); clearTimeout(timeoutId); if (!healthCheck.ok) { throw new Error(`Ollama not accessible: HTTP ${healthCheck.status}`); } } catch (healthError) { if (healthError.name === 'AbortError') { throw new Error(`Ollama health check timed out. Is Ollama running at ${this.localModelUrl}?`); } throw new Error(`Ollama health check failed: ${healthError.message}. Is Ollama running at ${this.localModelUrl}?`); } // Check if the query needs web search const lastUserMessage = messages[messages.length - 1]?.content || ''; const needsWebSearch = this.shouldUseWebSearch(lastUserMessage); let searchContext = ''; if (needsWebSearch) { logger.info('Query requires web search', { query: lastUserMessage }); try { searchContext = await this.performWebSearch(lastUserMessage, userContext); } catch (searchError) { logger.warn('Web search failed, proceeding without current data', { error: searchError.message }); searchContext = `Web search was attempted but failed: ${searchError.message}. Responding with available knowledge.`; } } // Prepare system message with UGA context and search results const systemMessage = { role: 'system', content: this.ugaSystemPrompt + this.buildContextualPrompt(userContext) + (searchContext ? `\n\n${searchContext}` : '') }; // Format messages for Ollama const formattedMessages = [systemMessage, ...messages]; const prompt = this.formatMessagesForOllama(formattedMessages); logger.info('Sending request to local AI', { model: this.localModel, url: this.localModelUrl, promptLength: prompt.length }); // Call Ollama API with timeout const generateController = new AbortController(); const generateTimeoutId = setTimeout(() => generateController.abort(), 60000); const response = await fetch(`${this.localModelUrl}/api/generate`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ model: this.localModel, prompt: prompt, stream: false, options: { temperature: 0.7, top_p: 0.9, top_k: 40, num_predict: 1000 } }), signal: generateController.signal }); clearTimeout(generateTimeoutId); if (!response.ok) { const errorText = await response.text(); throw new Error(`Ollama API error: ${response.status} - ${errorText}`); } const data = await response.json(); const endTime = Date.now(); const responseTime = endTime - startTime; // Validate response if (!data.response || data.response.trim().length === 0) { throw new Error('Empty response from Ollama'); } logger.info('Local AI response generated successfully', { model: this.localModel, responseTime, promptLength: prompt.length, responseLength: data.response.length, tokens: data.eval_count || 0 }); return { content: data.response.trim(), metadata: { aiProvider: 'ollama', localModel: this.localModel, responseTime, tokens: data.eval_count || 0, promptTokens: data.prompt_eval_count || 0, success: true } }; } catch (error) { logger.error('Local AI service error:', error); // Enhanced fallback response with setup instructions const fallbackContent = `**Local AI Connection Issue** I'm configured to use Ollama (local AI) but encountered an error: **Error**: ${error.message} **Quick Fix**: 1. **Check Ollama**: \`curl ${this.localModelUrl}/api/tags\` 2. **Start Ollama**: \`ollama serve\` 3. **Pull Model**: \`ollama pull ${this.localModel}\` **Current Config**: • Model: ${this.localModel} • URL: ${this.localModelUrl} • Provider: Local Ollama (Privacy-First) See LOCAL_AI_SETUP.md for detailed troubleshooting. **Test Question**: Try asking "What is UGA?" to test the connection.`; return { content: fallbackContent, metadata: { aiProvider: 'ollama', localModel: this.localModel, fallback: true, responseTime: 100, error: error.message, setupRequired: true } }; } } async generateHuggingFaceResponse(messages, userContext = {}) { try { const startTime = Date.now(); // Get the last user message const lastMessage = messages[messages.length - 1]?.content || ''; // Call Hugging Face Inference API const response = await fetch(`https://api-inference.huggingface.co/models/${this.huggingFaceModel}`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.huggingFaceApiKey}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ inputs: lastMessage, parameters: { max_length: 500, temperature: 0.7, do_sample: true } }), }); if (!response.ok) { throw new Error(`Hugging Face API error: ${response.status}`); } const data = await response.json(); const endTime = Date.now(); const responseTime = endTime - startTime; let content = ''; if (Array.isArray(data) && data[0]?.generated_text) { content = data[0].generated_text.replace(lastMessage, '').trim(); } else if (data.generated_text) { content = data.generated_text.replace(lastMessage, '').trim(); } else { content = "I'm using Hugging Face AI. How can I help you with UGA-related questions?"; } logger.info('Hugging Face AI response generated', { model: this.huggingFaceModel, responseTime, promptLength: lastMessage.length }); return { content: content || "I'm here to help with UGA questions. What would you like to know?", metadata: { huggingFaceModel: this.huggingFaceModel, responseTime, tokens: content.length } }; } catch (error) { logger.error('Hugging Face AI service error:', error); // Fallback response return { content: `I'm using Hugging Face AI (${this.huggingFaceModel}) but there was an issue connecting. How can I help you with UGA-related questions?`, metadata: { huggingFaceModel: this.huggingFaceModel, fallback: true, responseTime: 100 } }; } } formatMessagesForOllama(messages) { // Convert chat format to a single prompt for Ollama let prompt = ''; for (const message of messages) { if (message.role === 'system') { prompt += `System: ${message.content}\n\n`; } else if (message.role === 'user') { prompt += `Human: ${message.content}\n\n`; } else if (message.role === 'assistant') { prompt += `Assistant: ${message.content}\n\n`; } } prompt += 'Assistant: '; return prompt; } async generateResponse(messages, userContext = {}) { // Check for quick responses first const lastUserMessage = messages[messages.length - 1]?.content || ''; const quickResponse = this.getQuickResponse(lastUserMessage); if (quickResponse) { return { content: quickResponse, metadata: { quickResponse: true, responseTime: 1, aiProvider: 'built-in' } }; } // PRIORITY 1: Route to local AI if enabled (recommended) if (this.useLocal) { logger.info('Using Local AI (Ollama) for response generation'); return this.generateLocalResponse(messages, userContext); } // PRIORITY 2: Route to Hugging Face if enabled (fallback) if (this.useHuggingFace && this.huggingFaceApiKey) { logger.info('Using Hugging Face AI for response generation'); return this.generateHuggingFaceResponse(messages, userContext); } // PRIORITY 3: Check if OpenAI is available (last resort) if (!openai) { logger.warn('No AI service configured - all providers disabled or unavailable'); return { content: `**edi.chat Local AI Setup Required** I'm the UGA Assistant, but I need an AI provider to give you intelligent responses. **Recommended Setup (Private & Free)**: • Install Ollama: \`curl -fsSL https://ollama.com/install.sh | sh\` • Start Ollama: \`ollama serve\` • Pull a model: \`ollama pull llama3:8b\` • Set USE_LOCAL_AI=true **Quick Test Questions**: • "What is UGA's mascot?" • "How do I register for classes?" • "Where is the Miller Learning Center?" Check the LOCAL_AI_SETUP.md guide for complete instructions.`, metadata: { fallback: true, responseTime: 1, aiProvider: 'none', setupRequired: true } }; } try { const startTime = Date.now(); // Check if we need to search for current information const needsWebSearch = this.shouldUseWebSearch(lastUserMessage); let searchContext = ''; if (needsWebSearch) { searchContext = await this.performWebSearch(lastUserMessage); } // Prepare system message with UGA context and search results const systemMessage = { role: 'system', content: this.ugaSystemPrompt + this.buildContextualPrompt(userContext) + (searchContext ? `\n\nCURRENT WEB SEARCH RESULTS:\n${searchContext}` : '') }; // Prepare conversation messages const conversationMessages = [systemMessage, ...messages]; const completion = await openai.chat.completions.create({ model: process.env.OPENAI_MODEL || 'gpt-4', messages: conversationMessages, max_tokens: parseInt(process.env.MAX_TOKENS) || 1000, temperature: parseFloat(process.env.AI_TEMPERATURE) || 0.7, top_p: 0.9, frequency_penalty: 0.1, presence_penalty: 0.1, user: userContext.userId || 'anonymous' }); const responseTime = Date.now() - startTime; const response = completion.choices[0].message; // Extract metadata const metadata = { model: completion.model, tokens: completion.usage.total_tokens, responseTime, finishReason: completion.choices[0].finish_reason }; // Analyze intent and entities const analysis = await this.analyzeMessage(messages[messages.length - 1]?.content); logger.info('AI response generated', { userId: userContext.userId, tokens: metadata.tokens, responseTime: metadata.responseTime, intent: analysis.intent }); return { content: response.content, metadata: { ...metadata, ...analysis, ugaSystemUsed: this.detectUgaSystem(messages[messages.length - 1]?.content) } }; } catch (error) { logger.error('AI service error:', error); // TEMPORARY: Provide mock response when API key is invalid (development mode) if (error.code === 'invalid_api_key') { logger.warn('Using mock AI response due to invalid API key (development mode)'); return { content: "I'm a mock AI response for development mode. The OpenAI API key is not configured properly, but the chat system is working correctly. Please configure a valid OpenAI API key in production.", metadata: { mockResponse: true, tokens: 0, responseTime: 100 } }; } throw new Error('Failed to generate AI response'); } } buildContextualPrompt(userContext) { let contextPrompt = '\n\nUSER CONTEXT:\n'; if (userContext.role) { contextPrompt += `- Role: ${userContext.role}\n`; } if (userContext.college) { contextPrompt += `- College: ${userContext.college}\n`; } if (userContext.major) { contextPrompt += `- Major: ${userContext.major}\n`; } if (userContext.classification) { contextPrompt += `- Classification: ${userContext.classification}\n`; } // Add current semester info if available const currentSemester = this.getCurrentSemester(); contextPrompt += `- Current Semester: ${currentSemester}\n`; return contextPrompt; } async analyzeMessage(content) { try { // Simple intent classification based on keywords const intents = { 'grades': ['grade', 'gpa', 'transcript', 'score'], 'courses': ['course', 'class', 'schedule', 'syllabus'], 'registration': ['register', 'enroll', 'drop', 'add', 'waitlist'], 'technical': ['elc', 'athena', 'myid', 'password', 'login', 'access'], 'campus': ['dining', 'parking', 'library', 'gym', 'recreation'], 'financial': ['tuition', 'fee', 'payment', 'financial aid', 'scholarship', 'fafsa', 'hope', 'billing'], 'housing': ['housing', 'dorm', 'residence', 'roommate', 'application'], 'dining': ['meal plan', 'dining', 'food', 'bulldog bucks', 'niche', 'ecv'], 'academic': ['degree', 'graduation', 'advisor', 'major', 'minor'] }; let detectedIntent = 'general'; let confidence = 0; for (const [intent, keywords] of Object.entries(intents)) { const matches = keywords.filter(keyword => content.toLowerCase().includes(keyword) ).length; const currentConfidence = matches / keywords.length; if (currentConfidence > confidence) { confidence = currentConfidence; detectedIntent = intent; } } // Extract entities (simple keyword extraction) const entities = this.extractEntities(content); return { intent: detectedIntent, confidence, entities }; } catch (error) { logger.error('Message analysis error:', error); return { intent: 'general', confidence: 0, entities: [] }; } } extractEntities(content) { const entities = []; // Extract course codes (e.g., CSCI 1301, MATH 2250) const coursePattern = /\b[A-Z]{3,4}\s*\d{4}\b/g; const courses = content.match(coursePattern); if (courses) { entities.push(...courses.map(course => ({ type: 'course', value: course }))); } // Extract semesters const semesterPattern = /\b(fall|spring|summer)\s*\d{4}\b/gi; const semesters = content.match(semesterPattern); if (semesters) { entities.push(...semesters.map(sem => ({ type: 'semester', value: sem }))); } // Extract UGA systems const ugaSystems = ['elc', 'athena', 'myid', 'archpass']; ugaSystems.forEach(system => { if (content.toLowerCase().includes(system)) { entities.push({ type: 'uga_system', value: system }); } }); return entities; } detectUgaSystem(content) { const lowerContent = content.toLowerCase(); if (lowerContent.includes('elc') || lowerContent.includes('elearning')) { return 'eLC'; } else if (lowerContent.includes('athena')) { return 'Athena'; } else if (lowerContent.includes('myid') || lowerContent.includes('archpass')) { return 'MyID'; } else if (lowerContent.includes('email') || lowerContent.includes('ugamail')) { return 'UGAMail'; } return null; } getCurrentSemester() { const now = new Date(); const month = now.getMonth() + 1; // getMonth() returns 0-11 const year = now.getFullYear(); if (month >= 8 && month <= 12) { return `Fall ${year}`; } else if (month >= 1 && month <= 5) { return `Spring ${year}`; } else { return `Summer ${year}`; } } async generateTitle(messages) { try { const userMessage = messages.find(msg => msg.role === 'user'); if (!userMessage) return 'New Conversation'; const completion = await openai.chat.completions.create({ model: 'gpt-3.5-turbo', messages: [ { role: 'system', content: 'Generate a brief, descriptive title (max 6 words) for this conversation based on the user\'s question.' }, { role: 'user', content: userMessage.content } ], max_tokens: 20, temperature: 0.3 }); return completion.choices[0].message.content.trim().replace(/['"]/g, ''); } catch (error) { logger.error('Title generation error:', error); return 'New Conversation'; } } // Specialized responses for UGA-specific queries getUgaSpecificResponse(intent, entities) { const responses = { 'elc_help': `For eLC (eLearning Commons) support: 1. Visit https://elc.uga.edu for direct access 2. Use your MyID credentials to log in 3. Enable ArchPass two-step authentication if prompted 4. For technical issues, contact EITS at 706-542-3106 5. Check the eLC Help page at https://help.elc.uga.edu/`, 'athena_help': `For Athena access: 1. Go to https://athena.uga.edu 2. Use your MyID and password 3. Complete ArchPass verification 4. Note: Off-campus access may be limited due to vendor issues 5. For assistance, visit the EITS Help Desk or call 706-542-3106`, 'myid_help': `MyID Account Information: 1. Your MyID is your primary UGA login 2. Password must be 10-16 characters with 3 types of characters 3. ArchPass (Duo) is required for most UGA systems 4. Reset password at https://myid.uga.edu 5. For account issues, contact EITS at 706-542-3106` }; return responses[intent] || null; } shouldUseWebSearch(message) { const searchKeywords = [ 'current', 'latest', 'recent', 'today', 'now', 'this year', '2024', '2025', 'news', 'events', 'schedule', 'calendar', 'registration dates', 'deadline', 'weather', 'traffic', 'construction', 'closure', 'hours', 'open' ]; const lowerMessage = message.toLowerCase(); return searchKeywords.some(keyword => lowerMessage.includes(keyword)); } getQuickResponse(message) { const lowerMessage = message.toLowerCase().trim(); // Greeting responses const greetingPatterns = [ /^(hi|hello|hey|yo|sup)$/, /^(hi|hello|hey|yo|sup)\s*(there|uga|assistant|chatbot)?$/, /^good\s*(morning|afternoon|evening)$/ ]; const greetingResponses = [ "Hi there! I'm your UGA Assistant. How can I help you today?", "Hello! Ready to help with anything UGA-related. What do you need?", "Hey! I'm here to help with questions about UGA. What's up?", "Hi! I'm the UGA Assistant. What can I help you with?" ]; // Check for greetings for (const pattern of greetingPatterns) { if (pattern.test(lowerMessage)) { return greetingResponses[Math.floor(Math.random() * greetingResponses.length)]; } } // "What's going on" responses if (/what'?s\s*(going\s*on|up|happening)/.test(lowerMessage)) { const whatsUpResponses = [ "Just here ready to help UGA students! What do you need assistance with?", "Nothing much - just waiting to help with your UGA questions! What's on your mind?", "Ready to assist with anything UGA-related. What brings you here today?" ]; return whatsUpResponses[Math.floor(Math.random() * whatsUpResponses.length)]; } // "What is this" or "what are you" responses if (/what\s*(is\s*this|are\s*you|can\s*you\s*do)/.test(lowerMessage)) { return "I'm the UGA Assistant - an AI chatbot designed to help University of Georgia students, faculty, and staff with questions about campus life, academics, registration, and more. How can I help you?"; } // Thank you responses if (/^(thanks|thank\s*you|thx)$/i.test(lowerMessage)) { const thankYouResponses = [ "You're welcome! Go Dawgs! 🐶", "Happy to help! Let me know if you need anything else.", "Anytime! That's what I'm here for." ]; return thankYouResponses[Math.floor(Math.random() * thankYouResponses.length)]; } // No quick response found return null; } async performWebSearch(query, userContext = {}) { try { logger.info('Performing web search', { query, userId: userContext.userId }); // Check cache first const cachedResult = searchCacheService.get(query, { searchType: 'general' }); if (cachedResult) { logger.info('Using cached search result', { query }); return this.formatSearchResultsForAI(cachedResult); } // Enhance query with UGA-specific context const enhancedQuery = ugaSearchEnhancements.enhanceQuery(query); const searchFilters = ugaSearchEnhancements.buildSearchFilters(query); // Perform search const searchOptions = { ugaOnly: searchFilters.ugaOnly, maxResults: 5, userId: userContext.userId }; const searchResult = await webSearchService.search(enhancedQuery, searchOptions); if (searchResult.success) { // Process UGA-specific results const processedResults = ugaSearchEnhancements.processUGAResults( searchResult.results, query ); const enhancedResult = { ...searchResult, results: processedResults }; // Cache the result searchCacheService.set(query, searchOptions, enhancedResult); return this.formatSearchResultsForAI(enhancedResult); } else { logger.warn('Web search failed', { query, error: searchResult.message }); return `Web search for "${query}" was unsuccessful. ${searchResult.message}`; } } catch (error) { logger.error('Web search error:', error); return `Web search encountered an error: ${error.message}. Proceeding with available knowledge.`; } } formatSearchResultsForAI(searchResult) { if (!searchResult || !searchResult.results || searchResult.results.length === 0) { return 'No current web search results found.'; } let formattedResults = `CURRENT WEB SEARCH RESULTS (${searchResult.provider}):\n\n`; searchResult.results.slice(0, 3).forEach((result, index) => { formattedResults += `${index + 1}. **${result.title}**\n`; formattedResults += ` Source: ${result.ugaSource || 'UGA'} (${result.sourceType || 'official'})\n`; formattedResults += ` URL: ${result.url}\n`; formattedResults += ` Summary: ${result.snippet || 'No summary available'}\n`; if (result.termExplanations && Object.keys(result.termExplanations).length > 0) { formattedResults += ` Terms: ${Object.entries(result.termExplanations) .map(([term, explanation]) => `${term} (${explanation})`) .join(', ')}\n`; } formattedResults += '\n'; }); // Add key information if available if (searchResult.keyInfo) { if (searchResult.keyInfo.dates && searchResult.keyInfo.dates.length > 0) { formattedResults += `Important Dates: ${searchResult.keyInfo.dates.join(', ')}\n`; } if (searchResult.keyInfo.contacts && searchResult.keyInfo.contacts.length > 0) { formattedResults += `Contact Info: ${searchResult.keyInfo.contacts.join(', ')}\n`; } } formattedResults += `\nSearch performed at: ${new Date().toLocaleString()}\n`; formattedResults += 'Please use this current information to supplement your knowledge when responding.\n'; return formattedResults; } buildSearchQuery(userMessage) { // Extract key terms and build focused search query const query = userMessage .replace(/[^\w\s]/g, ' ') .split(' ') .filter(word => word.length > 2) .slice(0, 5) .join(' '); return `UGA University of Georgia ${query}`; } } module.exports = new AIService();