Spaces:
Sleeping
Sleeping
Download server.js from edichat/edi.chat.test: direct link, hf CLI and curl.
- Browser
- Download file 61.8 kB
-
https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/server.js
- Command line
-
hf download hf://spaces/edichat/edi.chat.test/server.js
-
curl -L -o server.js https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/server.js
61.8 kB
const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs').promises;
const crypto = require('crypto');
const { HfInference } = require('@huggingface/inference');
const axios = require('axios');
const NodeCache = require('node-cache');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 7860;
// Initialize caching system for web search results
const searchCache = new NodeCache({
stdTTL: parseInt(process.env.WEB_SEARCH_CACHE_TTL) || 1800, // 30 minutes default
checkperiod: 600, // Check for expired keys every 10 minutes
useClones: false
});
// Chat history storage directory
const CHAT_HISTORY_DIR = path.join(__dirname, 'chat_history');
// Ensure chat history directory exists
async function ensureChatHistoryDir() {
try {
await fs.access(CHAT_HISTORY_DIR);
} catch {
await fs.mkdir(CHAT_HISTORY_DIR, { recursive: true });
}
}
// Chat history data structures and utilities
function generateSessionId() {
return crypto.randomUUID();
}
function getUserHistoryFile(userId) {
return path.join(CHAT_HISTORY_DIR, `user_${userId}.json`);
}
async function loadUserHistory(userId) {
try {
const historyFile = getUserHistoryFile(userId);
const data = await fs.readFile(historyFile, 'utf8');
return JSON.parse(data);
} catch (error) {
// Return empty history structure if file doesn't exist
return {
userId,
sessions: {},
metadata: {
totalMessages: 0,
totalSessions: 0,
createdAt: new Date().toISOString(),
lastActivity: new Date().toISOString()
}
};
}
}
async function saveUserHistory(userId, history) {
try {
const historyFile = getUserHistoryFile(userId);
history.metadata.lastActivity = new Date().toISOString();
await fs.writeFile(historyFile, JSON.stringify(history, null, 2));
return true;
} catch (error) {
console.error('Error saving user history:', error);
return false;
}
}
function createChatSession(title = null) {
const sessionId = generateSessionId();
return {
id: sessionId,
title: title || `Chat ${new Date().toLocaleDateString()}`,
messages: [],
metadata: {
createdAt: new Date().toISOString(),
lastActivity: new Date().toISOString(),
messageCount: 0,
totalTokens: 0,
avgResponseTime: 0
}
};
}
function addMessageToSession(session, message, sender, metadata = {}) {
const messageObj = {
id: crypto.randomUUID(),
content: message,
sender, // 'user' or 'bot'
timestamp: new Date().toISOString(),
metadata: {
...metadata,
tokens: metadata.tokens || 0,
responseTime: metadata.responseTime || 0
}
};
session.messages.push(messageObj);
session.metadata.lastActivity = new Date().toISOString();
session.metadata.messageCount = session.messages.length;
if (metadata.tokens) {
session.metadata.totalTokens += metadata.tokens;
}
if (metadata.responseTime && sender === 'bot') {
const botMessages = session.messages.filter(m => m.sender === 'bot');
const totalResponseTime = botMessages.reduce((sum, m) => sum + (m.metadata.responseTime || 0), 0);
session.metadata.avgResponseTime = Math.round(totalResponseTime / botMessages.length);
}
// Auto-generate title from first user message if not set
if (!session.title || session.title.startsWith('Chat ')) {
const firstUserMessage = session.messages.find(m => m.sender === 'user');
if (firstUserMessage) {
session.title = firstUserMessage.content.substring(0, 50) +
(firstUserMessage.content.length > 50 ? '...' : '');
}
}
return messageObj;
}
// =================================================================
// WEB SEARCH SERVICE WITH MULTIPLE PROVIDERS
// =================================================================
// Web Search Service Class
class UGAWebSearchService {
constructor() {
this.enableWebSearch = process.env.ENABLE_WEB_SEARCH === 'true';
this.googleApiKey = process.env.GOOGLE_SEARCH_API_KEY;
this.googleEngineId = process.env.GOOGLE_SEARCH_ENGINE_ID;
this.bingApiKey = process.env.BING_SEARCH_API_KEY;
this.searxngUrl = process.env.SEARXNG_URL || 'https://searx.org';
}
// Generate cache key for search queries
generateCacheKey(query, searchType = 'general') {
return `search:${searchType}:${crypto.createHash('md5').update(query.toLowerCase()).digest('hex')}`;
}
// UGA-specific search domains and filters
// Enhanced query building for more specific searches
enhanceSearchQuery(originalQuery, agentType) {
const lowerQuery = originalQuery.toLowerCase();
// Detect specific information types and add targeted keywords
const enhancements = {
hours: ['hours', 'open', 'close', 'schedule', 'time', 'operating'],
location: ['where', 'location', 'address', 'building', 'room'],
contact: ['phone', 'email', 'contact', 'number'],
dates: ['when', 'date', 'deadline', 'calendar'],
costs: ['cost', 'price', 'fee', 'tuition', 'expense'],
requirements: ['requirement', 'prerequisite', 'need', 'must'],
events: ['event', 'happening', 'schedule', 'calendar']
};
let enhancedQuery = originalQuery;
// Add specific terms based on query content
for (const [category, keywords] of Object.entries(enhancements)) {
if (keywords.some(keyword => lowerQuery.includes(keyword))) {
switch (category) {
case 'hours':
enhancedQuery += ' hours schedule operating times open close';
break;
case 'location':
enhancedQuery += ' location address building campus map';
break;
case 'contact':
enhancedQuery += ' contact phone email information';
break;
case 'dates':
enhancedQuery += ' date calendar schedule deadline';
break;
case 'costs':
enhancedQuery += ' cost price fee tuition expense budget';
break;
case 'requirements':
enhancedQuery += ' requirements prerequisites needed criteria';
break;
case 'events':
enhancedQuery += ' events calendar schedule happening activities';
break;
}
break; // Only add one enhancement category
}
}
return enhancedQuery;
}
getUGASearchFilters(agentType) {
const filters = {
academic: {
sites: ['uga.edu', 'bulletin.uga.edu', 'reg.uga.edu', 'admissions.uga.edu'],
keywords: ['University of Georgia', 'UGA', 'course', 'degree', 'academic', 'registration']
},
student_life: {
sites: ['uga.edu', 'housing.uga.edu', 'dining.uga.edu', 'rec.uga.edu', 'studentaffairs.uga.edu'],
keywords: ['University of Georgia', 'UGA', 'campus', 'student life', 'housing', 'dining', 'events']
},
athletics: {
sites: ['georgiadogs.com', 'uga.edu', 'sec.espn.com'],
keywords: ['Georgia Bulldogs', 'UGA athletics', 'Georgia football', 'Georgia basketball', 'SEC']
},
general: {
sites: ['uga.edu', 'georgiadogs.com'],
keywords: ['University of Georgia', 'UGA']
}
};
return filters[agentType] || filters.general;
}
// Google Custom Search API
async searchGoogle(query, agentType = 'general') {
if (!this.googleApiKey || !this.googleEngineId) {
throw new Error('Google Search API not configured');
}
const filters = this.getUGASearchFilters(agentType);
const specificQuery = this.enhanceSearchQuery(query, agentType);
const enhancedQuery = `${specificQuery} ${filters.keywords.join(' OR ')}`;
try {
const response = await axios.get('https://www.googleapis.com/customsearch/v1', {
params: {
key: this.googleApiKey,
cx: this.googleEngineId,
q: enhancedQuery,
num: 8,
safe: 'active'
},
timeout: 10000
});
return this.formatSearchResults(response.data.items || [], 'google', agentType);
} catch (error) {
console.error('Google Search API error:', error.message);
throw error;
}
}
// Bing Search API
async searchBing(query, agentType = 'general') {
if (!this.bingApiKey) {
throw new Error('Bing Search API not configured');
}
const filters = this.getUGASearchFilters(agentType);
const enhancedQuery = `${query} ${filters.keywords.join(' OR ')}`;
try {
const response = await axios.get('https://api.bing.microsoft.com/v7.0/search', {
headers: {
'Ocp-Apim-Subscription-Key': this.bingApiKey
},
params: {
q: enhancedQuery,
count: 8,
safeSearch: 'Moderate',
responseFilter: 'Webpages'
},
timeout: 10000
});
return this.formatSearchResults(response.data.webPages?.value || [], 'bing', agentType);
} catch (error) {
console.error('Bing Search API error:', error.message);
throw error;
}
}
// SearXNG (Free/Open Source Search)
async searchSearXNG(query, agentType = 'general') {
const filters = this.getUGASearchFilters(agentType);
const enhancedQuery = `${query} ${filters.keywords.join(' OR ')}`;
try {
const response = await axios.get(`${this.searxngUrl}/search`, {
params: {
q: enhancedQuery,
format: 'json',
engines: 'google,bing,duckduckgo',
safesearch: 1
},
timeout: 15000,
headers: {
'User-Agent': 'UGA-AI-Assistant/1.0'
}
});
return this.formatSearchResults(response.data.results || [], 'searxng', agentType);
} catch (error) {
console.error('SearXNG Search error:', error.message);
throw error;
}
}
// Format search results consistently across providers
formatSearchResults(results, provider, agentType) {
const filters = this.getUGASearchFilters(agentType);
const formatted = results.slice(0, 6).map(result => {
let title, url, snippet;
if (provider === 'google') {
title = result.title;
url = result.link;
snippet = result.snippet;
} else if (provider === 'bing') {
title = result.name;
url = result.url;
snippet = result.snippet;
} else if (provider === 'searxng') {
title = result.title;
url = result.url;
snippet = result.content;
}
// Score relevance based on UGA domains and keywords
let relevanceScore = 0;
if (filters.sites.some(site => url.includes(site))) {
relevanceScore += 10;
}
if (filters.keywords.some(keyword =>
title.toLowerCase().includes(keyword.toLowerCase()) ||
snippet.toLowerCase().includes(keyword.toLowerCase())
)) {
relevanceScore += 5;
}
return {
title: title || 'No title',
url: url || '',
snippet: snippet || 'No description available',
provider,
relevanceScore,
timestamp: new Date().toISOString()
};
});
// Sort by relevance score
return formatted.sort((a, b) => b.relevanceScore - a.relevanceScore);
}
// Main search function with fallback providers
async search(query, agentType = 'general') {
if (!this.enableWebSearch) {
return {
results: [],
fromCache: false,
provider: 'disabled',
message: 'Web search is disabled'
};
}
// Check cache first
const cacheKey = this.generateCacheKey(query, agentType);
const cachedResults = searchCache.get(cacheKey);
if (cachedResults) {
console.log(`π Returning cached search results for: ${query}`);
return {
results: cachedResults.results,
fromCache: true,
provider: cachedResults.provider,
timestamp: cachedResults.timestamp,
cacheKey
};
}
console.log(`π Searching web for: ${query} (agent: ${agentType})`);
// Try different search providers in order of preference
const providers = [
{ name: 'google', method: () => this.searchGoogle(query, agentType) },
{ name: 'bing', method: () => this.searchBing(query, agentType) },
{ name: 'searxng', method: () => this.searchSearXNG(query, agentType) }
];
for (const provider of providers) {
try {
const results = await provider.method();
if (results && results.length > 0) {
// Cache successful results
const searchData = {
results,
provider: provider.name,
timestamp: new Date().toISOString(),
query,
agentType
};
searchCache.set(cacheKey, searchData);
console.log(`β
Search successful with ${provider.name}: ${results.length} results`);
return {
results,
fromCache: false,
provider: provider.name,
timestamp: searchData.timestamp,
cacheKey
};
}
} catch (error) {
console.error(`β ${provider.name} search failed:`, error.message);
continue; // Try next provider
}
}
// If all providers fail, return empty results
console.log('β All search providers failed');
return {
results: [],
fromCache: false,
provider: 'none',
error: 'All search providers unavailable',
timestamp: new Date().toISOString()
};
}
// Get search suggestions for UGA-specific topics
getUGASearchSuggestions(agentType) {
const suggestions = {
academic: [
'UGA course registration dates',
'UGA degree requirements',
'UGA academic calendar 2024',
'UGA faculty directory',
'UGA graduation requirements'
],
student_life: [
'UGA dining hours',
'UGA campus events this week',
'UGA housing application',
'UGA recreation center hours',
'UGA student organizations'
],
athletics: [
'Georgia Bulldogs football schedule',
'UGA basketball tickets',
'Georgia Bulldogs latest news',
'Sanford Stadium events',
'UGA athletics scores'
],
general: [
'UGA campus map',
'UGA contact information',
'UGA admissions requirements',
'UGA news and announcements',
'UGA academic programs'
]
};
return suggestions[agentType] || suggestions.general;
}
// Search specifically for current UGA information
async searchCurrentUGAInfo(topic, agentType = 'general') {
const currentYear = new Date().getFullYear();
const currentMonth = new Date().toLocaleString('default', { month: 'long' });
const timeBasedQuery = `UGA ${topic} ${currentYear} ${currentMonth} current latest`;
return await this.search(timeBasedQuery, agentType);
}
// Get cache statistics
getCacheStats() {
return {
keys: searchCache.keys().length,
hits: searchCache.getStats().hits,
misses: searchCache.getStats().misses,
ksize: searchCache.getStats().ksize,
vsize: searchCache.getStats().vsize
};
}
// Clear cache (admin function)
clearCache() {
searchCache.flushAll();
return { message: 'Search cache cleared successfully' };
}
}
// Initialize the web search service
const webSearchService = new UGAWebSearchService();
// =================================================================
// END WEB SEARCH SERVICE
// =================================================================
// Middleware
app.use(cors({ origin: '*', credentials: true }));
app.use(express.json({ limit: '10mb' }));
app.use(express.static('.'));
// Initialize Hugging Face client
let hfClient = null;
if (process.env.HUGGINGFACE_API_KEY) {
hfClient = new HfInference(process.env.HUGGINGFACE_API_KEY);
}
// UGA Specialized Agents Configuration
// Load enhanced UGA agents and comprehensive knowledge
const UGA_ENHANCED_AGENTS = require('./uga-enhanced-agents.js');
const UGA_KNOWLEDGE = require('./uga-comprehensive-knowledge.js');
const UGA_AGENTS = UGA_ENHANCED_AGENTS;
// Enhanced Agent Selection Logic
function selectAgent(message) {
const messageLower = message.toLowerCase();
const scores = {};
// High-priority keywords that should strongly influence agent selection
const priorityKeywords = {
'student_life': ['dining', 'food', 'meal', 'eat', 'housing', 'dorm', 'residence', 'clubs', 'organizations', 'greek'],
'athletics': ['football', 'basketball', 'sports', 'athletics', 'game', 'schedule', 'tickets', 'bulldogs', 'dawgs'],
'academic': ['course', 'class', 'degree', 'major', 'graduation', 'gpa', 'transcript', 'registration', 'professor'],
'general': ['admissions', 'apply', 'contact', 'directions', 'map', 'location', 'visit']
};
// Calculate relevance scores for each agent
Object.keys(UGA_AGENTS).forEach(agentKey => {
const agent = UGA_AGENTS[agentKey];
scores[agentKey] = 0;
// Check priority keywords first (higher weight)
if (priorityKeywords[agentKey]) {
priorityKeywords[agentKey].forEach(keyword => {
if (messageLower.includes(keyword)) {
scores[agentKey] += 3; // Higher weight for priority keywords
}
});
}
// Check regular domain keywords
agent.domains.forEach(domain => {
if (messageLower.includes(domain)) {
scores[agentKey] += 1;
}
});
});
// Find the agent with the highest score
const bestAgent = Object.keys(scores).reduce((a, b) =>
scores[a] > scores[b] ? a : b
);
// If no specific matches found, use general agent
return scores[bestAgent] > 0 ? bestAgent : 'general';
}
// Function to extract relevant UGA knowledge based on message content
function getRelevantUGAKnowledge(message, agentType) {
const messageLower = message.toLowerCase();
let relevantKnowledge = [];
// Extract relevant knowledge sections based on agent type and message content
try {
switch (agentType) {
case 'academic':
if (UGA_KNOWLEDGE.academics) {
if (messageLower.includes('college') || messageLower.includes('school') || messageLower.includes('department')) {
relevantKnowledge.push('COLLEGES & SCHOOLS:');
Object.keys(UGA_KNOWLEDGE.academics.colleges).forEach(collegeName => {
const college = UGA_KNOWLEDGE.academics.colleges[collegeName];
relevantKnowledge.push(`- ${collegeName}: ${college.description}`);
if (college.popular_majors) {
relevantKnowledge.push(` Popular majors: ${college.popular_majors.join(', ')}`);
}
});
}
if (messageLower.includes('graduation') || messageLower.includes('requirement') || messageLower.includes('credit')) {
relevantKnowledge.push('\nGRADUATION REQUIREMENTS:');
relevantKnowledge.push(`- Total hours: ${UGA_KNOWLEDGE.academics.graduation_requirements.undergraduate.total_hours}`);
relevantKnowledge.push(`- Core curriculum: ${UGA_KNOWLEDGE.academics.graduation_requirements.undergraduate.core_curriculum} hours`);
relevantKnowledge.push(`- GPA requirement: ${UGA_KNOWLEDGE.academics.graduation_requirements.undergraduate.gpa_requirement}`);
relevantKnowledge.push(`- Residency: ${UGA_KNOWLEDGE.academics.graduation_requirements.undergraduate.residency_requirement}`);
}
}
break;
case 'student_life':
if (UGA_KNOWLEDGE.student_life) {
if (messageLower.includes('dining') || messageLower.includes('food') || messageLower.includes('meal')) {
relevantKnowledge.push('DINING OPTIONS:');
relevantKnowledge.push(`- Dining halls: ${UGA_KNOWLEDGE.student_life.dining.dining_halls.join(', ')}`);
relevantKnowledge.push(`- Popular spots: ${UGA_KNOWLEDGE.student_life.dining.popular_spots.join(', ')}`);
}
if (messageLower.includes('housing') || messageLower.includes('dorm') || messageLower.includes('residence')) {
relevantKnowledge.push('HOUSING:');
relevantKnowledge.push(`- Residence halls: ${UGA_KNOWLEDGE.student_life.housing.residence_halls.join(', ')}`);
relevantKnowledge.push(`- Housing types: ${UGA_KNOWLEDGE.student_life.housing.housing_types.join(', ')}`);
}
if (messageLower.includes('organization') || messageLower.includes('club') || messageLower.includes('greek')) {
relevantKnowledge.push('STUDENT ORGANIZATIONS:');
relevantKnowledge.push(`- Total: ${UGA_KNOWLEDGE.student_life.organizations.total_count}`);
relevantKnowledge.push(`- Greek life: ${UGA_KNOWLEDGE.student_life.organizations.greek_life.fraternities} fraternities, ${UGA_KNOWLEDGE.student_life.organizations.greek_life.sororities} sororities`);
}
}
break;
case 'athletics':
if (UGA_KNOWLEDGE.athletics) {
if (messageLower.includes('football')) {
relevantKnowledge.push('FOOTBALL:');
relevantKnowledge.push(`- Stadium: ${UGA_KNOWLEDGE.athletics.sports.football.stadium} (capacity: ${UGA_KNOWLEDGE.athletics.sports.football.capacity.toLocaleString()})`);
relevantKnowledge.push(`- Coach: ${UGA_KNOWLEDGE.athletics.sports.football.coach}`);
relevantKnowledge.push(`- National Championships: ${UGA_KNOWLEDGE.athletics.sports.football.national_championships.join(', ')}`);
}
if (messageLower.includes('basketball')) {
relevantKnowledge.push('BASKETBALL:');
relevantKnowledge.push(`- Arena: ${UGA_KNOWLEDGE.athletics.sports.basketball.mens.arena} (capacity: ${UGA_KNOWLEDGE.athletics.sports.basketball.mens.capacity.toLocaleString()})`);
relevantKnowledge.push(`- Men's Coach: ${UGA_KNOWLEDGE.athletics.sports.basketball.mens.coach}`);
relevantKnowledge.push(`- Women's Coach: ${UGA_KNOWLEDGE.athletics.sports.basketball.womens.coach}`);
}
}
break;
case 'general':
if (UGA_KNOWLEDGE.campus || UGA_KNOWLEDGE.admissions) {
if (messageLower.includes('location') || messageLower.includes('address') || messageLower.includes('athens')) {
relevantKnowledge.push('CAMPUS LOCATION:');
relevantKnowledge.push(`- Location: ${UGA_KNOWLEDGE.campus.location.city}, ${UGA_KNOWLEDGE.campus.location.state}`);
relevantKnowledge.push(`- Size: ${UGA_KNOWLEDGE.campus.size.total_acres} acres`);
relevantKnowledge.push(`- Students: ${UGA_KNOWLEDGE.campus.size.students}`);
}
if (messageLower.includes('admission') || messageLower.includes('apply') || messageLower.includes('tuition')) {
relevantKnowledge.push('ADMISSIONS:');
relevantKnowledge.push(`- Acceptance rate: ${UGA_KNOWLEDGE.admissions.undergraduate.acceptance_rate}`);
relevantKnowledge.push(`- SAT range: ${UGA_KNOWLEDGE.admissions.undergraduate.middle_50_sat}`);
relevantKnowledge.push(`- In-state tuition: ${UGA_KNOWLEDGE.admissions.tuition_and_fees.in_state_undergraduate}`);
}
}
break;
}
} catch (error) {
console.log('Knowledge extraction error:', error.message);
}
return relevantKnowledge.length > 0 ? relevantKnowledge.join('\n') : null;
}
// Enhanced function to determine if web search should be used
function shouldUseWebSearch(message) {
const messageLower = message.toLowerCase();
// Keywords that suggest current/real-time information is needed
const currentInfoKeywords = [
'current', 'today', 'now', 'latest', 'recent', 'this week', 'this month', 'this year',
'hours', 'schedule', 'deadline', 'when', 'what time', 'how much', 'cost',
'events', 'happening', 'open', 'closed', 'available', 'score', 'news',
'2024', '2025', 'spring', 'fall', 'summer'
];
// UGA-specific topics that benefit from current information
const ugaTopics = [
'registration', 'enrollment', 'tuition', 'fees', 'dining', 'housing',
'football', 'basketball', 'game', 'ticket', 'event', 'deadline',
'faculty', 'professor', 'course', 'class', 'calendar'
];
// Check if message contains current info keywords
const hasCurrentKeywords = currentInfoKeywords.some(keyword =>
messageLower.includes(keyword)
);
// Check if message contains UGA topics
const hasUGATopic = ugaTopics.some(topic =>
messageLower.includes(topic)
);
// Use web search if asking for current info OR UGA-specific topics
return hasCurrentKeywords || hasUGATopic;
}
// Enhanced function to extract search query from user message
function extractSearchQuery(message, agentType) {
// Remove common question words and focus on the core topic
const cleanMessage = message
.toLowerCase()
.replace(/^(what|when|where|how|why|can you|tell me|find|search)\s+/g, '')
.replace(/\b(about|for|on|the|a|an|is|are|were|was)\b/g, ' ')
.replace(/\s+/g, ' ')
.trim();
// Add UGA context to make search more specific
return `UGA ${cleanMessage}`;
}
// Enhanced Hugging Face integration with agent support and web search
async function callHuggingFace(message, agentType = null) {
if (!hfClient) {
throw new Error('Hugging Face API key not configured');
}
const model = process.env.HUGGINGFACE_MODEL || 'meta-llama/Llama-3.1-8B-Instruct';
const startTime = Date.now();
// Select agent if not specified
if (!agentType) {
agentType = selectAgent(message);
}
const agent = UGA_AGENTS[agentType] || UGA_AGENTS.general;
console.log(`π€ ${agent.emoji} Calling Hugging Face with ${agent.name} (${model})`);
// Extract relevant UGA knowledge for the message
const ugaKnowledge = getRelevantUGAKnowledge(message, agentType);
// Check if we should use web search
let searchResults = null;
let enhancedMessage = message;
// Build enhanced message with UGA knowledge
if (ugaKnowledge) {
enhancedMessage = `User Question: ${message}
Relevant UGA Knowledge:
${ugaKnowledge}
Please use the above UGA knowledge to provide an accurate, helpful response. Keep responses concise (2-3 sentences max).`;
}
if (shouldUseWebSearch(message)) {
try {
console.log(`π ${agent.emoji} Performing web search for enhanced response`);
const searchQuery = extractSearchQuery(message, agentType);
const searchResponse = await webSearchService.search(searchQuery, agentType);
if (searchResponse.results && searchResponse.results.length > 0) {
searchResults = searchResponse;
// Create detailed context from search results
const searchContext = searchResponse.results
.slice(0, 5) // Top 5 results for better coverage
.map((result, index) => {
return `Result ${index + 1}:
Title: ${result.title}
URL: ${result.url}
Content: ${result.snippet}
Source: ${result.displayLink || 'N/A'}`;
})
.join('\n\n');
// Enhanced AI prompt for better search result analysis
enhancedMessage = `User Question: ${message}
${ugaKnowledge ? `UGA Knowledge Base Information:\n${ugaKnowledge}\n\n` : ''}Current Real-Time Search Results:
${searchContext}
CRITICAL INSTRUCTIONS FOR AI RESPONSE:
1. EXTRACT SPECIFIC DETAILS: Look for exact times, hours, dates, locations, phone numbers, addresses, prices, and specific requirements in the search results
2. PRIORITIZE CURRENT INFORMATION: Focus on the most recent and up-to-date information from official UGA sources
3. BE PRECISE: If asking about hours, provide the exact operating hours. If asking about locations, provide specific building names and addresses
4. SYNTHESIZE MULTIPLE SOURCES: Combine information from different search results to give a complete answer
5. CITE AUTHORITATIVE SOURCES: Prioritize uga.edu, dining.uga.edu, georgiadogs.com, and other official UGA domains
6. PROVIDE ACTIONABLE INFORMATION: Include relevant links, phone numbers, or next steps when available
7. HANDLE MISSING INFO: If specific details aren't found, clearly state what information is not available and suggest where to find it
8. FORMAT CLEARLY: Present information in a clear, organized manner with specific details highlighted
EXAMPLE GOOD RESPONSES:
- "The Dining Commons is open Monday-Friday 7:00 AM - 9:00 PM, Saturday-Sunday 8:00 AM - 8:00 PM. Contact: (706) 542-1234. Full hours: dining.uga.edu/hours"
- "Registration deadline is March 15, 2024. Requirements include 2.5 GPA minimum. Apply at: reg.uga.edu/registration"
Please provide the most specific, detailed, and actionable answer possible using the search results above.`;
}
} catch (searchError) {
console.error(`π Search failed for ${agent.name}:`, searchError.message);
// Continue without search results
}
}
try {
const response = await hfClient.chatCompletion({
model: model,
messages: [
{
role: 'system',
content: agent.systemPrompt
},
{
role: 'user',
content: enhancedMessage
}
],
max_tokens: parseInt(process.env.HUGGINGFACE_MAX_TOKENS) || 400,
temperature: parseFloat(process.env.HUGGINGFACE_TEMPERATURE) || 0.7,
top_p: parseFloat(process.env.HUGGINGFACE_TOP_P) || 0.9
});
const responseTime = Date.now() - startTime;
const content = response.choices[0].message.content;
console.log(`β
${agent.emoji} ${agent.name} response: ${content.length} chars in ${responseTime}ms`);
return {
content: content,
metadata: {
model: model,
responseTime: responseTime,
tokens: response.usage?.total_tokens || 0,
provider: 'huggingface',
agent: agentType,
agentName: agent.name,
agentEmoji: agent.emoji,
searchUsed: searchResults !== null,
searchProvider: searchResults?.provider,
searchFromCache: searchResults?.fromCache
}
};
} catch (error) {
console.error('β Hugging Face API error:', error.message);
throw new Error(`Hugging Face API error: ${error.message}`);
}
}
// Enhanced Ollama integration with agent support and web search
async function callOllama(message, agentType = null) {
const ollamaUrl = process.env.LOCAL_AI_URL || 'http://localhost:11434';
const model = process.env.LOCAL_AI_MODEL || 'tinyllama';
const startTime = Date.now();
// Select agent if not specified
if (!agentType) {
agentType = selectAgent(message);
}
const agent = UGA_AGENTS[agentType] || UGA_AGENTS.general;
console.log(`π€ ${agent.emoji} Calling Ollama with ${agent.name}: ${ollamaUrl}/api/generate (${model})`);
// Extract relevant UGA knowledge for the message
const ugaKnowledge = getRelevantUGAKnowledge(message, agentType);
// Check if we should use web search
let searchResults = null;
let enhancedPrompt = `${agent.systemPrompt}
${ugaKnowledge ? `Relevant UGA Knowledge:\n${ugaKnowledge}\n\n` : ''}Question: ${message}
Answer:`;
if (shouldUseWebSearch(message)) {
try {
console.log(`π ${agent.emoji} Performing web search for enhanced response`);
const searchQuery = extractSearchQuery(message, agentType);
const searchResponse = await webSearchService.search(searchQuery, agentType);
if (searchResponse.results && searchResponse.results.length > 0) {
searchResults = searchResponse;
// Create detailed context from search results
const searchContext = searchResponse.results
.slice(0, 5) // Top 5 results for better coverage
.map((result, index) => {
return `Result ${index + 1}:
Title: ${result.title}
URL: ${result.url}
Content: ${result.snippet}
Source: ${result.displayLink || 'N/A'}`;
})
.join('\n\n');
enhancedPrompt = `${agent.systemPrompt}
${ugaKnowledge ? `UGA Knowledge Base Information:\n${ugaKnowledge}\n\n` : ''}Current Real-Time Search Results:
${searchContext}
Question: ${message}
INSTRUCTIONS FOR RESPONSE:
1. Analyze all search results carefully to find the most accurate and current information
2. Synthesize information from multiple sources when possible
3. Prioritize official UGA sources (uga.edu, georgiadogs.com) over third-party sources
4. Include specific details like dates, times, locations when available in search results
5. Provide 2-3 of the most relevant and useful source links
6. Keep response informative but concise (2-3 sentences maximum)
Answer using both the UGA knowledge base and current search results:`;
}
} catch (searchError) {
console.error(`π Search failed for ${agent.name}:`, searchError.message);
// Continue without search results
}
}
const response = await fetch(`${ollamaUrl}/api/generate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: model,
prompt: enhancedPrompt,
stream: false,
options: {
temperature: 0.7,
top_p: 0.9,
top_k: 40
}
}),
timeout: 30000 // 30 second timeout
});
if (!response.ok) {
throw new Error(`Ollama API error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
const responseTime = Date.now() - startTime;
console.log(`β
${agent.emoji} ${agent.name} response: ${data.response.length} chars in ${responseTime}ms`);
return {
content: data.response,
metadata: {
model: model,
responseTime: responseTime,
tokens: data.eval_count || 0,
provider: 'ollama',
agent: agentType,
agentName: agent.name,
agentEmoji: agent.emoji,
searchUsed: searchResults !== null,
searchProvider: searchResults?.provider,
searchFromCache: searchResults?.fromCache
}
};
}
// Smart AI router with agent support and fallback mechanism
async function callAI(message, agentType = null) {
const useHuggingFace = process.env.USE_HUGGINGFACE === 'true';
const useOllama = process.env.USE_LOCAL_AI === 'true';
// Auto-select agent if not specified
if (!agentType) {
agentType = selectAgent(message);
}
const agent = UGA_AGENTS[agentType] || UGA_AGENTS.general;
console.log(`π§ AI Router - Agent: ${agent.emoji} ${agent.name}, HuggingFace: ${useHuggingFace}, Ollama: ${useOllama}`);
// Primary choice: Hugging Face if enabled and configured
if (useHuggingFace && process.env.HUGGINGFACE_API_KEY) {
try {
return await callHuggingFace(message, agentType);
} catch (error) {
console.error('β Hugging Face failed, trying fallback...', error.message);
// Fallback to Ollama if available
if (useOllama) {
try {
return await callOllama(message, agentType);
} catch (ollamaError) {
console.error('β Ollama fallback also failed:', ollamaError.message);
throw new Error('Both Hugging Face and Ollama services are unavailable');
}
} else {
throw error;
}
}
}
// Primary choice: Ollama if Hugging Face is not enabled
if (useOllama) {
try {
return await callOllama(message, agentType);
} catch (error) {
console.error('β Ollama failed, trying fallback...', error.message);
// Fallback to Hugging Face if available
if (process.env.HUGGINGFACE_API_KEY) {
try {
return await callHuggingFace(message, agentType);
} catch (hfError) {
console.error('β Hugging Face fallback also failed:', hfError.message);
throw new Error('Both Ollama and Hugging Face services are unavailable');
}
} else {
throw error;
}
}
}
throw new Error('No AI services are enabled. Please configure either Ollama or Hugging Face.');
}
// =================================================================
// WEB SEARCH API ENDPOINTS
// =================================================================
// Direct web search endpoint
app.post('/api/search', async (req, res) => {
try {
const { query, agentType = 'general' } = req.body;
if (!query || typeof query !== 'string' || query.trim().length === 0) {
return res.status(400).json({
success: false,
error: 'Valid search query is required'
});
}
console.log(`π Direct search request: "${query}" (agent: ${agentType})`);
const searchResults = await webSearchService.search(query.trim(), agentType);
res.json({
success: true,
data: {
query: query.trim(),
agentType,
results: searchResults.results,
fromCache: searchResults.fromCache,
provider: searchResults.provider,
timestamp: searchResults.timestamp,
totalResults: searchResults.results.length
}
});
} catch (error) {
console.error('β Search API error:', error.message);
res.status(500).json({
success: false,
error: 'Search service unavailable',
details: error.message
});
}
});
// Current UGA info search endpoint
app.post('/api/search/current', async (req, res) => {
try {
const { topic, agentType = 'general' } = req.body;
if (!topic || typeof topic !== 'string' || topic.trim().length === 0) {
return res.status(400).json({
success: false,
error: 'Valid topic is required'
});
}
console.log(`π Current UGA info search: "${topic}" (agent: ${agentType})`);
const searchResults = await webSearchService.searchCurrentUGAInfo(topic.trim(), agentType);
res.json({
success: true,
data: {
topic: topic.trim(),
agentType,
results: searchResults.results,
fromCache: searchResults.fromCache,
provider: searchResults.provider,
timestamp: searchResults.timestamp,
totalResults: searchResults.results.length
}
});
} catch (error) {
console.error('β Current search API error:', error.message);
res.status(500).json({
success: false,
error: 'Current search service unavailable',
details: error.message
});
}
});
// Get search suggestions for agent types
app.get('/api/search/suggestions/:agentType?', (req, res) => {
try {
const { agentType = 'general' } = req.params;
const suggestions = webSearchService.getUGASearchSuggestions(agentType);
res.json({
success: true,
data: {
agentType,
suggestions,
totalSuggestions: suggestions.length
}
});
} catch (error) {
console.error('β Search suggestions error:', error.message);
res.status(500).json({
success: false,
error: 'Failed to get search suggestions',
details: error.message
});
}
});
// Search cache management endpoints
app.get('/api/search/cache/stats', (req, res) => {
try {
const stats = webSearchService.getCacheStats();
res.json({
success: true,
data: {
cache: stats,
cacheEnabled: process.env.ENABLE_WEB_SEARCH === 'true',
cacheTTL: process.env.WEB_SEARCH_CACHE_TTL || 1800
}
});
} catch (error) {
console.error('β Cache stats error:', error.message);
res.status(500).json({
success: false,
error: 'Failed to get cache statistics'
});
}
});
app.post('/api/search/cache/clear', (req, res) => {
try {
const result = webSearchService.clearCache();
console.log('ποΈ Search cache cleared by admin request');
res.json({
success: true,
data: result
});
} catch (error) {
console.error('β Cache clear error:', error.message);
res.status(500).json({
success: false,
error: 'Failed to clear search cache'
});
}
});
// Web search status and configuration
app.get('/api/search/status', (req, res) => {
try {
const status = {
enabled: process.env.ENABLE_WEB_SEARCH === 'true',
providers: {
google: !!(process.env.GOOGLE_SEARCH_API_KEY && process.env.GOOGLE_SEARCH_ENGINE_ID),
bing: !!process.env.BING_SEARCH_API_KEY,
searxng: !!process.env.SEARXNG_URL
},
cache: {
enabled: true,
ttl: process.env.WEB_SEARCH_CACHE_TTL || 1800,
stats: webSearchService.getCacheStats()
}
};
res.json({
success: true,
data: status
});
} catch (error) {
console.error('β Search status error:', error.message);
res.status(500).json({
success: false,
error: 'Failed to get search status'
});
}
});
// =================================================================
// END WEB SEARCH API ENDPOINTS
// =================================================================
// Enhanced health check for both services
app.get('/health', async (req, res) => {
try {
const ollamaUrl = process.env.LOCAL_AI_URL || 'http://localhost:11434';
const response = await fetch(`${ollamaUrl}/api/tags`, { timeout: 5000 });
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
ollama: response.ok ? 'connected' : 'error',
model: process.env.LOCAL_AI_MODEL || 'tinyllama'
});
} catch (error) {
res.status(500).json({
status: 'error',
error: error.message,
ollama: 'disconnected'
});
}
});
// Enhanced AI Chat endpoint with agent support and history
app.post('/api/chat', async (req, res) => {
try {
const { message, sessionId, userId, agentType } = req.body;
if (!message || typeof message !== 'string' || message.trim().length === 0) {
return res.status(400).json({
success: false,
error: 'Valid message is required'
});
}
console.log(`π Processing: "${message.substring(0, 100)}${message.length > 100 ? '...' : ''}"`);
// Use the smart AI router with agent support
const result = await callAI(message.trim(), agentType);
// Save to chat history if userId and sessionId are provided
if (userId && sessionId) {
try {
const userHistory = await loadUserHistory(userId);
// Get or create session
let session = userHistory.sessions[sessionId];
if (!session) {
session = createChatSession();
session.id = sessionId;
userHistory.sessions[sessionId] = session;
userHistory.metadata.totalSessions++;
}
// Add user message
addMessageToSession(session, message.trim(), 'user');
// Add bot response with agent information
addMessageToSession(session, result.content, 'bot', result.metadata);
// Update user metadata
userHistory.metadata.totalMessages += 2;
// Save updated history
await saveUserHistory(userId, userHistory);
} catch (historyError) {
console.error('Error saving to chat history:', historyError);
// Continue with response even if history save fails
}
}
res.json({
success: true,
response: result.content,
metadata: result.metadata,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error('β AI Error:', error.message);
// Return error instead of fallback to ensure real AI is working
res.status(500).json({
success: false,
error: 'AI service unavailable',
details: error.message,
message: 'Please ensure AI service is running'
});
}
});
// Get available agents
app.get('/api/agents', (req, res) => {
const agents = Object.keys(UGA_AGENTS).map(key => {
const agent = UGA_AGENTS[key];
return {
id: key,
name: agent.name,
emoji: agent.emoji,
domains: agent.domains,
description: agent.systemPrompt.split('\n')[0].replace('You are the ', '').replace('You are a ', '')
};
});
res.json({
success: true,
data: {
agents,
totalAgents: agents.length,
defaultAgent: 'general'
}
});
});
// Agent-specific chat endpoints
app.post('/api/chat/academic', async (req, res) => {
try {
const { message, sessionId, userId } = req.body;
if (!message || typeof message !== 'string' || message.trim().length === 0) {
return res.status(400).json({
success: false,
error: 'Valid message is required'
});
}
console.log(`π Processing with Academic Advisor: "${message.substring(0, 100)}${message.length > 100 ? '...' : ''}"`);
const result = await callAI(message.trim(), 'academic');
res.json({
success: true,
response: result.content,
metadata: result.metadata,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error('β Academic Advisor Error:', error.message);
res.status(500).json({
success: false,
error: 'Academic advisor service unavailable',
details: error.message
});
}
});
app.post('/api/chat/student-life', async (req, res) => {
try {
const { message, sessionId, userId } = req.body;
if (!message || typeof message !== 'string' || message.trim().length === 0) {
return res.status(400).json({
success: false,
error: 'Valid message is required'
});
}
console.log(`π Processing with Student Life Guide: "${message.substring(0, 100)}${message.length > 100 ? '...' : ''}"`);
const result = await callAI(message.trim(), 'student_life');
res.json({
success: true,
response: result.content,
metadata: result.metadata,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error('β Student Life Guide Error:', error.message);
res.status(500).json({
success: false,
error: 'Student life guide service unavailable',
details: error.message
});
}
});
app.post('/api/chat/athletics', async (req, res) => {
try {
const { message, sessionId, userId } = req.body;
if (!message || typeof message !== 'string' || message.trim().length === 0) {
return res.status(400).json({
success: false,
error: 'Valid message is required'
});
}
console.log(`π Processing with Athletics Assistant: "${message.substring(0, 100)}${message.length > 100 ? '...' : ''}"`);
const result = await callAI(message.trim(), 'athletics');
res.json({
success: true,
response: result.content,
metadata: result.metadata,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error('β Athletics Assistant Error:', error.message);
res.status(500).json({
success: false,
error: 'Athletics assistant service unavailable',
details: error.message
});
}
});
app.post('/api/chat/general', async (req, res) => {
try {
const { message, sessionId, userId } = req.body;
if (!message || typeof message !== 'string' || message.trim().length === 0) {
return res.status(400).json({
success: false,
error: 'Valid message is required'
});
}
console.log(`π Processing with General Helper: "${message.substring(0, 100)}${message.length > 100 ? '...' : ''}"`);
const result = await callAI(message.trim(), 'general');
res.json({
success: true,
response: result.content,
metadata: result.metadata,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error('β General Helper Error:', error.message);
res.status(500).json({
success: false,
error: 'General helper service unavailable',
details: error.message
});
}
});
// New endpoint specifically for Hugging Face (with agent support)
app.post('/api/chat/huggingface', async (req, res) => {
try {
const { message, agentType } = req.body;
if (!message || typeof message !== 'string' || message.trim().length === 0) {
return res.status(400).json({
success: false,
error: 'Valid message is required'
});
}
if (!process.env.HUGGINGFACE_API_KEY) {
return res.status(400).json({
success: false,
error: 'Hugging Face API key not configured'
});
}
console.log(`π Processing with Hugging Face: "${message.substring(0, 100)}${message.length > 100 ? '...' : ''}"`);
const result = await callHuggingFace(message.trim(), agentType);
res.json({
success: true,
response: result.content,
metadata: result.metadata,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error('β Hugging Face Error:', error.message);
res.status(500).json({
success: false,
error: 'Hugging Face service unavailable',
details: error.message,
message: 'Please check your Hugging Face API key and model configuration'
});
}
});
// New endpoint specifically for Ollama (with agent support)
app.post('/api/chat/ollama', async (req, res) => {
try {
const { message, agentType } = req.body;
if (!message || typeof message !== 'string' || message.trim().length === 0) {
return res.status(400).json({
success: false,
error: 'Valid message is required'
});
}
console.log(`π Processing with Ollama: "${message.substring(0, 100)}${message.length > 100 ? '...' : ''}"`);
const result = await callOllama(message.trim(), agentType);
res.json({
success: true,
response: result.content,
metadata: result.metadata,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error('β Ollama Error:', error.message);
res.status(500).json({
success: false,
error: 'Ollama service unavailable',
details: error.message,
message: 'Please ensure Ollama is running with the correct model'
});
}
});
// Chat History API Endpoints
// Get user's chat sessions
app.get('/api/history/sessions/:userId', async (req, res) => {
try {
const { userId } = req.params;
const userHistory = await loadUserHistory(userId);
// Convert sessions object to array and sort by last activity
const sessions = Object.values(userHistory.sessions)
.sort((a, b) => new Date(b.metadata.lastActivity) - new Date(a.metadata.lastActivity));
res.json({
success: true,
data: {
sessions,
metadata: userHistory.metadata
}
});
} catch (error) {
console.error('Error loading chat sessions:', error);
res.status(500).json({
success: false,
error: 'Failed to load chat sessions'
});
}
});
// Get specific chat session
app.get('/api/history/session/:userId/:sessionId', async (req, res) => {
try {
const { userId, sessionId } = req.params;
const userHistory = await loadUserHistory(userId);
const session = userHistory.sessions[sessionId];
if (!session) {
return res.status(404).json({
success: false,
error: 'Session not found'
});
}
res.json({
success: true,
data: session
});
} catch (error) {
console.error('Error loading chat session:', error);
res.status(500).json({
success: false,
error: 'Failed to load chat session'
});
}
});
// Create new chat session
app.post('/api/history/session/:userId', async (req, res) => {
try {
const { userId } = req.params;
const { title } = req.body;
const userHistory = await loadUserHistory(userId);
const newSession = createChatSession(title);
userHistory.sessions[newSession.id] = newSession;
userHistory.metadata.totalSessions++;
await saveUserHistory(userId, userHistory);
res.json({
success: true,
data: newSession
});
} catch (error) {
console.error('Error creating chat session:', error);
res.status(500).json({
success: false,
error: 'Failed to create chat session'
});
}
});
// Update chat session (rename, etc.)
app.put('/api/history/session/:userId/:sessionId', async (req, res) => {
try {
const { userId, sessionId } = req.params;
const { title } = req.body;
const userHistory = await loadUserHistory(userId);
const session = userHistory.sessions[sessionId];
if (!session) {
return res.status(404).json({
success: false,
error: 'Session not found'
});
}
if (title) {
session.title = title;
session.metadata.lastActivity = new Date().toISOString();
}
await saveUserHistory(userId, userHistory);
res.json({
success: true,
data: session
});
} catch (error) {
console.error('Error updating chat session:', error);
res.status(500).json({
success: false,
error: 'Failed to update chat session'
});
}
});
// Delete chat session
app.delete('/api/history/session/:userId/:sessionId', async (req, res) => {
try {
const { userId, sessionId } = req.params;
const userHistory = await loadUserHistory(userId);
if (!userHistory.sessions[sessionId]) {
return res.status(404).json({
success: false,
error: 'Session not found'
});
}
// Update metadata
const session = userHistory.sessions[sessionId];
userHistory.metadata.totalMessages -= session.metadata.messageCount;
userHistory.metadata.totalSessions--;
delete userHistory.sessions[sessionId];
await saveUserHistory(userId, userHistory);
res.json({
success: true,
message: 'Session deleted successfully'
});
} catch (error) {
console.error('Error deleting chat session:', error);
res.status(500).json({
success: false,
error: 'Failed to delete chat session'
});
}
});
// Search chat history
app.get('/api/history/search/:userId', async (req, res) => {
try {
const { userId } = req.params;
const { q: query, limit = 50 } = req.query;
if (!query || query.trim().length === 0) {
return res.status(400).json({
success: false,
error: 'Search query is required'
});
}
const userHistory = await loadUserHistory(userId);
const searchResults = [];
const searchTerm = query.toLowerCase();
// Search through all sessions and messages
Object.values(userHistory.sessions).forEach(session => {
// Check session title
if (session.title.toLowerCase().includes(searchTerm)) {
searchResults.push({
type: 'session',
sessionId: session.id,
title: session.title,
lastActivity: session.metadata.lastActivity,
messageCount: session.metadata.messageCount
});
}
// Check messages
session.messages.forEach(message => {
if (message.content.toLowerCase().includes(searchTerm)) {
searchResults.push({
type: 'message',
sessionId: session.id,
sessionTitle: session.title,
messageId: message.id,
content: message.content,
sender: message.sender,
timestamp: message.timestamp,
// Highlight the search term (simple implementation)
highlight: message.content.substring(
Math.max(0, message.content.toLowerCase().indexOf(searchTerm) - 50),
Math.min(message.content.length, message.content.toLowerCase().indexOf(searchTerm) + searchTerm.length + 50)
)
});
}
});
});
// Sort by relevance (sessions first, then by timestamp)
searchResults.sort((a, b) => {
if (a.type !== b.type) {
return a.type === 'session' ? -1 : 1;
}
const aTime = new Date(a.timestamp || a.lastActivity);
const bTime = new Date(b.timestamp || b.lastActivity);
return bTime - aTime;
});
res.json({
success: true,
data: {
query,
results: searchResults.slice(0, parseInt(limit)),
totalResults: searchResults.length
}
});
} catch (error) {
console.error('Error searching chat history:', error);
res.status(500).json({
success: false,
error: 'Failed to search chat history'
});
}
});
// Export chat history
app.get('/api/history/export/:userId', async (req, res) => {
try {
const { userId } = req.params;
const { format = 'json', sessionId } = req.query;
const userHistory = await loadUserHistory(userId);
let exportData;
if (sessionId) {
// Export specific session
const session = userHistory.sessions[sessionId];
if (!session) {
return res.status(404).json({
success: false,
error: 'Session not found'
});
}
exportData = session;
} else {
// Export all history
exportData = userHistory;
}
if (format === 'json') {
res.setHeader('Content-Type', 'application/json');
res.setHeader('Content-Disposition', `attachment; filename="chat-history-${userId}-${Date.now()}.json"`);
res.json(exportData);
} else if (format === 'txt') {
// Convert to plain text format
let textContent = '';
if (sessionId) {
const session = exportData;
textContent = `Chat Session: ${session.title}\n`;
textContent += `Created: ${new Date(session.metadata.createdAt).toLocaleString()}\n`;
textContent += `Messages: ${session.metadata.messageCount}\n\n`;
session.messages.forEach(msg => {
textContent += `[${new Date(msg.timestamp).toLocaleString()}] ${msg.sender.toUpperCase()}: ${msg.content}\n\n`;
});
} else {
textContent = `Chat History Export for User: ${userId}\n`;
textContent += `Export Date: ${new Date().toLocaleString()}\n`;
textContent += `Total Sessions: ${exportData.metadata.totalSessions}\n`;
textContent += `Total Messages: ${exportData.metadata.totalMessages}\n\n`;
Object.values(exportData.sessions).forEach(session => {
textContent += `=== ${session.title} ===\n`;
textContent += `Created: ${new Date(session.metadata.createdAt).toLocaleString()}\n\n`;
session.messages.forEach(msg => {
textContent += `[${new Date(msg.timestamp).toLocaleString()}] ${msg.sender.toUpperCase()}: ${msg.content}\n\n`;
});
textContent += '\n---\n\n';
});
}
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Disposition', `attachment; filename="chat-history-${userId}-${Date.now()}.txt"`);
res.send(textContent);
} else {
res.status(400).json({
success: false,
error: 'Unsupported export format. Use json or txt.'
});
}
} catch (error) {
console.error('Error exporting chat history:', error);
res.status(500).json({
success: false,
error: 'Failed to export chat history'
});
}
});
// Serve files
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.get('/dashboard', (req, res) => {
res.sendFile(path.join(__dirname, 'dashboard.html'));
});
app.get('/landing.html', (req, res) => {
res.sendFile(path.join(__dirname, 'landing.html'));
});
// Start server
app.listen(PORT, '0.0.0.0', async () => {
// Initialize chat history directory
await ensureChatHistoryDir();
console.log(`π edi.chat Multi-Agent AI Server running on port ${PORT}`);
console.log(`π€ Ollama URL: ${process.env.LOCAL_AI_URL || 'http://localhost:11434'}`);
console.log(`π€ HuggingFace: ${process.env.HUGGINGFACE_API_KEY ? 'Enabled' : 'Disabled'}`);
console.log(`π¦ Model: ${process.env.LOCAL_AI_MODEL || 'tinyllama'}`);
console.log(`πΎ Chat History: ${CHAT_HISTORY_DIR}`);
console.log('');
// Web Search Status
console.log('π Web Search Integration:');
console.log(` β’ Status: ${process.env.ENABLE_WEB_SEARCH === 'true' ? 'Enabled' : 'Disabled'}`);
console.log(` β’ Google API: ${process.env.GOOGLE_SEARCH_API_KEY && process.env.GOOGLE_SEARCH_ENGINE_ID ? 'Configured' : 'Not Configured'}`);
console.log(` β’ Bing API: ${process.env.BING_SEARCH_API_KEY ? 'Configured' : 'Not Configured'}`);
console.log(` β’ SearXNG: ${process.env.SEARXNG_URL ? 'Configured' : 'Using Default'}`);
console.log(` β’ Cache TTL: ${process.env.WEB_SEARCH_CACHE_TTL || 1800}s`);
console.log('');
console.log('π UGA Specialized Agents with Real-Time Search:');
Object.keys(UGA_AGENTS).forEach(key => {
const agent = UGA_AGENTS[key];
console.log(` ${agent.emoji} ${agent.name} (web search enabled)`);
});
console.log('');
console.log(`π Dashboard: http://localhost:${PORT}/dashboard`);
console.log(`π Landing: http://localhost:${PORT}/landing.html`);
console.log(`β€οΈ Health: http://localhost:${PORT}/health`);
console.log(`π€ Agents API: http://localhost:${PORT}/api/agents`);
console.log(`π Search Status: http://localhost:${PORT}/api/search/status`);
console.log('');
console.log('π Agent Endpoints:');
console.log(` β’ Academic: POST /api/chat/academic`);
console.log(` β’ Student Life: POST /api/chat/student-life`);
console.log(` β’ Athletics: POST /api/chat/athletics`);
console.log(` β’ General: POST /api/chat/general`);
console.log(` β’ Auto-select: POST /api/chat`);
console.log('');
console.log('π Web Search Endpoints:');
console.log(` β’ Direct Search: POST /api/search`);
console.log(` β’ Current Info: POST /api/search/current`);
console.log(` β’ Suggestions: GET /api/search/suggestions/:agentType`);
console.log(` β’ Cache Stats: GET /api/search/cache/stats`);
console.log(` β’ Clear Cache: POST /api/search/cache/clear`);
console.log('');
console.log('π§ Multi-Agent AI Router with Real-Time Web Search & Chat History enabled!');
});
const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs').promises;
const crypto = require('crypto');
const { HfInference } = require('@huggingface/inference');
const axios = require('axios');
const NodeCache = require('node-cache');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 7860;
// Initialize caching system for web search results
const searchCache = new NodeCache({
stdTTL: parseInt(process.env.WEB_SEARCH_CACHE_TTL) || 1800, // 30 minutes default
checkperiod: 600, // Check for expired keys every 10 minutes
useClones: false
});
// Chat history storage directory
const CHAT_HISTORY_DIR = path.join(__dirname, 'chat_history');
// Ensure chat history directory exists
async function ensureChatHistoryDir() {
try {
await fs.access(CHAT_HISTORY_DIR);
} catch {
await fs.mkdir(CHAT_HISTORY_DIR, { recursive: true });
}
}
// Chat history data structures and utilities
function generateSessionId() {
return crypto.randomUUID();
}
function getUserHistoryFile(userId) {
return path.join(CHAT_HISTORY_DIR, `user_${userId}.json`);
}
async function loadUserHistory(userId) {
try {
const historyFile = getUserHistoryFile(userId);
const data = await fs.readFile(historyFile, 'utf8');
return JSON.parse(data);
} catch (error) {
// Return empty history structure if file doesn't exist
return {
userId,
sessions: {},
metadata: {
totalMessages: 0,
totalSessions: 0,
createdAt: new Date().toISOString(),
lastActivity: new Date().toISOString()
}
};
}
}
async function saveUserHistory(userId, history) {
try {
const historyFile = getUserHistoryFile(userId);
history.metadata.lastActivity = new Date().toISOString();
await fs.writeFile(historyFile, JSON.stringify(history, null, 2));
return true;
} catch (error) {
console.error('Error saving user history:', error);
return false;
}
}
function createChatSession(title = null) {
const sessionId = generateSessionId();
return {
id: sessionId,
title: title || `Chat ${new Date().toLocaleDateString()}`,
messages: [],
metadata: {
createdAt: new Date().toISOString(),
lastActivity: new Date().toISOString(),
messageCount: 0,
totalTokens: 0,
avgResponseTime: 0
}
};
}
function addMessageToSession(session, message, sender, metadata = {}) {
const messageObj = {
id: crypto.randomUUID(),
content: message,
sender, // 'user' or 'bot'
timestamp: new Date().toISOString(),
metadata: {
...metadata,
tokens: metadata.tokens || 0,
responseTime: metadata.responseTime || 0
}