betty2 / ai-handler copy.js
sdgsdggds's picture
Upload folder using huggingface_hub
e7c953d verified
// AI Handler for Gemini API integration - Simple version
const https = require('https');
class AIHandler {
constructor(apiKey) {
this.apiKey = apiKey;
console.log('AI Handler initialized with simple implementation');
}
/**
* Make a request to the Gemini API and get a response for chat
* @param {string} userMessage - The message from the chat user
* @returns {Promise<string>} - The AI response or error message
*/
async getAIResponse(userMessage) {
return new Promise((resolve, reject) => {
try {
console.log(`AI processing message: ${userMessage}`);
// Create a simple context-aware prompt
const prompt = `You are a helpful AI assistant in a music chat room.
Respond in a friendly, helpful way. Keep it very short (1-2 sentences max).
User message: ${userMessage}`;
// Use the stable gemini-1.5-flash-002 model
const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-002:generateContent?key=${this.apiKey}`;
// Prepare request body
const body = JSON.stringify({
contents: [{
parts: [{
text: prompt
}]
}],
generationConfig: {
temperature: 0.7,
maxOutputTokens: 100
}
});
// Log the request URL to debug
console.log(`Sending request to: ${url.replace(this.apiKey, 'API_KEY')}`);
// Parse the URL for the request
const urlObj = new URL(url);
// Set up the request options
const options = {
hostname: urlObj.hostname,
path: urlObj.pathname + urlObj.search,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body)
}
};
const req = https.request(options, (res) => {
let responseBody = '';
// Collect data chunks
res.on('data', (chunk) => {
responseBody += chunk;
});
// Process complete response
res.on('end', () => {
console.log(`API Response status: ${res.statusCode}`);
// Check for success
if (res.statusCode !== 200) {
console.error(`API Error ${res.statusCode}: ${responseBody}`);
return resolve('Sorry, I had a problem connecting to my AI brain.');
}
try {
const response = JSON.parse(responseBody);
// Extract the generated text
if (response.candidates &&
response.candidates[0] &&
response.candidates[0].content &&
response.candidates[0].content.parts &&
response.candidates[0].content.parts[0] &&
response.candidates[0].content.parts[0].text) {
const text = response.candidates[0].content.parts[0].text.trim();
console.log(`AI generated: ${text.substring(0, 50)}...`);
resolve(text);
} else {
console.error('Unexpected response format:', JSON.stringify(response).substring(0, 200));
resolve('Sorry, I got confused. Can you try again?');
}
} catch (error) {
console.error('Error parsing response:', error);
console.error('Raw response:', responseBody.substring(0, 200));
resolve('Sorry, I had trouble understanding the response.');
}
});
});
// Handle request errors
req.on('error', (error) => {
console.error('Request error:', error);
resolve('Sorry, I had trouble connecting to my AI brain. Try again later?');
});
// Send the request
req.write(body);
req.end();
} catch (error) {
console.error('Unexpected error in getAIResponse:', error);
resolve('Sorry, something unexpected happened with my AI processing.');
}
});
}
}
module.exports = AIHandler;