# RAG Chatbot Library

A comprehensive React-based chatbot library with RAG (Retrieval Augmented Generation) capabilities, built for modern web applications.

## Features

- 🤖 **RAG-powered AI Chat** - Intelligent responses with document-based knowledge
- 📚 **Document Management** - Upload and manage various document formats (PDF, DOCX, TXT, etc.)
- 🔍 **Semantic Search** - Vector-based document search and retrieval
- 🌐 **Multi-language Support** - Built-in internationalization (i18n)
- 🎨 **Customizable UI** - Flexible theming and styling options
- 📱 **Responsive Design** - Works on desktop and mobile devices
- 🔧 **Admin Tools** - Knowledge management and configuration interfaces
- 🧪 **Well Tested** - Comprehensive test coverage with Jest and React Testing Library
- 📦 **TypeScript** - Full type safety and excellent developer experience

## Installation

```bash
npm install @restnfeel/agentc-starter-kit
```

### Peer Dependencies

Make sure you have the following peer dependencies installed:

```bash
npm install react react-dom next @prisma/client @supabase/supabase-js
```

## Quick Start

### 1. Basic Setup

```tsx
import {
  ChatbotProvider,
  ChatbotWidget,
} from "@restnfeel/agentc-starter-kit/chatbot";

function App() {
  return (
    <ChatbotProvider>
      <div className="app">
        {/* Your app content */}
        <ChatbotWidget />
      </div>
    </ChatbotProvider>
  );
}
```

### 2. With Configuration

```tsx
import {
  ChatbotProvider,
  ChatbotWidget,
} from "@restnfeel/agentc-starter-kit/chatbot";

const chatbotConfig = {
  llm: {
    provider: "openai",
    model: "gpt-3.5-turbo",
    apiKey: process.env.OPENAI_API_KEY,
    maxTokens: 1000,
    temperature: 0.7,
  },
  vectorStore: {
    provider: "supabase",
    dimensions: 1536,
  },
  storage: {
    provider: "supabase",
    bucket: "documents",
  },
};

function App() {
  return (
    <ChatbotProvider config={chatbotConfig}>
      <ChatbotWidget
        theme={{
          primaryColor: "#007bff",
          mode: "light",
        }}
        position="bottom-right"
      />
    </ChatbotProvider>
  );
}
```

## Components

### Client Components

#### ChatbotWidget

The main chatbot interface that users interact with.

```tsx
import { ChatbotWidget } from "@restnfeel/agentc-starter-kit/chatbot/client";

<ChatbotWidget
  theme={{
    primaryColor: "#007bff",
    mode: "light",
  }}
  position="bottom-right"
  showSuggestedQuestions={true}
  placeholder="Ask me anything..."
/>;
```

#### RAGChat

A full-featured chat interface with document support.

```tsx
import { RAGChat } from "@restnfeel/agentc-starter-kit/chatbot/client";

<RAGChat
  conversationId="conversation-123"
  showDocumentSearch={true}
  showUpload={true}
  maxHeight="600px"
/>;
```

#### FloatingChatButton

A floating action button to open the chat interface.

```tsx
import { FloatingChatButton } from "@restnfeel/agentc-starter-kit/chatbot/client";

<FloatingChatButton
  position="bottom-right"
  size="md"
  icon={<MessageCircle />}
/>;
```

### Admin Components

#### KnowledgeManagement

Admin interface for managing documents and knowledge base.

```tsx
import { KnowledgeManagement } from "@restnfeel/agentc-starter-kit/chatbot/admin";

<KnowledgeManagement
  showUpload={true}
  showBulkActions={true}
  allowedFileTypes={["pdf", "docx", "txt"]}
  maxFileSize="10MB"
/>;
```

#### RAGManager

Advanced admin interface for RAG system configuration.

```tsx
import { RAGManager } from "@restnfeel/agentc-starter-kit/chatbot/admin";

<RAGManager
  showAnalytics={true}
  showConfiguration={true}
  enableBatchProcessing={true}
/>;
```

## Hooks

### useChatbot

Main hook for accessing chatbot functionality.

```tsx
import { useChatbot } from "@restnfeel/agentc-starter-kit/chatbot/hooks";

function ChatComponent() {
  const {
    isInitialized,
    sendMessage,
    uploadDocument,
    conversations,
    currentConversation,
    isProcessing,
    lastError,
  } = useChatbot();

  const handleSendMessage = async (content: string) => {
    try {
      await sendMessage(content);
    } catch (error) {
      console.error("Failed to send message:", error);
    }
  };

  return <div>{/* Chat UI */}</div>;
}
```

