skailan-ai
Version:
Servicio de IA y procesamiento de lenguaje natural para Skailan
163 lines • 8.63 kB
JavaScript
import { AIService } from '../domain/services/AIService';
import { SentimentAnalysisService } from '../domain/services/SentimentAnalysisService';
import { IntentClassificationService } from '../domain/services/IntentClassificationService';
import { ContentGenerationService } from '../domain/services/ContentGenerationService';
import { ConversationContextService } from '../domain/services/ConversationContextService';
export class AIServiceSDK {
llmConfigRepository;
organizationId;
options;
constructor(llmConfigRepository, organizationId, options = {}) {
this.llmConfigRepository = llmConfigRepository;
this.organizationId = organizationId;
this.options = {
defaultLLMConfigName: 'default',
enableCaching: true,
enableLogging: true,
...options
};
}
async getLLMConfig(configName) {
const name = configName || this.options.defaultLLMConfigName || 'default';
const config = await this.llmConfigRepository.findByName(name, this.organizationId);
if (!config || !config.isActive) {
throw new Error(`LLM configuration '${name}' not found or inactive for organization ${this.organizationId}`);
}
return config;
}
// Análisis de sentimiento
async analyzeSentiment(request) {
const llmConfig = await this.getLLMConfig(request.llmConfigName);
const service = new SentimentAnalysisService(llmConfig);
return await service.analyzeSentiment(request.text);
}
async analyzeConversationSentiment(messages, llmConfigName) {
const llmConfig = await this.getLLMConfig(llmConfigName);
const service = new SentimentAnalysisService(llmConfig);
return await service.analyzeConversationSentiment(messages);
}
// Clasificación de intenciones
async classifyIntent(request) {
const llmConfig = await this.getLLMConfig(request.llmConfigName);
const service = new IntentClassificationService(llmConfig, request.intents);
return await service.classifyIntent(request.text);
}
async classifyConversationIntent(messages, llmConfigName, intents) {
const llmConfig = await this.getLLMConfig(llmConfigName);
const service = new IntentClassificationService(llmConfig, intents);
return await service.classifyConversationIntent(messages);
}
// Generación de contenido
async generateContent(request) {
const llmConfig = await this.getLLMConfig(request.llmConfigName);
const service = new ContentGenerationService(llmConfig);
switch (request.type) {
case 'email':
return await service.generateEmail(request.data, request.options);
case 'quote':
return await service.generateQuote(request.data, request.options);
case 'report':
return await service.generateReport(request.data, request.options);
case 'summary':
return await service.generateConversationSummary(request.data, request.options);
case 'bot-response':
return await service.generateBotResponse(request.data.userMessage, request.data.context || '', request.data.intent || '', request.options);
case 'marketing':
return await service.generateMarketingContent(request.data.product, request.data.targetAudience, request.data.purpose, request.options);
case 'documentation':
return await service.generateDocumentation(request.data.topic, request.data.audience, request.data.purpose, request.options);
default:
throw new Error(`Unsupported content generation type: ${request.type}`);
}
}
// Procesamiento de texto básico
async processText(text, promptName, llmConfigName, parameters) {
const llmConfig = await this.getLLMConfig(llmConfigName);
const service = new AIService(llmConfig);
return await service.generateText(text, parameters);
}
// Gestión de contexto de conversaciones
async createConversationContext(conversationId, initialMessage, llmConfigName) {
const llmConfig = await this.getLLMConfig(llmConfigName);
const service = new ConversationContextService(llmConfig);
return await service.createContext(this.organizationId, conversationId, initialMessage);
}
async addMessageToContext(conversationId, role, content, llmConfigName) {
const llmConfig = await this.getLLMConfig(llmConfigName);
const service = new ConversationContextService(llmConfig);
return await service.addMessage(this.organizationId, conversationId, role, content);
}
async getConversationContext(conversationId, llmConfigName) {
const llmConfig = await this.getLLMConfig(llmConfigName);
const service = new ConversationContextService(llmConfig);
return await service.getContext(this.organizationId, conversationId);
}
async generateConversationSummary(conversationId, llmConfigName) {
const llmConfig = await this.getLLMConfig(llmConfigName);
const service = new ConversationContextService(llmConfig);
return await service.generateSummary(this.organizationId, conversationId);
}
// Métodos de utilidad
async getAvailableLLMConfigs() {
return await this.llmConfigRepository.findAll(this.organizationId);
}
async validateLLMConfig(configName) {
const config = await this.llmConfigRepository.findByName(configName, this.organizationId);
return config && config.isActive;
}
// Métodos para integración con otros módulos
async generateBotResponseForConversation(conversationId, userMessage, llmConfigName) {
const llmConfig = await this.getLLMConfig(llmConfigName);
const contextService = new ConversationContextService(llmConfig);
const contentService = new ContentGenerationService(llmConfig);
// Obtener contexto de la conversación
const context = await contextService.getContext(this.organizationId, conversationId);
if (!context) {
throw new Error(`Conversation context not found for ${conversationId}`);
}
// Analizar intención del mensaje
const intentService = new IntentClassificationService(llmConfig);
const intentResult = await intentService.classifyIntent(userMessage);
// Generar respuesta del bot
const response = await contentService.generateBotResponse(userMessage, context.messages.map(m => `${m.role}: ${m.content}`).join('\n'), intentResult.intent);
// Agregar mensajes al contexto
await contextService.addMessage(this.organizationId, conversationId, 'user', userMessage);
await contextService.addMessage(this.organizationId, conversationId, 'assistant', response);
return {
response,
intent: intentResult.intent,
confidence: intentResult.confidence,
entities: intentResult.entities
};
}
async analyzeConversationForCRM(conversationId, llmConfigName) {
const llmConfig = await this.getLLMConfig(llmConfigName);
const contextService = new ConversationContextService(llmConfig);
const sentimentService = new SentimentAnalysisService(llmConfig);
const intentService = new IntentClassificationService(llmConfig);
const context = await contextService.getContext(this.organizationId, conversationId);
if (!context || context.messages.length === 0) {
throw new Error(`No conversation context found for ${conversationId}`);
}
const messages = context.messages.map(m => ({ role: m.role, content: m.content }));
// Análisis completo
const [sentiment, intent, summary] = await Promise.all([
sentimentService.analyzeConversationSentiment(messages),
intentService.classifyConversationIntent(messages),
contextService.generateSummary(this.organizationId, conversationId)
]);
return {
conversationId,
summary,
sentiment: sentiment.sentiment,
sentimentConfidence: sentiment.confidence,
intent: intent.intent,
intentConfidence: intent.confidence,
entities: intent.entities,
messageCount: context.messages.length,
duration: context.updatedAt.getTime() - context.createdAt.getTime(),
lastActivity: context.updatedAt
};
}
}
//# sourceMappingURL=AIServiceSDK.js.map