skailan-ai
Version:
Servicio de IA y procesamiento de lenguaje natural para Skailan
116 lines (110 loc) • 3.58 kB
JavaScript
import { AIService } from './AIService';
export class SentimentAnalysisService {
aiService;
constructor(llmConfig) {
this.aiService = new AIService(llmConfig);
}
async analyzeSentiment(text) {
const prompt = `
Analiza el sentimiento del siguiente texto y responde en formato JSON:
Texto: "${text}"
Responde con un JSON que contenga:
{
"sentiment": "positive|negative|neutral",
"confidence": 0.95,
"emotions": {
"joy": 0.3,
"sadness": 0.1,
"anger": 0.05,
"fear": 0.02,
"surprise": 0.1
},
"summary": "Breve resumen del análisis"
}
Solo responde con el JSON, sin texto adicional.
`;
try {
const response = await this.aiService.generateText(prompt);
const result = JSON.parse(response);
return {
sentiment: result.sentiment,
confidence: result.confidence,
emotions: result.emotions,
summary: result.summary
};
}
catch (error) {
// Fallback a análisis básico si falla el parsing
return this.fallbackSentimentAnalysis(text);
}
}
async analyzeConversationSentiment(messages) {
const conversationText = messages
.map(msg => `${msg.role}: ${msg.content}`)
.join('\n');
const prompt = `
Analiza el sentimiento general de esta conversación y responde en formato JSON:
Conversación:
${conversationText}
Responde con un JSON que contenga:
{
"sentiment": "positive|negative|neutral",
"confidence": 0.95,
"emotions": {
"joy": 0.3,
"sadness": 0.1,
"anger": 0.05,
"fear": 0.02,
"surprise": 0.1
},
"summary": "Resumen del sentimiento de la conversación"
}
Solo responde con el JSON, sin texto adicional.
`;
try {
const response = await this.aiService.generateText(prompt);
const result = JSON.parse(response);
return {
sentiment: result.sentiment,
confidence: result.confidence,
emotions: result.emotions,
summary: result.summary
};
}
catch (error) {
return this.fallbackSentimentAnalysis(conversationText);
}
}
fallbackSentimentAnalysis(text) {
// Análisis básico basado en palabras clave
const positiveWords = ['bueno', 'excelente', 'genial', 'perfecto', 'me gusta', 'gracias'];
const negativeWords = ['malo', 'terrible', 'horrible', 'no me gusta', 'problema', 'error'];
const lowerText = text.toLowerCase();
let positiveCount = 0;
let negativeCount = 0;
positiveWords.forEach(word => {
if (lowerText.includes(word))
positiveCount++;
});
negativeWords.forEach(word => {
if (lowerText.includes(word))
negativeCount++;
});
let sentiment = 'neutral';
let confidence = 0.5;
if (positiveCount > negativeCount) {
sentiment = 'positive';
confidence = Math.min(0.9, 0.5 + (positiveCount * 0.1));
}
else if (negativeCount > positiveCount) {
sentiment = 'negative';
confidence = Math.min(0.9, 0.5 + (negativeCount * 0.1));
}
return {
sentiment,
confidence,
summary: `Análisis básico: ${sentiment} (confianza: ${confidence})`
};
}
}
//# sourceMappingURL=SentimentAnalysisService.js.map