### useDocuments

Hook for document management.

```tsx
import { useDocuments } from "@restnfeel/agentc-starter-kit/chatbot/hooks";

function DocumentManager() {
  const {
    documents,
    uploadDocument,
    deleteDocument,
    searchDocuments,
    isLoading,
  } = useDocuments();

  return <div>{/* Document management UI */}</div>;
}
```

### useErrorHandler

Hook for centralized error handling.

```tsx
import { useErrorHandler } from "@restnfeel/agentc-starter-kit/chatbot/hooks";

function ChatComponent() {
  const { error, hasError, clearError, handleError, getErrorMessage } =
    useErrorHandler();

  if (hasError) {
    return (
      <div className="error">
        {getErrorMessage()}
        <button onClick={clearError}>Dismiss</button>
      </div>
    );
  }

  return <div>{/* Normal UI */}</div>;
}
```

## API

### ChatbotAPI

Direct API access for advanced use cases.

```tsx
import { ChatbotAPI } from "@restnfeel/agentc-starter-kit/chatbot/core";

const api = new ChatbotAPI();

// Initialize
await api.initialize({
  llm: { provider: "openai", apiKey: "your-key" },
  vectorStore: { provider: "memory" },
});

// Send message
const response = await api.sendMessage("Hello", "conversation-id");

// Upload document
const file = new File(["content"], "document.txt");
const document = await api.uploadDocument(file);

// Search documents
const results = await api.searchSimilarDocuments("query");
```

## Configuration

### LLM Providers

#### OpenAI

```typescript
{
  llm: {
    provider: 'openai',
    model: 'gpt-3.5-turbo',
    apiKey: process.env.OPENAI_API_KEY,
    maxTokens: 1000,
    temperature: 0.7,
  }
}
```

#### Anthropic

```typescript
{
  llm: {
    provider: 'anthropic',
    model: 'claude-3-sonnet-20240229',
    apiKey: process.env.ANTHROPIC_API_KEY,
    maxTokens: 1000,
  }
}
```

### Vector Store Providers

#### Supabase

```typescript
{
  vectorStore: {
    provider: 'supabase',
    url: process.env.SUPABASE_URL,
    apiKey: process.env.SUPABASE_ANON_KEY,
    dimensions: 1536,
  }
}
```

#### Memory (Development)

```typescript
{
  vectorStore: {
    provider: 'memory',
    dimensions: 1536,
  }
}
```

## Styling

### CSS Variables

The library uses CSS variables for theming:

```css
:root {
  --chatbot-primary-color: #007bff;
  --chatbot-background-color: #ffffff;
  --chatbot-text-color: #333333;
  --chatbot-border-color: #e0e0e0;
  --chatbot-border-radius: 8px;
  --chatbot-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
```

### Custom Themes

```tsx
import { useTheme } from "@restnfeel/agentc-starter-kit/chatbot/hooks";

function ThemedChat() {
  const { theme, setTheme } = useTheme();

  const applyDarkTheme = () => {
    setTheme({
      mode: "dark",
      backgroundColor: "#1a1a1a",
      textColor: "#ffffff",
      primaryColor: "#3b82f6",
    });
  };

  return <div>{/* Chat UI */}</div>;
}
```

## Internationalization

### Built-in Languages

- English (en)
- Korean (ko)
- Japanese (ja)
- Chinese (zh)

### Usage

```tsx
import { useI18n } from "@restnfeel/agentc-starter-kit/chatbot/hooks";

function ChatComponent() {
  const { language, setLanguage, t } = useI18n();

  return (
    <div>
      <button onClick={() => setLanguage("ko")}>한국어</button>
      <p>{t("chatbot.welcome")}</p>
    </div>
  );
}
```

## Testing

### Running Tests

```bash
# Run all chatbot tests
npm run test:chatbot

# Run tests in watch mode
npm run test:chatbot:watch

# Generate coverage report
npm run test:chatbot:coverage
```

### Custom Matchers

The library includes custom Jest matchers:

```javascript
expect(response).toBeValidChatbotResponse();
```

## Building

### Library Build

```bash
# Build the library
npm run build:lib

# Build TypeScript declarations
npm run build:types

# Build everything
npm run build:package
```

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new functionality
5. Ensure all tests pass
6. Submit a pull request

## License

MIT License - see the [LICENSE](LICENSE) file for details.

## Support

For questions and support:

- 📧 Email: contact@restnfeel.com
- 🐛 Issues: [GitHub Issues](https://github.com/restnfeel/agentc-starter-kit/issues)
- 📖 Documentation: [Full Documentation](https://docs.restnfeel.com)
