Spaces:
Sleeping

edi.chat.test / backend /src /middleware /searchDetection.js
Claude Code Bot
Fix AI responses - implement direct Ollama integration with no fallbacks
7851df6
Raw History Blame Contribute Delete
8.02 kB
const webSearchService = require('../services/webSearchService');
const logger = require('../utils/logger');
/**
* Middleware to detect if a user query needs current/live information via web search
*/
class SearchDetectionMiddleware {
constructor() {
// Patterns that indicate need for current information
this.currentInfoPatterns = [
// Time-sensitive keywords
/\b(current|latest|recent|today|now|this\s+(week|month|year|semester))\b/i,
/\b(new|updated|upcoming|2024|2025)\b/i,
// News and events
/\b(news|events|happening|schedule|calendar|announcement)\b/i,
// UGA-specific time-sensitive
/\b(registration|deadline|apply|application|semester)\b/i,
/\b(academic\s+calendar|finals|break|graduation)\b/i,
// Services and hours
/\b(hours|open|closed|available|operating)\b/i,
/\b(weather|traffic|construction|closure)\b/i,
// Dining and facilities
/\b(dining\s+hours|gym\s+hours|library\s+hours|menu)\b/i
];
// UGA-specific patterns that typically need current info
this.ugaCurrentPatterns = [
/uga\s+(news|events|schedule|calendar)/i,
/registration\s+dates/i,
/uga\s+deadlines/i,
/uga\s+(dining|facilities|construction)/i,
/what.*happening.*uga/i,
/when.*registration/i,
/what.*hours.*uga/i,
/what.*new.*uga/i,
/uga.*today/i,
/current.*uga/i
];
// Patterns that indicate academic/static information (don't need web search)
this.staticInfoPatterns = [
/\b(what\s+is|define|explain|how\s+to|tutorial|guide)\b/i,
/\b(history|founded|established|background)\b/i,
/\b(location|address|phone|contact\s+info)\b/i,
/\b(mascot|colors|traditions|fight\s+song)\b/i
];
logger.info('SearchDetectionMiddleware initialized');
}
/**
* Analyze message to determine if web search is needed
*/
analyzeSearchNeed(message, userContext = {}) {
const analysis = {
needsWebSearch: false,
confidence: 0,
reasons: [],
searchType: null,
ugaSpecific: false,
queryEnhancements: {}
};
const lowerMessage = message.toLowerCase();
// Check if it's asking for static/historical information (override web search)
const hasStaticPattern = this.staticInfoPatterns.some(pattern => pattern.test(message));
if (hasStaticPattern) {
analysis.needsWebSearch = false;
analysis.reasons.push('Static/historical information query');
return analysis;
}
// Check for current information patterns
let currentInfoScore = 0;
this.currentInfoPatterns.forEach(pattern => {
if (pattern.test(message)) {
currentInfoScore += 1;
analysis.reasons.push(`Matched current info pattern: ${pattern}`);
}
});
// Check for UGA-specific current patterns
let ugaCurrentScore = 0;
this.ugaCurrentPatterns.forEach(pattern => {
if (pattern.test(message)) {
ugaCurrentScore += 2; // Higher weight for UGA-specific patterns
analysis.ugaSpecific = true;
analysis.reasons.push(`Matched UGA current pattern: ${pattern}`);
}
});
// Calculate total score and confidence
const totalScore = currentInfoScore + ugaCurrentScore;
analysis.confidence = Math.min(totalScore * 0.2, 1.0); // Scale to 0-1
// Determine if web search is needed
analysis.needsWebSearch = totalScore >= 1;
// Determine search type based on content
if (lowerMessage.includes('news')) {
analysis.searchType = 'news';
} else if (lowerMessage.includes('event') || lowerMessage.includes('calendar')) {
analysis.searchType = 'events';
} else if (lowerMessage.includes('registration') || lowerMessage.includes('deadline')) {
analysis.searchType = 'academic';
} else if (lowerMessage.includes('dining') || lowerMessage.includes('hours')) {
analysis.searchType = 'services';
} else {
analysis.searchType = 'general';
}
// Add query enhancements
if (analysis.needsWebSearch) {
analysis.queryEnhancements = this.generateQueryEnhancements(message, analysis.searchType);
}
logger.info('Search need analysis completed', {
message: message.substring(0, 100),
needsWebSearch: analysis.needsWebSearch,
confidence: analysis.confidence,
searchType: analysis.searchType,
ugaSpecific: analysis.ugaSpecific
});
return analysis;
}
/**
* Generate query enhancements based on search type
*/
generateQueryEnhancements(message, searchType) {
const enhancements = {
ugaOnly: false,
maxResults: 5,
additionalTerms: []
};
const lowerMessage = message.toLowerCase();
// UGA-specific search enhancements
if (lowerMessage.includes('uga') || lowerMessage.includes('university of georgia')) {
enhancements.ugaOnly = true;
enhancements.additionalTerms.push('site:uga.edu');
}
// Search type specific enhancements
switch (searchType) {
case 'news':
enhancements.additionalTerms.push('news', 'announcement');
enhancements.maxResults = 3;
break;
case 'events':
enhancements.additionalTerms.push('events', 'calendar', 'schedule');
enhancements.maxResults = 5;
break;
case 'academic':
enhancements.additionalTerms.push('registration', 'academic', 'semester');
enhancements.ugaOnly = true;
break;
case 'services':
enhancements.additionalTerms.push('hours', 'services');
enhancements.maxResults = 3;
break;
default:
enhancements.maxResults = 5;
}
return enhancements;
}
/**
* Express middleware function
*/
middleware() {
return (req, res, next) => {
if (req.body && req.body.message) {
const analysis = this.analyzeSearchNeed(req.body.message, req.user);
req.searchAnalysis = analysis;
logger.info('Search detection middleware applied', {
path: req.path,
needsWebSearch: analysis.needsWebSearch,
confidence: analysis.confidence
});
}
next();
};
}
/**
* Check if query is UGA-specific
*/
isUGASpecific(message) {
const ugaKeywords = [
'uga', 'university of georgia', 'georgia bulldogs', 'athens',
'dawgs', 'bulldog', 'sanford stadium', 'tate center',
'elc', 'athena', 'myid', 'archpass'
];
const lowerMessage = message.toLowerCase();
return ugaKeywords.some(keyword => lowerMessage.includes(keyword));
}
/**
* Determine search priority based on query analysis
*/
getSearchPriority(analysis) {
if (analysis.ugaSpecific && analysis.confidence > 0.7) {
return 'high';
} else if (analysis.confidence > 0.5) {
return 'medium';
} else if (analysis.needsWebSearch) {
return 'low';
}
return 'none';
}
/**
* Generate search suggestions for queries that might benefit from web search
*/
generateSearchSuggestions(message) {
const suggestions = [];
const lowerMessage = message.toLowerCase();
// Suggest more specific queries for better results
if (lowerMessage.includes('uga') && lowerMessage.includes('event')) {
suggestions.push('Try: "UGA events this week" for current events');
}
if (lowerMessage.includes('registration')) {
suggestions.push('Try: "UGA registration dates Spring 2025" for specific dates');
}
if (lowerMessage.includes('dining')) {
suggestions.push('Try: "UGA dining hours today" for current hours');
}
if (lowerMessage.includes('news')) {
suggestions.push('Try: "UGA news this week" for recent updates');
}
return suggestions;
}
/**
* Simple boolean check for web search need (for compatibility)
*/
shouldUseWebSearch(message) {
const analysis = this.analyzeSearchNeed(message);
return analysis.needsWebSearch;
}
}
module.exports = new SearchDetectionMiddleware();