@tomisakae/tomibot
Version:
TomiBot - AI Chatbot CLI với Google Genkit. Một chatbot AI thông minh chạy trên command line với giao diện đẹp.
202 lines • 7.58 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AIServiceImpl = void 0;
const googleai_1 = require("@genkit-ai/googleai");
const genkit_1 = require("genkit");
const ai_interface_1 = require("./ai.interface");
const types_1 = require("../../core/types");
const config_1 = require("../../core/config");
const logger_util_1 = require("../../utils/logger.util");
class AIServiceImpl extends ai_interface_1.BaseAIService {
constructor() {
const aiConfig = config_1.config.aiConfig;
const serviceConfig = {
provider: aiConfig.provider,
model: aiConfig.model,
apiKey: aiConfig.apiKey || '',
maxTokens: aiConfig.maxTokens || 2048,
temperature: aiConfig.temperature || 0.7,
};
super(serviceConfig, {
retryAttempts: 3,
retryDelay: 1000,
enableLogging: config_1.config.isDevelopment(),
});
this.logger = new logger_util_1.Logger('GenkitService');
}
async initialize() {
if (this.initialized) {
this.logger.warn('Service already initialized');
return;
}
try {
this.logger.info('Initializing Genkit AI service...');
if (!this.config.apiKey) {
this.logger.warn('No API key provided, service will not be ready');
return;
}
this.ai = (0, genkit_1.genkit)({
plugins: [(0, googleai_1.googleAI)()],
model: googleai_1.googleAI.model(this.config.model),
});
this.initialized = true;
this.logger.info('Genkit AI service initialized successfully');
}
catch (error) {
this.logger.error('Failed to initialize Genkit service:', error);
throw new types_1.AIServiceError('Failed to initialize AI service', {
originalError: error,
});
}
}
async sendMessage(message) {
this.logger.debug('Sending message to AI', {
messageLength: message.length,
});
if (!this.isReady()) {
return {
content: '',
success: false,
error: 'AI service is not ready. Please check your API key configuration.',
};
}
try {
return await this.withRetry(async () => {
const userMessage = {
id: this.generateMessageId(),
role: 'user',
content: message,
timestamp: new Date(),
};
this.addToHistory(userMessage);
const context = this.buildContext();
const response = await this.ai.generate(context);
const assistantMessage = {
id: this.generateMessageId(),
role: 'assistant',
content: response.text,
timestamp: new Date(),
};
this.addToHistory(assistantMessage);
this.logger.debug('Received response from AI', {
responseLength: response.text.length,
});
return {
content: response.text,
success: true,
metadata: {
model: this.config.model,
provider: this.config.provider,
messageId: assistantMessage.id,
},
};
}, 'Send message to AI');
}
catch (error) {
this.logger.error('Error sending message to AI:', error);
return {
content: '',
success: false,
error: `AI Error: ${error instanceof Error ? error.message : 'Unknown error'}`,
};
}
}
async testConnection() {
if (!this.isReady()) {
return false;
}
try {
this.logger.debug('Testing AI connection...');
const testResponse = await this.sendMessage('Xin chào! Đây là test connection. Vui lòng trả lời ngắn gọn.');
const isConnected = testResponse.success;
this.logger.debug('Connection test result:', { isConnected });
return isConnected;
}
catch (error) {
this.logger.error('Connection test failed:', error);
return false;
}
}
buildContext() {
const systemPrompt = this.getSystemPrompt();
if (this.history.length === 0) {
return systemPrompt;
}
const recentHistory = this.history.slice(-10);
let context = systemPrompt + '\n\nLịch sử hội thoại:\n';
recentHistory.forEach(msg => {
const role = msg.role === 'user' ? 'Người dùng' : 'TomiBot';
context += `${role}: ${msg.content}\n`;
});
context += '\nHãy trả lời tin nhắn mới nhất của người dùng:';
return context;
}
getSystemPrompt() {
return `Bạn là TomiBot, một AI chatbot thông minh và hữu ích được phát triển bằng Google Genkit.
Bạn luôn trả lời bằng tiếng Việt một cách lịch sự, thân thiện và chi tiết.
Bạn có thể giúp người dùng với nhiều chủ đề khác nhau như lập trình, học tập, giải trí, và cuộc sống hàng ngày.
Hãy luôn cung cấp thông tin chính xác và hữu ích.`;
}
async dispose() {
this.logger.info('Disposing Genkit AI service...');
try {
this.clearHistory();
this.ai = null;
this.initialized = false;
this.logger.info('Genkit AI service disposed successfully');
}
catch (error) {
this.logger.error('Error disposing Genkit service:', error);
throw error;
}
}
forceReinitialize() {
this.logger.info('Force reinitializing Genkit service...');
this.initialized = false;
this.ai = null;
const aiConfig = config_1.config.aiConfig;
this.config = {
...this.config,
apiKey: aiConfig.apiKey || '',
};
if (this.config.apiKey) {
this.initialize().catch(error => {
this.logger.error('Failed to reinitialize:', error);
});
}
}
getCapabilities() {
return [
'text-generation',
'conversation',
'multilingual',
'vietnamese-support',
'context-awareness',
'retry-mechanism',
];
}
updateConfig(newConfig) {
this.logger.info('Updating AI service configuration');
this.config = { ...this.config, ...newConfig };
if (newConfig.apiKey !== undefined) {
this.forceReinitialize();
}
}
getStatistics() {
return {
initialized: this.initialized,
ready: this.isReady(),
historyCount: this.history.length,
config: {
provider: this.config.provider,
model: this.config.model,
hasApiKey: !!this.config.apiKey,
maxTokens: this.config.maxTokens,
temperature: this.config.temperature,
},
capabilities: this.getCapabilities(),
};
}
}
exports.AIServiceImpl = AIServiceImpl;
//# sourceMappingURL=genkit.service.js.map