/** * @fileoverview Advanced usage examples for the RAG Chatbot Library */ "use client"; import React, { useState, useEffect } from "react"; import { ChatbotProvider, RAGChat, useChatbot, useDocuments, useTheme, useI18n, useErrorHandler, } from "../index"; /** * Advanced chatbot with custom configuration */ export function AdvancedChatbotExample() { const config = { llm: { provider: "openai" as const, model: "gpt-4", apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY || "", maxTokens: 2000, temperature: 0.8, systemPrompt: "You are a helpful AI assistant with access to a knowledge base. Provide accurate and detailed responses based on the available documents.", }, vectorStore: { provider: "supabase" as const, url: process.env.NEXT_PUBLIC_SUPABASE_URL || "", apiKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || "", dimensions: 1536, }, storage: { provider: "supabase" as const, bucket: "chatbot-documents", }, }; const handleError = (error: any) => { console.error("Chatbot Error:", error); // Send to error tracking service }; return (

Advanced RAG Chatbot

{/* Settings Panel */}
{/* Main Chat Interface */}
{/* Analytics Panel */}
); } /** * Settings panel for theme and language customization */ function SettingsPanel() { const { theme, setTheme, toggleMode } = useTheme(); const { language, setLanguage, t } = useI18n(); const { clearError } = useErrorHandler(); return (

{t("settings.title")}

{/* Theme Settings */}

{t("settings.theme")}

{["#007bff", "#28a745", "#dc3545", "#ffc107", "#6f42c1"].map( (color) => (
{/* Language Settings */}

{t("settings.language")}

{/* Actions */}
); } /** * Analytics panel showing conversation and document stats */ function AnalyticsPanel() { const { conversations, documents } = useChatbot(); const [stats, setStats] = useState({ totalMessages: 0, totalDocuments: documents.length, avgResponseTime: 0, }); useEffect(() => { const totalMessages = conversations.reduce( (acc, conv) => acc + conv.messages.length, 0 ); setStats((prev) => ({ ...prev, totalMessages, totalDocuments: documents.length, })); }, [conversations, documents]); return (

Analytics

{/* Stats Cards */}
{conversations.length}
Total Conversations
{stats.totalMessages}
Total Messages
{stats.totalDocuments}
Documents in KB
{/* Recent Activity */}

Recent Activity

{conversations.slice(0, 5).map((conv) => (
{conv.title}
{conv.messages.length} messages •{" "} {conv.updatedAt.toLocaleDateString()}
))}
); } /** * Custom hook for chatbot analytics */ export function useChatbotAnalytics() { const { conversations, documents } = useChatbot(); const [analytics, setAnalytics] = useState({ conversationCount: 0, messageCount: 0, documentCount: 0, avgMessagesPerConversation: 0, mostActiveDay: "", topicsDiscussed: [] as string[], }); useEffect(() => { const messageCount = conversations.reduce( (acc, conv) => acc + conv.messages.length, 0 ); const avgMessages = conversations.length > 0 ? messageCount / conversations.length : 0; // Analyze conversation topics (simplified) const topics = conversations .map((conv) => conv.title) .filter((title) => title && title !== "New Conversation") .slice(0, 5); setAnalytics({ conversationCount: conversations.length, messageCount, documentCount: documents.length, avgMessagesPerConversation: Math.round(avgMessages * 10) / 10, mostActiveDay: "Today", // Simplified topicsDiscussed: topics, }); }, [conversations, documents]); return analytics; } /** * Example with custom document processing */ export function CustomDocumentProcessingExample() { const { uploadDocument } = useDocuments(); const [processing, setProcessing] = useState(false); const handleCustomUpload = async (file: File) => { setProcessing(true); try { // Custom preprocessing const processedFile = await preprocessDocument(file); // Upload with custom metadata await uploadDocument(processedFile, { title: file.name.replace(/\.[^/.]+$/, ""), tags: extractTags(file.name), description: `Processed document: ${file.name}`, uploadedAt: new Date(), }); } catch (error) { console.error("Custom upload failed:", error); } finally { setProcessing(false); } }; return (

Custom Document Processing

e.target.files?.[0] && handleCustomUpload(e.target.files[0]) } className="mb-4" disabled={processing} /> {processing && (
Processing document...
)}
); } // Helper functions async function preprocessDocument(file: File): Promise { // Add custom preprocessing logic here return file; } function extractTags(filename: string): string[] { // Extract tags from filename const parts = filename.toLowerCase().split(/[-_\s]/); return parts.filter((part) => part.length > 2).slice(0, 3); }