UNPKG

@restnfeel/agentc-starter-kit

Version:

한국어 기업용 CMS 모듈 - Task Master AI와 함께 빠르게 웹사이트를 구현할 수 있는 재사용 가능한 컴포넌트 시스템

351 lines (348 loc) 12 kB
import { createChatbotError } from '../../utils/index.js'; /** * @fileoverview Unified API wrapper for the RAG chatbot system * @module core/api/ChatbotAPI */ /** * Unified API class for the RAG chatbot system * Provides a clean, consistent interface for all chatbot operations */ class ChatbotAPI { constructor() { this.initialized = false; this.config = null; this.errorHandlers = []; } /** * Initialize the chatbot system */ async initialize(config, options) { try { this.validateConfig(config); this.config = config; // Initialize components based on options const results = await Promise.allSettled([ !(options === null || options === void 0 ? void 0 : options.skipVectorStore) ? this.initializeVectorStore() : Promise.resolve(), !(options === null || options === void 0 ? void 0 : options.skipLLM) ? this.initializeLLM() : Promise.resolve(), !(options === null || options === void 0 ? void 0 : options.skipStorage) ? this.initializeStorage() : Promise.resolve(), ]); // Check for failures const failures = results.filter((result) => result.status === "rejected"); if (failures.length > 0 && !(options === null || options === void 0 ? void 0 : options.retryOnFailure)) { throw new Error(`Initialization failed: ${failures.length} components failed`); } this.initialized = true; return { success: true, data: undefined, timestamp: new Date().toISOString(), }; } catch (error) { const chatbotError = this.createError("INITIALIZATION_FAILED", "Failed to initialize chatbot system", { originalError: error, config }); this.handleError(chatbotError); return { success: false, error: chatbotError.message, details: chatbotError.details, timestamp: new Date().toISOString(), }; } } /** * Reset the chatbot system */ async reset() { try { // Reset all components await Promise.allSettled([ this.resetVectorStore(), this.resetLLM(), this.resetStorage(), ]); this.initialized = false; this.config = null; return { success: true, data: undefined, timestamp: new Date().toISOString(), }; } catch (error) { const chatbotError = this.createError("RESET_FAILED", "Failed to reset chatbot system", { originalError: error }); this.handleError(chatbotError); return { success: false, error: chatbotError.message, details: chatbotError.details, timestamp: new Date().toISOString(), }; } } /** * Send a message and get response */ async sendMessage(content, conversationId, options) { try { this.ensureInitialized(); const message = { id: this.generateId("msg"), role: "user", content, timestamp: new Date(), }; // Process message through the system const response = (options === null || options === void 0 ? void 0 : options.useRAG) ? await this.processRAGMessage(message, conversationId) : await this.processDirectMessage(message, conversationId); return { success: true, data: response, timestamp: new Date().toISOString(), }; } catch (error) { const chatbotError = this.createError("MESSAGE_PROCESSING_FAILED", "Failed to process message", { originalError: error, content, conversationId }); this.handleError(chatbotError); return { success: false, error: chatbotError.message, details: chatbotError.details, timestamp: new Date().toISOString(), }; } } /** * Upload documents to the knowledge base */ async uploadDocuments(files, constraints, onProgress) { try { this.ensureInitialized(); // Validate files this.validateFiles(files, constraints); const documents = []; for (let i = 0; i < files.length; i++) { const file = files[i]; onProgress === null || onProgress === void 0 ? void 0 : onProgress((i / files.length) * 100); const document = await this.processFileUpload(file); documents.push(document); } onProgress === null || onProgress === void 0 ? void 0 : onProgress(100); return { success: true, data: documents, timestamp: new Date().toISOString(), }; } catch (error) { const chatbotError = this.createError("DOCUMENT_UPLOAD_FAILED", "Failed to upload documents", { originalError: error, fileCount: files.length }); this.handleError(chatbotError); return { success: false, error: chatbotError.message, details: chatbotError.details, timestamp: new Date().toISOString(), }; } } /** * Search documents in the knowledge base */ async searchDocuments(query, options) { try { this.ensureInitialized(); const startTime = Date.now(); const results = await this.performSearch(query, options); const searchTime = Date.now() - startTime; return { success: true, data: results, timestamp: new Date().toISOString(), }; } catch (error) { const chatbotError = this.createError("SEARCH_FAILED", "Failed to search documents", { originalError: error, query, options }); this.handleError(chatbotError); return { success: false, error: chatbotError.message, details: chatbotError.details, timestamp: new Date().toISOString(), }; } } /** * Get system health status */ async getHealthStatus() { try { const health = await this.checkSystemHealth(); return { success: true, data: health, timestamp: new Date().toISOString(), }; } catch (error) { const chatbotError = this.createError("HEALTH_CHECK_FAILED", "Failed to check system health", { originalError: error }); this.handleError(chatbotError); return { success: false, error: chatbotError.message, details: chatbotError.details, timestamp: new Date().toISOString(), }; } } /** * Add error handler */ onError(handler) { this.errorHandlers.push(handler); // Return unsubscribe function return () => { const index = this.errorHandlers.indexOf(handler); if (index > -1) { this.errorHandlers.splice(index, 1); } }; } /** * Get current configuration */ getConfig() { return this.config; } /** * Check if system is initialized */ isInitialized() { return this.initialized; } // Private helper methods ensureInitialized() { if (!this.initialized) { throw new Error("Chatbot system is not initialized. Call initialize() first."); } } validateConfig(config) { if (!config) { throw new Error("Configuration is required"); } // Add more specific validation logic here if (!config.llm) { throw new Error("LLM configuration is required"); } } validateFiles(files, constraints) { if (!files || files.length === 0) { throw new Error("No files provided"); } if (constraints) { for (const file of files) { if (file.size > constraints.maxSize) { throw new Error(`File ${file.name} exceeds maximum size of ${constraints.maxSize} bytes`); } if (constraints.allowedTypes && !constraints.allowedTypes.includes(file.type)) { throw new Error(`File type ${file.type} is not allowed`); } } } } createError(code, message, details) { return createChatbotError(code, message, details); } handleError(error) { this.errorHandlers.forEach((handler) => { try { handler(error); } catch (handlerError) { console.error("Error in error handler:", handlerError); } }); } generateId(prefix) { return `${prefix}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; } // Placeholder methods for implementation async initializeVectorStore() { // Implementation will be connected to existing vector store service console.log("Initializing vector store..."); } async initializeLLM() { // Implementation will be connected to existing LLM service console.log("Initializing LLM..."); } async initializeStorage() { // Implementation will be connected to existing storage service console.log("Initializing storage..."); } async resetVectorStore() { console.log("Resetting vector store..."); } async resetLLM() { console.log("Resetting LLM..."); } async resetStorage() { console.log("Resetting storage..."); } async processRAGMessage(message, conversationId) { // Implementation will use existing RAG chain service return { id: this.generateId("msg"), role: "assistant", content: "RAG response placeholder", timestamp: new Date(), }; } async processDirectMessage(message, conversationId) { // Implementation will use direct LLM service return { id: this.generateId("msg"), role: "assistant", content: "Direct response placeholder", timestamp: new Date(), }; } async processFileUpload(file) { // Implementation will use existing storage service return { id: this.generateId("doc"), title: file.name, content: "", metadata: { source: file.name, uploadedAt: new Date(), size: file.size, type: file.type, description: `Uploaded file: ${file.name}`, }, status: "processing", }; } async performSearch(query, options) { // Implementation will use existing vector store search return []; } async checkSystemHealth() { // Implementation will check all components return { overall: true, components: { vectorStore: true, llm: true, storage: true, }, }; } } /** * Default singleton instance */ const chatbotAPI = new ChatbotAPI(); export { ChatbotAPI, chatbotAPI, ChatbotAPI as default }; //# sourceMappingURL=ChatbotAPI.js.map