const fetch = require('node-fetch'); const logger = require('../utils/logger'); class WebSearchService { constructor() { // Configuration for different search providers this.config = { // Google Custom Search API google: { apiKey: process.env.GOOGLE_SEARCH_API_KEY, searchEngineId: process.env.GOOGLE_SEARCH_ENGINE_ID, endpoint: 'https://www.googleapis.com/customsearch/v1' }, // Bing Search API bing: { apiKey: process.env.BING_SEARCH_API_KEY, endpoint: 'https://api.bing.microsoft.com/v7.0/search' }, // SearXNG (Self-hosted or public instance) searxng: { endpoint: process.env.SEARXNG_URL || 'https://searx.org', instance: process.env.SEARXNG_INSTANCE || 'searx.org' } }; // Cache for search results (in-memory, could be Redis in production) this.searchCache = new Map(); this.cacheTimeout = 30 * 60 * 1000; // 30 minutes in milliseconds // Rate limiting this.rateLimiter = new Map(); this.rateLimitWindow = 60 * 1000; // 1 minute this.maxRequestsPerWindow = 10; // UGA-specific search patterns this.ugaPatterns = { news: ['uga news', 'university of georgia news', 'athens clarke news'], events: ['uga events', 'university of georgia events', 'uga calendar'], academics: ['uga academic calendar', 'uga registration', 'uga classes'], dining: ['uga dining', 'uga meal plans', 'uga food'], housing: ['uga housing', 'uga residence halls', 'uga dorms'], athletics: ['uga athletics', 'georgia bulldogs', 'uga sports'], admissions: ['uga admissions', 'uga applications', 'uga requirements'], campus: ['uga campus', 'athens georgia', 'uga facilities'] }; logger.info('WebSearchService initialized', { googleEnabled: !!this.config.google.apiKey, bingEnabled: !!this.config.bing.apiKey, searxngEnabled: !!this.config.searxng.endpoint }); } /** * Main search method that determines the best provider and executes search */ async search(query, options = {}) { try { const searchId = this.generateSearchId(query, options); // Check cache first const cachedResult = this.getCachedResult(searchId); if (cachedResult && !options.forceRefresh) { logger.info('Returning cached search result', { query, searchId }); return cachedResult; } // Check rate limiting if (!this.checkRateLimit(options.userId || 'anonymous')) { throw new Error('Rate limit exceeded. Please try again later.'); } // Enhance query for UGA-specific searches const enhancedQuery = this.enhanceUGAQuery(query, options); // Try different search providers in order of preference let searchResult = null; // Priority 1: Google Custom Search (most reliable) if (this.config.google.apiKey && this.config.google.searchEngineId) { try { searchResult = await this.googleSearch(enhancedQuery, options); logger.info('Google search successful', { query: enhancedQuery }); } catch (error) { logger.warn('Google search failed, trying next provider', { error: error.message }); } } // Priority 2: Bing Search API (fallback) if (!searchResult && this.config.bing.apiKey) { try { searchResult = await this.bingSearch(enhancedQuery, options); logger.info('Bing search successful', { query: enhancedQuery }); } catch (error) { logger.warn('Bing search failed, trying next provider', { error: error.message }); } } // Priority 3: SearXNG (open source fallback) if (!searchResult) { try { searchResult = await this.searxngSearch(enhancedQuery, options); logger.info('SearXNG search successful', { query: enhancedQuery }); } catch (error) { logger.warn('SearXNG search failed', { error: error.message }); } } if (!searchResult) { throw new Error('All search providers failed'); } // Process and enhance results const processedResult = this.processSearchResults(searchResult, query, options); // Cache the result this.cacheResult(searchId, processedResult); return processedResult; } catch (error) { logger.error('Web search error:', error); throw new Error(`Search failed: ${error.message}`); } } /** * Google Custom Search implementation */ async googleSearch(query, options = {}) { const params = new URLSearchParams({ key: this.config.google.apiKey, cx: this.config.google.searchEngineId, q: query, num: options.maxResults || 5, safe: 'active' }); // Add site restriction for UGA-specific searches if (options.ugaOnly) { params.append('siteSearch', 'uga.edu'); params.append('siteSearchFilter', 'i'); // include } const response = await fetch(`${this.config.google.endpoint}?${params}`, { headers: { 'User-Agent': 'UGA-edi.chat/1.0' }, timeout: 10000 }); if (!response.ok) { throw new Error(`Google Search API error: ${response.status}`); } const data = await response.json(); return { provider: 'google', query, results: data.items || [], totalResults: parseInt(data.searchInformation?.totalResults) || 0, searchTime: parseFloat(data.searchInformation?.searchTime) || 0 }; } /** * Bing Search API implementation */ async bingSearch(query, options = {}) { const params = new URLSearchParams({ q: query, count: options.maxResults || 5, safeSearch: 'Moderate' }); // Add site restriction for UGA-specific searches if (options.ugaOnly) { params.set('q', `${query} site:uga.edu`); } const response = await fetch(`${this.config.bing.endpoint}?${params}`, { headers: { 'Ocp-Apim-Subscription-Key': this.config.bing.apiKey, 'User-Agent': 'UGA-edi.chat/1.0' }, timeout: 10000 }); if (!response.ok) { throw new Error(`Bing Search API error: ${response.status}`); } const data = await response.json(); // Convert Bing format to standard format const results = (data.webPages?.value || []).map(item => ({ title: item.name, link: item.url, snippet: item.snippet, displayLink: item.displayUrl })); return { provider: 'bing', query, results, totalResults: data.webPages?.totalEstimatedMatches || 0, searchTime: 0 }; } /** * SearXNG search implementation (open source) */ async searxngSearch(query, options = {}) { const params = new URLSearchParams({ q: query, format: 'json', engines: 'google,bing,duckduckgo', lang: 'en' }); // Add site restriction for UGA-specific searches if (options.ugaOnly) { params.set('q', `${query} site:uga.edu`); } const response = await fetch(`${this.config.searxng.endpoint}/search?${params}`, { headers: { 'User-Agent': 'UGA-edi.chat/1.0' }, timeout: 15000 }); if (!response.ok) { throw new Error(`SearXNG error: ${response.status}`); } const data = await response.json(); // Convert SearXNG format to standard format and limit results const results = (data.results || []) .slice(0, options.maxResults || 5) .map(item => ({ title: item.title, link: item.url, snippet: item.content || '', displayLink: item.pretty_url || item.url })); return { provider: 'searxng', query, results, totalResults: data.results?.length || 0, searchTime: 0 }; } /** * Detect if a query needs current/live information */ shouldUseWebSearch(message) { const currentInfoKeywords = [ // Time-sensitive keywords 'current', 'latest', 'recent', 'today', 'now', 'this week', 'this month', 'new', 'upcoming', 'updated', '2024', '2025', // News and events 'news', 'events', 'happening', 'schedule', 'calendar', 'announcement', // UGA-specific time-sensitive 'registration', 'deadline', 'apply', 'application', 'semester', 'academic calendar', 'finals', 'break', 'graduation', // Services and hours 'hours', 'open', 'closed', 'available', 'operating', 'weather', 'traffic', 'construction', 'closure', // Dining and facilities 'dining hours', 'gym hours', 'library hours', 'menu' ]; const ugaTimeKeywords = [ 'uga news', 'uga events', 'uga schedule', 'uga calendar', 'registration dates', 'academic calendar', 'uga deadlines', 'uga dining hours', 'uga facilities', 'uga construction' ]; const lowerMessage = message.toLowerCase(); // Check for general time-sensitive keywords const hasCurrentKeywords = currentInfoKeywords.some(keyword => lowerMessage.includes(keyword) ); // Check for UGA-specific time-sensitive keywords const hasUGATimeKeywords = ugaTimeKeywords.some(keyword => lowerMessage.includes(keyword) ); // Also check for question patterns that typically need current info const currentQuestionPatterns = [ /what.*happening.*uga/i, /when.*registration/i, /what.*hours.*uga/i, /what.*new.*uga/i, /uga.*today/i, /current.*uga/i ]; const hasCurrentQuestionPattern = currentQuestionPatterns.some(pattern => pattern.test(message) ); return hasCurrentKeywords || hasUGATimeKeywords || hasCurrentQuestionPattern; } /** * Enhance query with UGA-specific terms */ enhanceUGAQuery(query, options = {}) { const lowerQuery = query.toLowerCase(); let enhancedQuery = query; // Add UGA context if not already present if (!lowerQuery.includes('uga') && !lowerQuery.includes('university of georgia')) { // Determine query category and enhance accordingly for (const [category, patterns] of Object.entries(this.ugaPatterns)) { if (patterns.some(pattern => lowerQuery.includes(pattern.split(' ').slice(-1)[0]))) { enhancedQuery = `UGA ${query}`; break; } } // If no specific pattern matched, add general UGA context if (enhancedQuery === query) { enhancedQuery = `University of Georgia UGA ${query}`; } } // Add Athens context for location-based queries if (lowerQuery.includes('dining') || lowerQuery.includes('restaurant') || lowerQuery.includes('food') || lowerQuery.includes('near')) { enhancedQuery += ' Athens Georgia'; } return enhancedQuery; } /** * Process and summarize search results for AI context */ processSearchResults(searchResult, originalQuery, options = {}) { const { results, provider, totalResults } = searchResult; if (!results || results.length === 0) { return { success: false, message: 'No search results found', provider, query: originalQuery, results: [] }; } // Create a summary for AI consumption const summary = this.createSearchSummary(results, originalQuery); // Extract key information const keyInfo = this.extractKeyInformation(results, originalQuery); return { success: true, provider, query: originalQuery, summary, keyInfo, results: results.map(result => ({ title: result.title, url: result.link, snippet: result.snippet, domain: result.displayLink })), totalResults, searchTime: searchResult.searchTime, timestamp: new Date().toISOString() }; } /** * Create a concise summary of search results for AI context */ createSearchSummary(results, query) { const summaryPoints = results.slice(0, 3).map(result => { const title = result.title; const snippet = result.snippet || ''; return `• ${title}: ${snippet.substring(0, 150)}${snippet.length > 150 ? '...' : ''}`; }); return `Search results for "${query}":\n${summaryPoints.join('\n')}`; } /** * Extract key information from search results */ extractKeyInformation(results, query) { const keyInfo = { ugaOfficial: [], news: [], events: [], dates: [], contacts: [] }; results.forEach(result => { const text = `${result.title} ${result.snippet}`.toLowerCase(); const url = result.link || ''; // UGA official sources if (url.includes('uga.edu')) { keyInfo.ugaOfficial.push({ title: result.title, url: result.link, snippet: result.snippet }); } // News items if (text.includes('news') || text.includes('announcement') || text.includes('update')) { keyInfo.news.push(result.title); } // Events if (text.includes('event') || text.includes('calendar') || text.includes('schedule')) { keyInfo.events.push(result.title); } // Extract dates const dateMatches = text.match(/\b\d{1,2}\/\d{1,2}\/\d{4}\b|\b\d{4}-\d{2}-\d{2}\b/g); if (dateMatches) { keyInfo.dates.push(...dateMatches); } // Extract contact information const phoneMatches = text.match(/\b\d{3}-\d{3}-\d{4}\b/g); if (phoneMatches) { keyInfo.contacts.push(...phoneMatches); } }); return keyInfo; } /** * Generate unique search ID for caching */ generateSearchId(query, options) { const optionsString = JSON.stringify(options); return `search_${Buffer.from(query + optionsString).toString('base64')}`; } /** * Get cached search result */ getCachedResult(searchId) { const cached = this.searchCache.get(searchId); if (cached && (Date.now() - cached.timestamp) < this.cacheTimeout) { return cached.result; } return null; } /** * Cache search result */ cacheResult(searchId, result) { this.searchCache.set(searchId, { result, timestamp: Date.now() }); // Clean old cache entries periodically if (this.searchCache.size > 100) { this.cleanCache(); } } /** * Clean expired cache entries */ cleanCache() { const now = Date.now(); for (const [key, value] of this.searchCache.entries()) { if ((now - value.timestamp) > this.cacheTimeout) { this.searchCache.delete(key); } } } /** * Check rate limiting */ checkRateLimit(userId) { const now = Date.now(); const userRequests = this.rateLimiter.get(userId) || []; // Remove old requests outside the window const recentRequests = userRequests.filter(timestamp => (now - timestamp) < this.rateLimitWindow ); if (recentRequests.length >= this.maxRequestsPerWindow) { return false; } // Add current request recentRequests.push(now); this.rateLimiter.set(userId, recentRequests); return true; } /** * Get search configuration status */ getStatus() { return { providers: { google: { enabled: !!(this.config.google.apiKey && this.config.google.searchEngineId), configured: !!(this.config.google.apiKey && this.config.google.searchEngineId) }, bing: { enabled: !!this.config.bing.apiKey, configured: !!this.config.bing.apiKey }, searxng: { enabled: !!this.config.searxng.endpoint, configured: !!this.config.searxng.endpoint } }, cache: { size: this.searchCache.size, maxAge: this.cacheTimeout }, rateLimit: { windowMs: this.rateLimitWindow, maxRequests: this.maxRequestsPerWindow } }; } } module.exports = new WebSearchService();